Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

20777 linhas
566KB

  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() :
  9. typeof define === 'function' && define.amd ? define(factory) :
  10. (global = global || self, global.Chart = factory());
  11. }(this, (function () { 'use strict';
  12. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  13. function commonjsRequire () {
  14. throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
  15. }
  16. function createCommonjsModule(fn, module) {
  17. return module = { exports: {} }, fn(module, module.exports), module.exports;
  18. }
  19. function getCjsExportFromNamespace (n) {
  20. return n && n['default'] || n;
  21. }
  22. var colorName = {
  23. "aliceblue": [240, 248, 255],
  24. "antiquewhite": [250, 235, 215],
  25. "aqua": [0, 255, 255],
  26. "aquamarine": [127, 255, 212],
  27. "azure": [240, 255, 255],
  28. "beige": [245, 245, 220],
  29. "bisque": [255, 228, 196],
  30. "black": [0, 0, 0],
  31. "blanchedalmond": [255, 235, 205],
  32. "blue": [0, 0, 255],
  33. "blueviolet": [138, 43, 226],
  34. "brown": [165, 42, 42],
  35. "burlywood": [222, 184, 135],
  36. "cadetblue": [95, 158, 160],
  37. "chartreuse": [127, 255, 0],
  38. "chocolate": [210, 105, 30],
  39. "coral": [255, 127, 80],
  40. "cornflowerblue": [100, 149, 237],
  41. "cornsilk": [255, 248, 220],
  42. "crimson": [220, 20, 60],
  43. "cyan": [0, 255, 255],
  44. "darkblue": [0, 0, 139],
  45. "darkcyan": [0, 139, 139],
  46. "darkgoldenrod": [184, 134, 11],
  47. "darkgray": [169, 169, 169],
  48. "darkgreen": [0, 100, 0],
  49. "darkgrey": [169, 169, 169],
  50. "darkkhaki": [189, 183, 107],
  51. "darkmagenta": [139, 0, 139],
  52. "darkolivegreen": [85, 107, 47],
  53. "darkorange": [255, 140, 0],
  54. "darkorchid": [153, 50, 204],
  55. "darkred": [139, 0, 0],
  56. "darksalmon": [233, 150, 122],
  57. "darkseagreen": [143, 188, 143],
  58. "darkslateblue": [72, 61, 139],
  59. "darkslategray": [47, 79, 79],
  60. "darkslategrey": [47, 79, 79],
  61. "darkturquoise": [0, 206, 209],
  62. "darkviolet": [148, 0, 211],
  63. "deeppink": [255, 20, 147],
  64. "deepskyblue": [0, 191, 255],
  65. "dimgray": [105, 105, 105],
  66. "dimgrey": [105, 105, 105],
  67. "dodgerblue": [30, 144, 255],
  68. "firebrick": [178, 34, 34],
  69. "floralwhite": [255, 250, 240],
  70. "forestgreen": [34, 139, 34],
  71. "fuchsia": [255, 0, 255],
  72. "gainsboro": [220, 220, 220],
  73. "ghostwhite": [248, 248, 255],
  74. "gold": [255, 215, 0],
  75. "goldenrod": [218, 165, 32],
  76. "gray": [128, 128, 128],
  77. "green": [0, 128, 0],
  78. "greenyellow": [173, 255, 47],
  79. "grey": [128, 128, 128],
  80. "honeydew": [240, 255, 240],
  81. "hotpink": [255, 105, 180],
  82. "indianred": [205, 92, 92],
  83. "indigo": [75, 0, 130],
  84. "ivory": [255, 255, 240],
  85. "khaki": [240, 230, 140],
  86. "lavender": [230, 230, 250],
  87. "lavenderblush": [255, 240, 245],
  88. "lawngreen": [124, 252, 0],
  89. "lemonchiffon": [255, 250, 205],
  90. "lightblue": [173, 216, 230],
  91. "lightcoral": [240, 128, 128],
  92. "lightcyan": [224, 255, 255],
  93. "lightgoldenrodyellow": [250, 250, 210],
  94. "lightgray": [211, 211, 211],
  95. "lightgreen": [144, 238, 144],
  96. "lightgrey": [211, 211, 211],
  97. "lightpink": [255, 182, 193],
  98. "lightsalmon": [255, 160, 122],
  99. "lightseagreen": [32, 178, 170],
  100. "lightskyblue": [135, 206, 250],
  101. "lightslategray": [119, 136, 153],
  102. "lightslategrey": [119, 136, 153],
  103. "lightsteelblue": [176, 196, 222],
  104. "lightyellow": [255, 255, 224],
  105. "lime": [0, 255, 0],
  106. "limegreen": [50, 205, 50],
  107. "linen": [250, 240, 230],
  108. "magenta": [255, 0, 255],
  109. "maroon": [128, 0, 0],
  110. "mediumaquamarine": [102, 205, 170],
  111. "mediumblue": [0, 0, 205],
  112. "mediumorchid": [186, 85, 211],
  113. "mediumpurple": [147, 112, 219],
  114. "mediumseagreen": [60, 179, 113],
  115. "mediumslateblue": [123, 104, 238],
  116. "mediumspringgreen": [0, 250, 154],
  117. "mediumturquoise": [72, 209, 204],
  118. "mediumvioletred": [199, 21, 133],
  119. "midnightblue": [25, 25, 112],
  120. "mintcream": [245, 255, 250],
  121. "mistyrose": [255, 228, 225],
  122. "moccasin": [255, 228, 181],
  123. "navajowhite": [255, 222, 173],
  124. "navy": [0, 0, 128],
  125. "oldlace": [253, 245, 230],
  126. "olive": [128, 128, 0],
  127. "olivedrab": [107, 142, 35],
  128. "orange": [255, 165, 0],
  129. "orangered": [255, 69, 0],
  130. "orchid": [218, 112, 214],
  131. "palegoldenrod": [238, 232, 170],
  132. "palegreen": [152, 251, 152],
  133. "paleturquoise": [175, 238, 238],
  134. "palevioletred": [219, 112, 147],
  135. "papayawhip": [255, 239, 213],
  136. "peachpuff": [255, 218, 185],
  137. "peru": [205, 133, 63],
  138. "pink": [255, 192, 203],
  139. "plum": [221, 160, 221],
  140. "powderblue": [176, 224, 230],
  141. "purple": [128, 0, 128],
  142. "rebeccapurple": [102, 51, 153],
  143. "red": [255, 0, 0],
  144. "rosybrown": [188, 143, 143],
  145. "royalblue": [65, 105, 225],
  146. "saddlebrown": [139, 69, 19],
  147. "salmon": [250, 128, 114],
  148. "sandybrown": [244, 164, 96],
  149. "seagreen": [46, 139, 87],
  150. "seashell": [255, 245, 238],
  151. "sienna": [160, 82, 45],
  152. "silver": [192, 192, 192],
  153. "skyblue": [135, 206, 235],
  154. "slateblue": [106, 90, 205],
  155. "slategray": [112, 128, 144],
  156. "slategrey": [112, 128, 144],
  157. "snow": [255, 250, 250],
  158. "springgreen": [0, 255, 127],
  159. "steelblue": [70, 130, 180],
  160. "tan": [210, 180, 140],
  161. "teal": [0, 128, 128],
  162. "thistle": [216, 191, 216],
  163. "tomato": [255, 99, 71],
  164. "turquoise": [64, 224, 208],
  165. "violet": [238, 130, 238],
  166. "wheat": [245, 222, 179],
  167. "white": [255, 255, 255],
  168. "whitesmoke": [245, 245, 245],
  169. "yellow": [255, 255, 0],
  170. "yellowgreen": [154, 205, 50]
  171. };
  172. var conversions = createCommonjsModule(function (module) {
  173. /* MIT license */
  174. // NOTE: conversions should only return primitive values (i.e. arrays, or
  175. // values that give correct `typeof` results).
  176. // do not use box values types (i.e. Number(), String(), etc.)
  177. var reverseKeywords = {};
  178. for (var key in colorName) {
  179. if (colorName.hasOwnProperty(key)) {
  180. reverseKeywords[colorName[key]] = key;
  181. }
  182. }
  183. var convert = module.exports = {
  184. rgb: {channels: 3, labels: 'rgb'},
  185. hsl: {channels: 3, labels: 'hsl'},
  186. hsv: {channels: 3, labels: 'hsv'},
  187. hwb: {channels: 3, labels: 'hwb'},
  188. cmyk: {channels: 4, labels: 'cmyk'},
  189. xyz: {channels: 3, labels: 'xyz'},
  190. lab: {channels: 3, labels: 'lab'},
  191. lch: {channels: 3, labels: 'lch'},
  192. hex: {channels: 1, labels: ['hex']},
  193. keyword: {channels: 1, labels: ['keyword']},
  194. ansi16: {channels: 1, labels: ['ansi16']},
  195. ansi256: {channels: 1, labels: ['ansi256']},
  196. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  197. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  198. gray: {channels: 1, labels: ['gray']}
  199. };
  200. // hide .channels and .labels properties
  201. for (var model in convert) {
  202. if (convert.hasOwnProperty(model)) {
  203. if (!('channels' in convert[model])) {
  204. throw new Error('missing channels property: ' + model);
  205. }
  206. if (!('labels' in convert[model])) {
  207. throw new Error('missing channel labels property: ' + model);
  208. }
  209. if (convert[model].labels.length !== convert[model].channels) {
  210. throw new Error('channel and label counts mismatch: ' + model);
  211. }
  212. var channels = convert[model].channels;
  213. var labels = convert[model].labels;
  214. delete convert[model].channels;
  215. delete convert[model].labels;
  216. Object.defineProperty(convert[model], 'channels', {value: channels});
  217. Object.defineProperty(convert[model], 'labels', {value: labels});
  218. }
  219. }
  220. convert.rgb.hsl = function (rgb) {
  221. var r = rgb[0] / 255;
  222. var g = rgb[1] / 255;
  223. var b = rgb[2] / 255;
  224. var min = Math.min(r, g, b);
  225. var max = Math.max(r, g, b);
  226. var delta = max - min;
  227. var h;
  228. var s;
  229. var l;
  230. if (max === min) {
  231. h = 0;
  232. } else if (r === max) {
  233. h = (g - b) / delta;
  234. } else if (g === max) {
  235. h = 2 + (b - r) / delta;
  236. } else if (b === max) {
  237. h = 4 + (r - g) / delta;
  238. }
  239. h = Math.min(h * 60, 360);
  240. if (h < 0) {
  241. h += 360;
  242. }
  243. l = (min + max) / 2;
  244. if (max === min) {
  245. s = 0;
  246. } else if (l <= 0.5) {
  247. s = delta / (max + min);
  248. } else {
  249. s = delta / (2 - max - min);
  250. }
  251. return [h, s * 100, l * 100];
  252. };
  253. convert.rgb.hsv = function (rgb) {
  254. var rdif;
  255. var gdif;
  256. var bdif;
  257. var h;
  258. var s;
  259. var r = rgb[0] / 255;
  260. var g = rgb[1] / 255;
  261. var b = rgb[2] / 255;
  262. var v = Math.max(r, g, b);
  263. var diff = v - Math.min(r, g, b);
  264. var diffc = function (c) {
  265. return (v - c) / 6 / diff + 1 / 2;
  266. };
  267. if (diff === 0) {
  268. h = s = 0;
  269. } else {
  270. s = diff / v;
  271. rdif = diffc(r);
  272. gdif = diffc(g);
  273. bdif = diffc(b);
  274. if (r === v) {
  275. h = bdif - gdif;
  276. } else if (g === v) {
  277. h = (1 / 3) + rdif - bdif;
  278. } else if (b === v) {
  279. h = (2 / 3) + gdif - rdif;
  280. }
  281. if (h < 0) {
  282. h += 1;
  283. } else if (h > 1) {
  284. h -= 1;
  285. }
  286. }
  287. return [
  288. h * 360,
  289. s * 100,
  290. v * 100
  291. ];
  292. };
  293. convert.rgb.hwb = function (rgb) {
  294. var r = rgb[0];
  295. var g = rgb[1];
  296. var b = rgb[2];
  297. var h = convert.rgb.hsl(rgb)[0];
  298. var w = 1 / 255 * Math.min(r, Math.min(g, b));
  299. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  300. return [h, w * 100, b * 100];
  301. };
  302. convert.rgb.cmyk = function (rgb) {
  303. var r = rgb[0] / 255;
  304. var g = rgb[1] / 255;
  305. var b = rgb[2] / 255;
  306. var c;
  307. var m;
  308. var y;
  309. var k;
  310. k = Math.min(1 - r, 1 - g, 1 - b);
  311. c = (1 - r - k) / (1 - k) || 0;
  312. m = (1 - g - k) / (1 - k) || 0;
  313. y = (1 - b - k) / (1 - k) || 0;
  314. return [c * 100, m * 100, y * 100, k * 100];
  315. };
  316. /**
  317. * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  318. * */
  319. function comparativeDistance(x, y) {
  320. return (
  321. Math.pow(x[0] - y[0], 2) +
  322. Math.pow(x[1] - y[1], 2) +
  323. Math.pow(x[2] - y[2], 2)
  324. );
  325. }
  326. convert.rgb.keyword = function (rgb) {
  327. var reversed = reverseKeywords[rgb];
  328. if (reversed) {
  329. return reversed;
  330. }
  331. var currentClosestDistance = Infinity;
  332. var currentClosestKeyword;
  333. for (var keyword in colorName) {
  334. if (colorName.hasOwnProperty(keyword)) {
  335. var value = colorName[keyword];
  336. // Compute comparative distance
  337. var distance = comparativeDistance(rgb, value);
  338. // Check if its less, if so set as closest
  339. if (distance < currentClosestDistance) {
  340. currentClosestDistance = distance;
  341. currentClosestKeyword = keyword;
  342. }
  343. }
  344. }
  345. return currentClosestKeyword;
  346. };
  347. convert.keyword.rgb = function (keyword) {
  348. return colorName[keyword];
  349. };
  350. convert.rgb.xyz = function (rgb) {
  351. var r = rgb[0] / 255;
  352. var g = rgb[1] / 255;
  353. var b = rgb[2] / 255;
  354. // assume sRGB
  355. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  356. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  357. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  358. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  359. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  360. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  361. return [x * 100, y * 100, z * 100];
  362. };
  363. convert.rgb.lab = function (rgb) {
  364. var xyz = convert.rgb.xyz(rgb);
  365. var x = xyz[0];
  366. var y = xyz[1];
  367. var z = xyz[2];
  368. var l;
  369. var a;
  370. var b;
  371. x /= 95.047;
  372. y /= 100;
  373. z /= 108.883;
  374. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  375. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  376. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  377. l = (116 * y) - 16;
  378. a = 500 * (x - y);
  379. b = 200 * (y - z);
  380. return [l, a, b];
  381. };
  382. convert.hsl.rgb = function (hsl) {
  383. var h = hsl[0] / 360;
  384. var s = hsl[1] / 100;
  385. var l = hsl[2] / 100;
  386. var t1;
  387. var t2;
  388. var t3;
  389. var rgb;
  390. var val;
  391. if (s === 0) {
  392. val = l * 255;
  393. return [val, val, val];
  394. }
  395. if (l < 0.5) {
  396. t2 = l * (1 + s);
  397. } else {
  398. t2 = l + s - l * s;
  399. }
  400. t1 = 2 * l - t2;
  401. rgb = [0, 0, 0];
  402. for (var i = 0; i < 3; i++) {
  403. t3 = h + 1 / 3 * -(i - 1);
  404. if (t3 < 0) {
  405. t3++;
  406. }
  407. if (t3 > 1) {
  408. t3--;
  409. }
  410. if (6 * t3 < 1) {
  411. val = t1 + (t2 - t1) * 6 * t3;
  412. } else if (2 * t3 < 1) {
  413. val = t2;
  414. } else if (3 * t3 < 2) {
  415. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  416. } else {
  417. val = t1;
  418. }
  419. rgb[i] = val * 255;
  420. }
  421. return rgb;
  422. };
  423. convert.hsl.hsv = function (hsl) {
  424. var h = hsl[0];
  425. var s = hsl[1] / 100;
  426. var l = hsl[2] / 100;
  427. var smin = s;
  428. var lmin = Math.max(l, 0.01);
  429. var sv;
  430. var v;
  431. l *= 2;
  432. s *= (l <= 1) ? l : 2 - l;
  433. smin *= lmin <= 1 ? lmin : 2 - lmin;
  434. v = (l + s) / 2;
  435. sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  436. return [h, sv * 100, v * 100];
  437. };
  438. convert.hsv.rgb = function (hsv) {
  439. var h = hsv[0] / 60;
  440. var s = hsv[1] / 100;
  441. var v = hsv[2] / 100;
  442. var hi = Math.floor(h) % 6;
  443. var f = h - Math.floor(h);
  444. var p = 255 * v * (1 - s);
  445. var q = 255 * v * (1 - (s * f));
  446. var t = 255 * v * (1 - (s * (1 - f)));
  447. v *= 255;
  448. switch (hi) {
  449. case 0:
  450. return [v, t, p];
  451. case 1:
  452. return [q, v, p];
  453. case 2:
  454. return [p, v, t];
  455. case 3:
  456. return [p, q, v];
  457. case 4:
  458. return [t, p, v];
  459. case 5:
  460. return [v, p, q];
  461. }
  462. };
  463. convert.hsv.hsl = function (hsv) {
  464. var h = hsv[0];
  465. var s = hsv[1] / 100;
  466. var v = hsv[2] / 100;
  467. var vmin = Math.max(v, 0.01);
  468. var lmin;
  469. var sl;
  470. var l;
  471. l = (2 - s) * v;
  472. lmin = (2 - s) * vmin;
  473. sl = s * vmin;
  474. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  475. sl = sl || 0;
  476. l /= 2;
  477. return [h, sl * 100, l * 100];
  478. };
  479. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  480. convert.hwb.rgb = function (hwb) {
  481. var h = hwb[0] / 360;
  482. var wh = hwb[1] / 100;
  483. var bl = hwb[2] / 100;
  484. var ratio = wh + bl;
  485. var i;
  486. var v;
  487. var f;
  488. var n;
  489. // wh + bl cant be > 1
  490. if (ratio > 1) {
  491. wh /= ratio;
  492. bl /= ratio;
  493. }
  494. i = Math.floor(6 * h);
  495. v = 1 - bl;
  496. f = 6 * h - i;
  497. if ((i & 0x01) !== 0) {
  498. f = 1 - f;
  499. }
  500. n = wh + f * (v - wh); // linear interpolation
  501. var r;
  502. var g;
  503. var b;
  504. switch (i) {
  505. default:
  506. case 6:
  507. case 0: r = v; g = n; b = wh; break;
  508. case 1: r = n; g = v; b = wh; break;
  509. case 2: r = wh; g = v; b = n; break;
  510. case 3: r = wh; g = n; b = v; break;
  511. case 4: r = n; g = wh; b = v; break;
  512. case 5: r = v; g = wh; b = n; break;
  513. }
  514. return [r * 255, g * 255, b * 255];
  515. };
  516. convert.cmyk.rgb = function (cmyk) {
  517. var c = cmyk[0] / 100;
  518. var m = cmyk[1] / 100;
  519. var y = cmyk[2] / 100;
  520. var k = cmyk[3] / 100;
  521. var r;
  522. var g;
  523. var b;
  524. r = 1 - Math.min(1, c * (1 - k) + k);
  525. g = 1 - Math.min(1, m * (1 - k) + k);
  526. b = 1 - Math.min(1, y * (1 - k) + k);
  527. return [r * 255, g * 255, b * 255];
  528. };
  529. convert.xyz.rgb = function (xyz) {
  530. var x = xyz[0] / 100;
  531. var y = xyz[1] / 100;
  532. var z = xyz[2] / 100;
  533. var r;
  534. var g;
  535. var b;
  536. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  537. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  538. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  539. // assume sRGB
  540. r = r > 0.0031308
  541. ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  542. : r * 12.92;
  543. g = g > 0.0031308
  544. ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  545. : g * 12.92;
  546. b = b > 0.0031308
  547. ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  548. : b * 12.92;
  549. r = Math.min(Math.max(0, r), 1);
  550. g = Math.min(Math.max(0, g), 1);
  551. b = Math.min(Math.max(0, b), 1);
  552. return [r * 255, g * 255, b * 255];
  553. };
  554. convert.xyz.lab = function (xyz) {
  555. var x = xyz[0];
  556. var y = xyz[1];
  557. var z = xyz[2];
  558. var l;
  559. var a;
  560. var b;
  561. x /= 95.047;
  562. y /= 100;
  563. z /= 108.883;
  564. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  565. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  566. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  567. l = (116 * y) - 16;
  568. a = 500 * (x - y);
  569. b = 200 * (y - z);
  570. return [l, a, b];
  571. };
  572. convert.lab.xyz = function (lab) {
  573. var l = lab[0];
  574. var a = lab[1];
  575. var b = lab[2];
  576. var x;
  577. var y;
  578. var z;
  579. y = (l + 16) / 116;
  580. x = a / 500 + y;
  581. z = y - b / 200;
  582. var y2 = Math.pow(y, 3);
  583. var x2 = Math.pow(x, 3);
  584. var z2 = Math.pow(z, 3);
  585. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  586. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  587. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  588. x *= 95.047;
  589. y *= 100;
  590. z *= 108.883;
  591. return [x, y, z];
  592. };
  593. convert.lab.lch = function (lab) {
  594. var l = lab[0];
  595. var a = lab[1];
  596. var b = lab[2];
  597. var hr;
  598. var h;
  599. var c;
  600. hr = Math.atan2(b, a);
  601. h = hr * 360 / 2 / Math.PI;
  602. if (h < 0) {
  603. h += 360;
  604. }
  605. c = Math.sqrt(a * a + b * b);
  606. return [l, c, h];
  607. };
  608. convert.lch.lab = function (lch) {
  609. var l = lch[0];
  610. var c = lch[1];
  611. var h = lch[2];
  612. var a;
  613. var b;
  614. var hr;
  615. hr = h / 360 * 2 * Math.PI;
  616. a = c * Math.cos(hr);
  617. b = c * Math.sin(hr);
  618. return [l, a, b];
  619. };
  620. convert.rgb.ansi16 = function (args) {
  621. var r = args[0];
  622. var g = args[1];
  623. var b = args[2];
  624. var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
  625. value = Math.round(value / 50);
  626. if (value === 0) {
  627. return 30;
  628. }
  629. var ansi = 30
  630. + ((Math.round(b / 255) << 2)
  631. | (Math.round(g / 255) << 1)
  632. | Math.round(r / 255));
  633. if (value === 2) {
  634. ansi += 60;
  635. }
  636. return ansi;
  637. };
  638. convert.hsv.ansi16 = function (args) {
  639. // optimization here; we already know the value and don't need to get
  640. // it converted for us.
  641. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
  642. };
  643. convert.rgb.ansi256 = function (args) {
  644. var r = args[0];
  645. var g = args[1];
  646. var b = args[2];
  647. // we use the extended greyscale palette here, with the exception of
  648. // black and white. normal palette only has 4 greyscale shades.
  649. if (r === g && g === b) {
  650. if (r < 8) {
  651. return 16;
  652. }
  653. if (r > 248) {
  654. return 231;
  655. }
  656. return Math.round(((r - 8) / 247) * 24) + 232;
  657. }
  658. var ansi = 16
  659. + (36 * Math.round(r / 255 * 5))
  660. + (6 * Math.round(g / 255 * 5))
  661. + Math.round(b / 255 * 5);
  662. return ansi;
  663. };
  664. convert.ansi16.rgb = function (args) {
  665. var color = args % 10;
  666. // handle greyscale
  667. if (color === 0 || color === 7) {
  668. if (args > 50) {
  669. color += 3.5;
  670. }
  671. color = color / 10.5 * 255;
  672. return [color, color, color];
  673. }
  674. var mult = (~~(args > 50) + 1) * 0.5;
  675. var r = ((color & 1) * mult) * 255;
  676. var g = (((color >> 1) & 1) * mult) * 255;
  677. var b = (((color >> 2) & 1) * mult) * 255;
  678. return [r, g, b];
  679. };
  680. convert.ansi256.rgb = function (args) {
  681. // handle greyscale
  682. if (args >= 232) {
  683. var c = (args - 232) * 10 + 8;
  684. return [c, c, c];
  685. }
  686. args -= 16;
  687. var rem;
  688. var r = Math.floor(args / 36) / 5 * 255;
  689. var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  690. var b = (rem % 6) / 5 * 255;
  691. return [r, g, b];
  692. };
  693. convert.rgb.hex = function (args) {
  694. var integer = ((Math.round(args[0]) & 0xFF) << 16)
  695. + ((Math.round(args[1]) & 0xFF) << 8)
  696. + (Math.round(args[2]) & 0xFF);
  697. var string = integer.toString(16).toUpperCase();
  698. return '000000'.substring(string.length) + string;
  699. };
  700. convert.hex.rgb = function (args) {
  701. var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  702. if (!match) {
  703. return [0, 0, 0];
  704. }
  705. var colorString = match[0];
  706. if (match[0].length === 3) {
  707. colorString = colorString.split('').map(function (char) {
  708. return char + char;
  709. }).join('');
  710. }
  711. var integer = parseInt(colorString, 16);
  712. var r = (integer >> 16) & 0xFF;
  713. var g = (integer >> 8) & 0xFF;
  714. var b = integer & 0xFF;
  715. return [r, g, b];
  716. };
  717. convert.rgb.hcg = function (rgb) {
  718. var r = rgb[0] / 255;
  719. var g = rgb[1] / 255;
  720. var b = rgb[2] / 255;
  721. var max = Math.max(Math.max(r, g), b);
  722. var min = Math.min(Math.min(r, g), b);
  723. var chroma = (max - min);
  724. var grayscale;
  725. var hue;
  726. if (chroma < 1) {
  727. grayscale = min / (1 - chroma);
  728. } else {
  729. grayscale = 0;
  730. }
  731. if (chroma <= 0) {
  732. hue = 0;
  733. } else
  734. if (max === r) {
  735. hue = ((g - b) / chroma) % 6;
  736. } else
  737. if (max === g) {
  738. hue = 2 + (b - r) / chroma;
  739. } else {
  740. hue = 4 + (r - g) / chroma + 4;
  741. }
  742. hue /= 6;
  743. hue %= 1;
  744. return [hue * 360, chroma * 100, grayscale * 100];
  745. };
  746. convert.hsl.hcg = function (hsl) {
  747. var s = hsl[1] / 100;
  748. var l = hsl[2] / 100;
  749. var c = 1;
  750. var f = 0;
  751. if (l < 0.5) {
  752. c = 2.0 * s * l;
  753. } else {
  754. c = 2.0 * s * (1.0 - l);
  755. }
  756. if (c < 1.0) {
  757. f = (l - 0.5 * c) / (1.0 - c);
  758. }
  759. return [hsl[0], c * 100, f * 100];
  760. };
  761. convert.hsv.hcg = function (hsv) {
  762. var s = hsv[1] / 100;
  763. var v = hsv[2] / 100;
  764. var c = s * v;
  765. var f = 0;
  766. if (c < 1.0) {
  767. f = (v - c) / (1 - c);
  768. }
  769. return [hsv[0], c * 100, f * 100];
  770. };
  771. convert.hcg.rgb = function (hcg) {
  772. var h = hcg[0] / 360;
  773. var c = hcg[1] / 100;
  774. var g = hcg[2] / 100;
  775. if (c === 0.0) {
  776. return [g * 255, g * 255, g * 255];
  777. }
  778. var pure = [0, 0, 0];
  779. var hi = (h % 1) * 6;
  780. var v = hi % 1;
  781. var w = 1 - v;
  782. var mg = 0;
  783. switch (Math.floor(hi)) {
  784. case 0:
  785. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  786. case 1:
  787. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  788. case 2:
  789. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  790. case 3:
  791. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  792. case 4:
  793. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  794. default:
  795. pure[0] = 1; pure[1] = 0; pure[2] = w;
  796. }
  797. mg = (1.0 - c) * g;
  798. return [
  799. (c * pure[0] + mg) * 255,
  800. (c * pure[1] + mg) * 255,
  801. (c * pure[2] + mg) * 255
  802. ];
  803. };
  804. convert.hcg.hsv = function (hcg) {
  805. var c = hcg[1] / 100;
  806. var g = hcg[2] / 100;
  807. var v = c + g * (1.0 - c);
  808. var f = 0;
  809. if (v > 0.0) {
  810. f = c / v;
  811. }
  812. return [hcg[0], f * 100, v * 100];
  813. };
  814. convert.hcg.hsl = function (hcg) {
  815. var c = hcg[1] / 100;
  816. var g = hcg[2] / 100;
  817. var l = g * (1.0 - c) + 0.5 * c;
  818. var s = 0;
  819. if (l > 0.0 && l < 0.5) {
  820. s = c / (2 * l);
  821. } else
  822. if (l >= 0.5 && l < 1.0) {
  823. s = c / (2 * (1 - l));
  824. }
  825. return [hcg[0], s * 100, l * 100];
  826. };
  827. convert.hcg.hwb = function (hcg) {
  828. var c = hcg[1] / 100;
  829. var g = hcg[2] / 100;
  830. var v = c + g * (1.0 - c);
  831. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  832. };
  833. convert.hwb.hcg = function (hwb) {
  834. var w = hwb[1] / 100;
  835. var b = hwb[2] / 100;
  836. var v = 1 - b;
  837. var c = v - w;
  838. var g = 0;
  839. if (c < 1) {
  840. g = (v - c) / (1 - c);
  841. }
  842. return [hwb[0], c * 100, g * 100];
  843. };
  844. convert.apple.rgb = function (apple) {
  845. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  846. };
  847. convert.rgb.apple = function (rgb) {
  848. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  849. };
  850. convert.gray.rgb = function (args) {
  851. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  852. };
  853. convert.gray.hsl = convert.gray.hsv = function (args) {
  854. return [0, 0, args[0]];
  855. };
  856. convert.gray.hwb = function (gray) {
  857. return [0, 100, gray[0]];
  858. };
  859. convert.gray.cmyk = function (gray) {
  860. return [0, 0, 0, gray[0]];
  861. };
  862. convert.gray.lab = function (gray) {
  863. return [gray[0], 0, 0];
  864. };
  865. convert.gray.hex = function (gray) {
  866. var val = Math.round(gray[0] / 100 * 255) & 0xFF;
  867. var integer = (val << 16) + (val << 8) + val;
  868. var string = integer.toString(16).toUpperCase();
  869. return '000000'.substring(string.length) + string;
  870. };
  871. convert.rgb.gray = function (rgb) {
  872. var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  873. return [val / 255 * 100];
  874. };
  875. });
  876. var conversions_1 = conversions.rgb;
  877. var conversions_2 = conversions.hsl;
  878. var conversions_3 = conversions.hsv;
  879. var conversions_4 = conversions.hwb;
  880. var conversions_5 = conversions.cmyk;
  881. var conversions_6 = conversions.xyz;
  882. var conversions_7 = conversions.lab;
  883. var conversions_8 = conversions.lch;
  884. var conversions_9 = conversions.hex;
  885. var conversions_10 = conversions.keyword;
  886. var conversions_11 = conversions.ansi16;
  887. var conversions_12 = conversions.ansi256;
  888. var conversions_13 = conversions.hcg;
  889. var conversions_14 = conversions.apple;
  890. var conversions_15 = conversions.gray;
  891. /*
  892. this function routes a model to all other models.
  893. all functions that are routed have a property `.conversion` attached
  894. to the returned synthetic function. This property is an array
  895. of strings, each with the steps in between the 'from' and 'to'
  896. color models (inclusive).
  897. conversions that are not possible simply are not included.
  898. */
  899. function buildGraph() {
  900. var graph = {};
  901. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  902. var models = Object.keys(conversions);
  903. for (var len = models.length, i = 0; i < len; i++) {
  904. graph[models[i]] = {
  905. // http://jsperf.com/1-vs-infinity
  906. // micro-opt, but this is simple.
  907. distance: -1,
  908. parent: null
  909. };
  910. }
  911. return graph;
  912. }
  913. // https://en.wikipedia.org/wiki/Breadth-first_search
  914. function deriveBFS(fromModel) {
  915. var graph = buildGraph();
  916. var queue = [fromModel]; // unshift -> queue -> pop
  917. graph[fromModel].distance = 0;
  918. while (queue.length) {
  919. var current = queue.pop();
  920. var adjacents = Object.keys(conversions[current]);
  921. for (var len = adjacents.length, i = 0; i < len; i++) {
  922. var adjacent = adjacents[i];
  923. var node = graph[adjacent];
  924. if (node.distance === -1) {
  925. node.distance = graph[current].distance + 1;
  926. node.parent = current;
  927. queue.unshift(adjacent);
  928. }
  929. }
  930. }
  931. return graph;
  932. }
  933. function link(from, to) {
  934. return function (args) {
  935. return to(from(args));
  936. };
  937. }
  938. function wrapConversion(toModel, graph) {
  939. var path = [graph[toModel].parent, toModel];
  940. var fn = conversions[graph[toModel].parent][toModel];
  941. var cur = graph[toModel].parent;
  942. while (graph[cur].parent) {
  943. path.unshift(graph[cur].parent);
  944. fn = link(conversions[graph[cur].parent][cur], fn);
  945. cur = graph[cur].parent;
  946. }
  947. fn.conversion = path;
  948. return fn;
  949. }
  950. var route = function (fromModel) {
  951. var graph = deriveBFS(fromModel);
  952. var conversion = {};
  953. var models = Object.keys(graph);
  954. for (var len = models.length, i = 0; i < len; i++) {
  955. var toModel = models[i];
  956. var node = graph[toModel];
  957. if (node.parent === null) {
  958. // no possible conversion, or this node is the source model.
  959. continue;
  960. }
  961. conversion[toModel] = wrapConversion(toModel, graph);
  962. }
  963. return conversion;
  964. };
  965. var convert = {};
  966. var models = Object.keys(conversions);
  967. function wrapRaw(fn) {
  968. var wrappedFn = function (args) {
  969. if (args === undefined || args === null) {
  970. return args;
  971. }
  972. if (arguments.length > 1) {
  973. args = Array.prototype.slice.call(arguments);
  974. }
  975. return fn(args);
  976. };
  977. // preserve .conversion property if there is one
  978. if ('conversion' in fn) {
  979. wrappedFn.conversion = fn.conversion;
  980. }
  981. return wrappedFn;
  982. }
  983. function wrapRounded(fn) {
  984. var wrappedFn = function (args) {
  985. if (args === undefined || args === null) {
  986. return args;
  987. }
  988. if (arguments.length > 1) {
  989. args = Array.prototype.slice.call(arguments);
  990. }
  991. var result = fn(args);
  992. // we're assuming the result is an array here.
  993. // see notice in conversions.js; don't use box types
  994. // in conversion functions.
  995. if (typeof result === 'object') {
  996. for (var len = result.length, i = 0; i < len; i++) {
  997. result[i] = Math.round(result[i]);
  998. }
  999. }
  1000. return result;
  1001. };
  1002. // preserve .conversion property if there is one
  1003. if ('conversion' in fn) {
  1004. wrappedFn.conversion = fn.conversion;
  1005. }
  1006. return wrappedFn;
  1007. }
  1008. models.forEach(function (fromModel) {
  1009. convert[fromModel] = {};
  1010. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  1011. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  1012. var routes = route(fromModel);
  1013. var routeModels = Object.keys(routes);
  1014. routeModels.forEach(function (toModel) {
  1015. var fn = routes[toModel];
  1016. convert[fromModel][toModel] = wrapRounded(fn);
  1017. convert[fromModel][toModel].raw = wrapRaw(fn);
  1018. });
  1019. });
  1020. var colorConvert = convert;
  1021. var colorName$1 = {
  1022. "aliceblue": [240, 248, 255],
  1023. "antiquewhite": [250, 235, 215],
  1024. "aqua": [0, 255, 255],
  1025. "aquamarine": [127, 255, 212],
  1026. "azure": [240, 255, 255],
  1027. "beige": [245, 245, 220],
  1028. "bisque": [255, 228, 196],
  1029. "black": [0, 0, 0],
  1030. "blanchedalmond": [255, 235, 205],
  1031. "blue": [0, 0, 255],
  1032. "blueviolet": [138, 43, 226],
  1033. "brown": [165, 42, 42],
  1034. "burlywood": [222, 184, 135],
  1035. "cadetblue": [95, 158, 160],
  1036. "chartreuse": [127, 255, 0],
  1037. "chocolate": [210, 105, 30],
  1038. "coral": [255, 127, 80],
  1039. "cornflowerblue": [100, 149, 237],
  1040. "cornsilk": [255, 248, 220],
  1041. "crimson": [220, 20, 60],
  1042. "cyan": [0, 255, 255],
  1043. "darkblue": [0, 0, 139],
  1044. "darkcyan": [0, 139, 139],
  1045. "darkgoldenrod": [184, 134, 11],
  1046. "darkgray": [169, 169, 169],
  1047. "darkgreen": [0, 100, 0],
  1048. "darkgrey": [169, 169, 169],
  1049. "darkkhaki": [189, 183, 107],
  1050. "darkmagenta": [139, 0, 139],
  1051. "darkolivegreen": [85, 107, 47],
  1052. "darkorange": [255, 140, 0],
  1053. "darkorchid": [153, 50, 204],
  1054. "darkred": [139, 0, 0],
  1055. "darksalmon": [233, 150, 122],
  1056. "darkseagreen": [143, 188, 143],
  1057. "darkslateblue": [72, 61, 139],
  1058. "darkslategray": [47, 79, 79],
  1059. "darkslategrey": [47, 79, 79],
  1060. "darkturquoise": [0, 206, 209],
  1061. "darkviolet": [148, 0, 211],
  1062. "deeppink": [255, 20, 147],
  1063. "deepskyblue": [0, 191, 255],
  1064. "dimgray": [105, 105, 105],
  1065. "dimgrey": [105, 105, 105],
  1066. "dodgerblue": [30, 144, 255],
  1067. "firebrick": [178, 34, 34],
  1068. "floralwhite": [255, 250, 240],
  1069. "forestgreen": [34, 139, 34],
  1070. "fuchsia": [255, 0, 255],
  1071. "gainsboro": [220, 220, 220],
  1072. "ghostwhite": [248, 248, 255],
  1073. "gold": [255, 215, 0],
  1074. "goldenrod": [218, 165, 32],
  1075. "gray": [128, 128, 128],
  1076. "green": [0, 128, 0],
  1077. "greenyellow": [173, 255, 47],
  1078. "grey": [128, 128, 128],
  1079. "honeydew": [240, 255, 240],
  1080. "hotpink": [255, 105, 180],
  1081. "indianred": [205, 92, 92],
  1082. "indigo": [75, 0, 130],
  1083. "ivory": [255, 255, 240],
  1084. "khaki": [240, 230, 140],
  1085. "lavender": [230, 230, 250],
  1086. "lavenderblush": [255, 240, 245],
  1087. "lawngreen": [124, 252, 0],
  1088. "lemonchiffon": [255, 250, 205],
  1089. "lightblue": [173, 216, 230],
  1090. "lightcoral": [240, 128, 128],
  1091. "lightcyan": [224, 255, 255],
  1092. "lightgoldenrodyellow": [250, 250, 210],
  1093. "lightgray": [211, 211, 211],
  1094. "lightgreen": [144, 238, 144],
  1095. "lightgrey": [211, 211, 211],
  1096. "lightpink": [255, 182, 193],
  1097. "lightsalmon": [255, 160, 122],
  1098. "lightseagreen": [32, 178, 170],
  1099. "lightskyblue": [135, 206, 250],
  1100. "lightslategray": [119, 136, 153],
  1101. "lightslategrey": [119, 136, 153],
  1102. "lightsteelblue": [176, 196, 222],
  1103. "lightyellow": [255, 255, 224],
  1104. "lime": [0, 255, 0],
  1105. "limegreen": [50, 205, 50],
  1106. "linen": [250, 240, 230],
  1107. "magenta": [255, 0, 255],
  1108. "maroon": [128, 0, 0],
  1109. "mediumaquamarine": [102, 205, 170],
  1110. "mediumblue": [0, 0, 205],
  1111. "mediumorchid": [186, 85, 211],
  1112. "mediumpurple": [147, 112, 219],
  1113. "mediumseagreen": [60, 179, 113],
  1114. "mediumslateblue": [123, 104, 238],
  1115. "mediumspringgreen": [0, 250, 154],
  1116. "mediumturquoise": [72, 209, 204],
  1117. "mediumvioletred": [199, 21, 133],
  1118. "midnightblue": [25, 25, 112],
  1119. "mintcream": [245, 255, 250],
  1120. "mistyrose": [255, 228, 225],
  1121. "moccasin": [255, 228, 181],
  1122. "navajowhite": [255, 222, 173],
  1123. "navy": [0, 0, 128],
  1124. "oldlace": [253, 245, 230],
  1125. "olive": [128, 128, 0],
  1126. "olivedrab": [107, 142, 35],
  1127. "orange": [255, 165, 0],
  1128. "orangered": [255, 69, 0],
  1129. "orchid": [218, 112, 214],
  1130. "palegoldenrod": [238, 232, 170],
  1131. "palegreen": [152, 251, 152],
  1132. "paleturquoise": [175, 238, 238],
  1133. "palevioletred": [219, 112, 147],
  1134. "papayawhip": [255, 239, 213],
  1135. "peachpuff": [255, 218, 185],
  1136. "peru": [205, 133, 63],
  1137. "pink": [255, 192, 203],
  1138. "plum": [221, 160, 221],
  1139. "powderblue": [176, 224, 230],
  1140. "purple": [128, 0, 128],
  1141. "rebeccapurple": [102, 51, 153],
  1142. "red": [255, 0, 0],
  1143. "rosybrown": [188, 143, 143],
  1144. "royalblue": [65, 105, 225],
  1145. "saddlebrown": [139, 69, 19],
  1146. "salmon": [250, 128, 114],
  1147. "sandybrown": [244, 164, 96],
  1148. "seagreen": [46, 139, 87],
  1149. "seashell": [255, 245, 238],
  1150. "sienna": [160, 82, 45],
  1151. "silver": [192, 192, 192],
  1152. "skyblue": [135, 206, 235],
  1153. "slateblue": [106, 90, 205],
  1154. "slategray": [112, 128, 144],
  1155. "slategrey": [112, 128, 144],
  1156. "snow": [255, 250, 250],
  1157. "springgreen": [0, 255, 127],
  1158. "steelblue": [70, 130, 180],
  1159. "tan": [210, 180, 140],
  1160. "teal": [0, 128, 128],
  1161. "thistle": [216, 191, 216],
  1162. "tomato": [255, 99, 71],
  1163. "turquoise": [64, 224, 208],
  1164. "violet": [238, 130, 238],
  1165. "wheat": [245, 222, 179],
  1166. "white": [255, 255, 255],
  1167. "whitesmoke": [245, 245, 245],
  1168. "yellow": [255, 255, 0],
  1169. "yellowgreen": [154, 205, 50]
  1170. };
  1171. /* MIT license */
  1172. var colorString = {
  1173. getRgba: getRgba,
  1174. getHsla: getHsla,
  1175. getRgb: getRgb,
  1176. getHsl: getHsl,
  1177. getHwb: getHwb,
  1178. getAlpha: getAlpha,
  1179. hexString: hexString,
  1180. rgbString: rgbString,
  1181. rgbaString: rgbaString,
  1182. percentString: percentString,
  1183. percentaString: percentaString,
  1184. hslString: hslString,
  1185. hslaString: hslaString,
  1186. hwbString: hwbString,
  1187. keyword: keyword
  1188. };
  1189. function getRgba(string) {
  1190. if (!string) {
  1191. return;
  1192. }
  1193. var abbr = /^#([a-fA-F0-9]{3,4})$/i,
  1194. hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
  1195. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1196. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1197. keyword = /(\w+)/;
  1198. var rgb = [0, 0, 0],
  1199. a = 1,
  1200. match = string.match(abbr),
  1201. hexAlpha = "";
  1202. if (match) {
  1203. match = match[1];
  1204. hexAlpha = match[3];
  1205. for (var i = 0; i < rgb.length; i++) {
  1206. rgb[i] = parseInt(match[i] + match[i], 16);
  1207. }
  1208. if (hexAlpha) {
  1209. a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
  1210. }
  1211. }
  1212. else if (match = string.match(hex)) {
  1213. hexAlpha = match[2];
  1214. match = match[1];
  1215. for (var i = 0; i < rgb.length; i++) {
  1216. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  1217. }
  1218. if (hexAlpha) {
  1219. a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
  1220. }
  1221. }
  1222. else if (match = string.match(rgba)) {
  1223. for (var i = 0; i < rgb.length; i++) {
  1224. rgb[i] = parseInt(match[i + 1]);
  1225. }
  1226. a = parseFloat(match[4]);
  1227. }
  1228. else if (match = string.match(per)) {
  1229. for (var i = 0; i < rgb.length; i++) {
  1230. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  1231. }
  1232. a = parseFloat(match[4]);
  1233. }
  1234. else if (match = string.match(keyword)) {
  1235. if (match[1] == "transparent") {
  1236. return [0, 0, 0, 0];
  1237. }
  1238. rgb = colorName$1[match[1]];
  1239. if (!rgb) {
  1240. return;
  1241. }
  1242. }
  1243. for (var i = 0; i < rgb.length; i++) {
  1244. rgb[i] = scale(rgb[i], 0, 255);
  1245. }
  1246. if (!a && a != 0) {
  1247. a = 1;
  1248. }
  1249. else {
  1250. a = scale(a, 0, 1);
  1251. }
  1252. rgb[3] = a;
  1253. return rgb;
  1254. }
  1255. function getHsla(string) {
  1256. if (!string) {
  1257. return;
  1258. }
  1259. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1260. var match = string.match(hsl);
  1261. if (match) {
  1262. var alpha = parseFloat(match[4]);
  1263. var h = scale(parseInt(match[1]), 0, 360),
  1264. s = scale(parseFloat(match[2]), 0, 100),
  1265. l = scale(parseFloat(match[3]), 0, 100),
  1266. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1267. return [h, s, l, a];
  1268. }
  1269. }
  1270. function getHwb(string) {
  1271. if (!string) {
  1272. return;
  1273. }
  1274. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1275. var match = string.match(hwb);
  1276. if (match) {
  1277. var alpha = parseFloat(match[4]);
  1278. var h = scale(parseInt(match[1]), 0, 360),
  1279. w = scale(parseFloat(match[2]), 0, 100),
  1280. b = scale(parseFloat(match[3]), 0, 100),
  1281. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1282. return [h, w, b, a];
  1283. }
  1284. }
  1285. function getRgb(string) {
  1286. var rgba = getRgba(string);
  1287. return rgba && rgba.slice(0, 3);
  1288. }
  1289. function getHsl(string) {
  1290. var hsla = getHsla(string);
  1291. return hsla && hsla.slice(0, 3);
  1292. }
  1293. function getAlpha(string) {
  1294. var vals = getRgba(string);
  1295. if (vals) {
  1296. return vals[3];
  1297. }
  1298. else if (vals = getHsla(string)) {
  1299. return vals[3];
  1300. }
  1301. else if (vals = getHwb(string)) {
  1302. return vals[3];
  1303. }
  1304. }
  1305. // generators
  1306. function hexString(rgba, a) {
  1307. var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
  1308. return "#" + hexDouble(rgba[0])
  1309. + hexDouble(rgba[1])
  1310. + hexDouble(rgba[2])
  1311. + (
  1312. (a >= 0 && a < 1)
  1313. ? hexDouble(Math.round(a * 255))
  1314. : ""
  1315. );
  1316. }
  1317. function rgbString(rgba, alpha) {
  1318. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1319. return rgbaString(rgba, alpha);
  1320. }
  1321. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  1322. }
  1323. function rgbaString(rgba, alpha) {
  1324. if (alpha === undefined) {
  1325. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  1326. }
  1327. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  1328. + ", " + alpha + ")";
  1329. }
  1330. function percentString(rgba, alpha) {
  1331. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1332. return percentaString(rgba, alpha);
  1333. }
  1334. var r = Math.round(rgba[0]/255 * 100),
  1335. g = Math.round(rgba[1]/255 * 100),
  1336. b = Math.round(rgba[2]/255 * 100);
  1337. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  1338. }
  1339. function percentaString(rgba, alpha) {
  1340. var r = Math.round(rgba[0]/255 * 100),
  1341. g = Math.round(rgba[1]/255 * 100),
  1342. b = Math.round(rgba[2]/255 * 100);
  1343. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  1344. }
  1345. function hslString(hsla, alpha) {
  1346. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  1347. return hslaString(hsla, alpha);
  1348. }
  1349. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  1350. }
  1351. function hslaString(hsla, alpha) {
  1352. if (alpha === undefined) {
  1353. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  1354. }
  1355. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  1356. + alpha + ")";
  1357. }
  1358. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  1359. // (hwb have alpha optional & 1 is default value)
  1360. function hwbString(hwb, alpha) {
  1361. if (alpha === undefined) {
  1362. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  1363. }
  1364. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  1365. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  1366. }
  1367. function keyword(rgb) {
  1368. return reverseNames[rgb.slice(0, 3)];
  1369. }
  1370. // helpers
  1371. function scale(num, min, max) {
  1372. return Math.min(Math.max(min, num), max);
  1373. }
  1374. function hexDouble(num) {
  1375. var str = num.toString(16).toUpperCase();
  1376. return (str.length < 2) ? "0" + str : str;
  1377. }
  1378. //create a list of reverse color names
  1379. var reverseNames = {};
  1380. for (var name in colorName$1) {
  1381. reverseNames[colorName$1[name]] = name;
  1382. }
  1383. /* MIT license */
  1384. var Color = function (obj) {
  1385. if (obj instanceof Color) {
  1386. return obj;
  1387. }
  1388. if (!(this instanceof Color)) {
  1389. return new Color(obj);
  1390. }
  1391. this.valid = false;
  1392. this.values = {
  1393. rgb: [0, 0, 0],
  1394. hsl: [0, 0, 0],
  1395. hsv: [0, 0, 0],
  1396. hwb: [0, 0, 0],
  1397. cmyk: [0, 0, 0, 0],
  1398. alpha: 1
  1399. };
  1400. // parse Color() argument
  1401. var vals;
  1402. if (typeof obj === 'string') {
  1403. vals = colorString.getRgba(obj);
  1404. if (vals) {
  1405. this.setValues('rgb', vals);
  1406. } else if (vals = colorString.getHsla(obj)) {
  1407. this.setValues('hsl', vals);
  1408. } else if (vals = colorString.getHwb(obj)) {
  1409. this.setValues('hwb', vals);
  1410. }
  1411. } else if (typeof obj === 'object') {
  1412. vals = obj;
  1413. if (vals.r !== undefined || vals.red !== undefined) {
  1414. this.setValues('rgb', vals);
  1415. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  1416. this.setValues('hsl', vals);
  1417. } else if (vals.v !== undefined || vals.value !== undefined) {
  1418. this.setValues('hsv', vals);
  1419. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  1420. this.setValues('hwb', vals);
  1421. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  1422. this.setValues('cmyk', vals);
  1423. }
  1424. }
  1425. };
  1426. Color.prototype = {
  1427. isValid: function () {
  1428. return this.valid;
  1429. },
  1430. rgb: function () {
  1431. return this.setSpace('rgb', arguments);
  1432. },
  1433. hsl: function () {
  1434. return this.setSpace('hsl', arguments);
  1435. },
  1436. hsv: function () {
  1437. return this.setSpace('hsv', arguments);
  1438. },
  1439. hwb: function () {
  1440. return this.setSpace('hwb', arguments);
  1441. },
  1442. cmyk: function () {
  1443. return this.setSpace('cmyk', arguments);
  1444. },
  1445. rgbArray: function () {
  1446. return this.values.rgb;
  1447. },
  1448. hslArray: function () {
  1449. return this.values.hsl;
  1450. },
  1451. hsvArray: function () {
  1452. return this.values.hsv;
  1453. },
  1454. hwbArray: function () {
  1455. var values = this.values;
  1456. if (values.alpha !== 1) {
  1457. return values.hwb.concat([values.alpha]);
  1458. }
  1459. return values.hwb;
  1460. },
  1461. cmykArray: function () {
  1462. return this.values.cmyk;
  1463. },
  1464. rgbaArray: function () {
  1465. var values = this.values;
  1466. return values.rgb.concat([values.alpha]);
  1467. },
  1468. hslaArray: function () {
  1469. var values = this.values;
  1470. return values.hsl.concat([values.alpha]);
  1471. },
  1472. alpha: function (val) {
  1473. if (val === undefined) {
  1474. return this.values.alpha;
  1475. }
  1476. this.setValues('alpha', val);
  1477. return this;
  1478. },
  1479. red: function (val) {
  1480. return this.setChannel('rgb', 0, val);
  1481. },
  1482. green: function (val) {
  1483. return this.setChannel('rgb', 1, val);
  1484. },
  1485. blue: function (val) {
  1486. return this.setChannel('rgb', 2, val);
  1487. },
  1488. hue: function (val) {
  1489. if (val) {
  1490. val %= 360;
  1491. val = val < 0 ? 360 + val : val;
  1492. }
  1493. return this.setChannel('hsl', 0, val);
  1494. },
  1495. saturation: function (val) {
  1496. return this.setChannel('hsl', 1, val);
  1497. },
  1498. lightness: function (val) {
  1499. return this.setChannel('hsl', 2, val);
  1500. },
  1501. saturationv: function (val) {
  1502. return this.setChannel('hsv', 1, val);
  1503. },
  1504. whiteness: function (val) {
  1505. return this.setChannel('hwb', 1, val);
  1506. },
  1507. blackness: function (val) {
  1508. return this.setChannel('hwb', 2, val);
  1509. },
  1510. value: function (val) {
  1511. return this.setChannel('hsv', 2, val);
  1512. },
  1513. cyan: function (val) {
  1514. return this.setChannel('cmyk', 0, val);
  1515. },
  1516. magenta: function (val) {
  1517. return this.setChannel('cmyk', 1, val);
  1518. },
  1519. yellow: function (val) {
  1520. return this.setChannel('cmyk', 2, val);
  1521. },
  1522. black: function (val) {
  1523. return this.setChannel('cmyk', 3, val);
  1524. },
  1525. hexString: function () {
  1526. return colorString.hexString(this.values.rgb);
  1527. },
  1528. rgbString: function () {
  1529. return colorString.rgbString(this.values.rgb, this.values.alpha);
  1530. },
  1531. rgbaString: function () {
  1532. return colorString.rgbaString(this.values.rgb, this.values.alpha);
  1533. },
  1534. percentString: function () {
  1535. return colorString.percentString(this.values.rgb, this.values.alpha);
  1536. },
  1537. hslString: function () {
  1538. return colorString.hslString(this.values.hsl, this.values.alpha);
  1539. },
  1540. hslaString: function () {
  1541. return colorString.hslaString(this.values.hsl, this.values.alpha);
  1542. },
  1543. hwbString: function () {
  1544. return colorString.hwbString(this.values.hwb, this.values.alpha);
  1545. },
  1546. keyword: function () {
  1547. return colorString.keyword(this.values.rgb, this.values.alpha);
  1548. },
  1549. rgbNumber: function () {
  1550. var rgb = this.values.rgb;
  1551. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  1552. },
  1553. luminosity: function () {
  1554. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  1555. var rgb = this.values.rgb;
  1556. var lum = [];
  1557. for (var i = 0; i < rgb.length; i++) {
  1558. var chan = rgb[i] / 255;
  1559. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  1560. }
  1561. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  1562. },
  1563. contrast: function (color2) {
  1564. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  1565. var lum1 = this.luminosity();
  1566. var lum2 = color2.luminosity();
  1567. if (lum1 > lum2) {
  1568. return (lum1 + 0.05) / (lum2 + 0.05);
  1569. }
  1570. return (lum2 + 0.05) / (lum1 + 0.05);
  1571. },
  1572. level: function (color2) {
  1573. var contrastRatio = this.contrast(color2);
  1574. if (contrastRatio >= 7.1) {
  1575. return 'AAA';
  1576. }
  1577. return (contrastRatio >= 4.5) ? 'AA' : '';
  1578. },
  1579. dark: function () {
  1580. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  1581. var rgb = this.values.rgb;
  1582. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  1583. return yiq < 128;
  1584. },
  1585. light: function () {
  1586. return !this.dark();
  1587. },
  1588. negate: function () {
  1589. var rgb = [];
  1590. for (var i = 0; i < 3; i++) {
  1591. rgb[i] = 255 - this.values.rgb[i];
  1592. }
  1593. this.setValues('rgb', rgb);
  1594. return this;
  1595. },
  1596. lighten: function (ratio) {
  1597. var hsl = this.values.hsl;
  1598. hsl[2] += hsl[2] * ratio;
  1599. this.setValues('hsl', hsl);
  1600. return this;
  1601. },
  1602. darken: function (ratio) {
  1603. var hsl = this.values.hsl;
  1604. hsl[2] -= hsl[2] * ratio;
  1605. this.setValues('hsl', hsl);
  1606. return this;
  1607. },
  1608. saturate: function (ratio) {
  1609. var hsl = this.values.hsl;
  1610. hsl[1] += hsl[1] * ratio;
  1611. this.setValues('hsl', hsl);
  1612. return this;
  1613. },
  1614. desaturate: function (ratio) {
  1615. var hsl = this.values.hsl;
  1616. hsl[1] -= hsl[1] * ratio;
  1617. this.setValues('hsl', hsl);
  1618. return this;
  1619. },
  1620. whiten: function (ratio) {
  1621. var hwb = this.values.hwb;
  1622. hwb[1] += hwb[1] * ratio;
  1623. this.setValues('hwb', hwb);
  1624. return this;
  1625. },
  1626. blacken: function (ratio) {
  1627. var hwb = this.values.hwb;
  1628. hwb[2] += hwb[2] * ratio;
  1629. this.setValues('hwb', hwb);
  1630. return this;
  1631. },
  1632. greyscale: function () {
  1633. var rgb = this.values.rgb;
  1634. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  1635. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  1636. this.setValues('rgb', [val, val, val]);
  1637. return this;
  1638. },
  1639. clearer: function (ratio) {
  1640. var alpha = this.values.alpha;
  1641. this.setValues('alpha', alpha - (alpha * ratio));
  1642. return this;
  1643. },
  1644. opaquer: function (ratio) {
  1645. var alpha = this.values.alpha;
  1646. this.setValues('alpha', alpha + (alpha * ratio));
  1647. return this;
  1648. },
  1649. rotate: function (degrees) {
  1650. var hsl = this.values.hsl;
  1651. var hue = (hsl[0] + degrees) % 360;
  1652. hsl[0] = hue < 0 ? 360 + hue : hue;
  1653. this.setValues('hsl', hsl);
  1654. return this;
  1655. },
  1656. /**
  1657. * Ported from sass implementation in C
  1658. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  1659. */
  1660. mix: function (mixinColor, weight) {
  1661. var color1 = this;
  1662. var color2 = mixinColor;
  1663. var p = weight === undefined ? 0.5 : weight;
  1664. var w = 2 * p - 1;
  1665. var a = color1.alpha() - color2.alpha();
  1666. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  1667. var w2 = 1 - w1;
  1668. return this
  1669. .rgb(
  1670. w1 * color1.red() + w2 * color2.red(),
  1671. w1 * color1.green() + w2 * color2.green(),
  1672. w1 * color1.blue() + w2 * color2.blue()
  1673. )
  1674. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  1675. },
  1676. toJSON: function () {
  1677. return this.rgb();
  1678. },
  1679. clone: function () {
  1680. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  1681. // making the final build way to big to embed in Chart.js. So let's do it manually,
  1682. // assuming that values to clone are 1 dimension arrays containing only numbers,
  1683. // except 'alpha' which is a number.
  1684. var result = new Color();
  1685. var source = this.values;
  1686. var target = result.values;
  1687. var value, type;
  1688. for (var prop in source) {
  1689. if (source.hasOwnProperty(prop)) {
  1690. value = source[prop];
  1691. type = ({}).toString.call(value);
  1692. if (type === '[object Array]') {
  1693. target[prop] = value.slice(0);
  1694. } else if (type === '[object Number]') {
  1695. target[prop] = value;
  1696. } else {
  1697. console.error('unexpected color value:', value);
  1698. }
  1699. }
  1700. }
  1701. return result;
  1702. }
  1703. };
  1704. Color.prototype.spaces = {
  1705. rgb: ['red', 'green', 'blue'],
  1706. hsl: ['hue', 'saturation', 'lightness'],
  1707. hsv: ['hue', 'saturation', 'value'],
  1708. hwb: ['hue', 'whiteness', 'blackness'],
  1709. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  1710. };
  1711. Color.prototype.maxes = {
  1712. rgb: [255, 255, 255],
  1713. hsl: [360, 100, 100],
  1714. hsv: [360, 100, 100],
  1715. hwb: [360, 100, 100],
  1716. cmyk: [100, 100, 100, 100]
  1717. };
  1718. Color.prototype.getValues = function (space) {
  1719. var values = this.values;
  1720. var vals = {};
  1721. for (var i = 0; i < space.length; i++) {
  1722. vals[space.charAt(i)] = values[space][i];
  1723. }
  1724. if (values.alpha !== 1) {
  1725. vals.a = values.alpha;
  1726. }
  1727. // {r: 255, g: 255, b: 255, a: 0.4}
  1728. return vals;
  1729. };
  1730. Color.prototype.setValues = function (space, vals) {
  1731. var values = this.values;
  1732. var spaces = this.spaces;
  1733. var maxes = this.maxes;
  1734. var alpha = 1;
  1735. var i;
  1736. this.valid = true;
  1737. if (space === 'alpha') {
  1738. alpha = vals;
  1739. } else if (vals.length) {
  1740. // [10, 10, 10]
  1741. values[space] = vals.slice(0, space.length);
  1742. alpha = vals[space.length];
  1743. } else if (vals[space.charAt(0)] !== undefined) {
  1744. // {r: 10, g: 10, b: 10}
  1745. for (i = 0; i < space.length; i++) {
  1746. values[space][i] = vals[space.charAt(i)];
  1747. }
  1748. alpha = vals.a;
  1749. } else if (vals[spaces[space][0]] !== undefined) {
  1750. // {red: 10, green: 10, blue: 10}
  1751. var chans = spaces[space];
  1752. for (i = 0; i < space.length; i++) {
  1753. values[space][i] = vals[chans[i]];
  1754. }
  1755. alpha = vals.alpha;
  1756. }
  1757. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  1758. if (space === 'alpha') {
  1759. return false;
  1760. }
  1761. var capped;
  1762. // cap values of the space prior converting all values
  1763. for (i = 0; i < space.length; i++) {
  1764. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  1765. values[space][i] = Math.round(capped);
  1766. }
  1767. // convert to all the other color spaces
  1768. for (var sname in spaces) {
  1769. if (sname !== space) {
  1770. values[sname] = colorConvert[space][sname](values[space]);
  1771. }
  1772. }
  1773. return true;
  1774. };
  1775. Color.prototype.setSpace = function (space, args) {
  1776. var vals = args[0];
  1777. if (vals === undefined) {
  1778. // color.rgb()
  1779. return this.getValues(space);
  1780. }
  1781. // color.rgb(10, 10, 10)
  1782. if (typeof vals === 'number') {
  1783. vals = Array.prototype.slice.call(args);
  1784. }
  1785. this.setValues(space, vals);
  1786. return this;
  1787. };
  1788. Color.prototype.setChannel = function (space, index, val) {
  1789. var svalues = this.values[space];
  1790. if (val === undefined) {
  1791. // color.red()
  1792. return svalues[index];
  1793. } else if (val === svalues[index]) {
  1794. // color.red(color.red())
  1795. return this;
  1796. }
  1797. // color.red(100)
  1798. svalues[index] = val;
  1799. this.setValues(space, svalues);
  1800. return this;
  1801. };
  1802. if (typeof window !== 'undefined') {
  1803. window.Color = Color;
  1804. }
  1805. var chartjsColor = Color;
  1806. function isValidKey(key) {
  1807. return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;
  1808. }
  1809. /**
  1810. * @namespace Chart.helpers
  1811. */
  1812. var helpers = {
  1813. /**
  1814. * An empty function that can be used, for example, for optional callback.
  1815. */
  1816. noop: function() {},
  1817. /**
  1818. * Returns a unique id, sequentially generated from a global variable.
  1819. * @returns {number}
  1820. * @function
  1821. */
  1822. uid: (function() {
  1823. var id = 0;
  1824. return function() {
  1825. return id++;
  1826. };
  1827. }()),
  1828. /**
  1829. * Returns true if `value` is neither null nor undefined, else returns false.
  1830. * @param {*} value - The value to test.
  1831. * @returns {boolean}
  1832. * @since 2.7.0
  1833. */
  1834. isNullOrUndef: function(value) {
  1835. return value === null || typeof value === 'undefined';
  1836. },
  1837. /**
  1838. * Returns true if `value` is an array (including typed arrays), else returns false.
  1839. * @param {*} value - The value to test.
  1840. * @returns {boolean}
  1841. * @function
  1842. */
  1843. isArray: function(value) {
  1844. if (Array.isArray && Array.isArray(value)) {
  1845. return true;
  1846. }
  1847. var type = Object.prototype.toString.call(value);
  1848. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  1849. return true;
  1850. }
  1851. return false;
  1852. },
  1853. /**
  1854. * Returns true if `value` is an object (excluding null), else returns false.
  1855. * @param {*} value - The value to test.
  1856. * @returns {boolean}
  1857. * @since 2.7.0
  1858. */
  1859. isObject: function(value) {
  1860. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  1861. },
  1862. /**
  1863. * Returns true if `value` is a finite number, else returns false
  1864. * @param {*} value - The value to test.
  1865. * @returns {boolean}
  1866. */
  1867. isFinite: function(value) {
  1868. return (typeof value === 'number' || value instanceof Number) && isFinite(value);
  1869. },
  1870. /**
  1871. * Returns `value` if defined, else returns `defaultValue`.
  1872. * @param {*} value - The value to return if defined.
  1873. * @param {*} defaultValue - The value to return if `value` is undefined.
  1874. * @returns {*}
  1875. */
  1876. valueOrDefault: function(value, defaultValue) {
  1877. return typeof value === 'undefined' ? defaultValue : value;
  1878. },
  1879. /**
  1880. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  1881. * @param {Array} value - The array to lookup for value at `index`.
  1882. * @param {number} index - The index in `value` to lookup for value.
  1883. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  1884. * @returns {*}
  1885. */
  1886. valueAtIndexOrDefault: function(value, index, defaultValue) {
  1887. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  1888. },
  1889. /**
  1890. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  1891. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  1892. * @param {function} fn - The function to call.
  1893. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  1894. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1895. * @returns {*}
  1896. */
  1897. callback: function(fn, args, thisArg) {
  1898. if (fn && typeof fn.call === 'function') {
  1899. return fn.apply(thisArg, args);
  1900. }
  1901. },
  1902. /**
  1903. * Note(SB) for performance sake, this method should only be used when loopable type
  1904. * is unknown or in none intensive code (not called often and small loopable). Else
  1905. * it's preferable to use a regular for() loop and save extra function calls.
  1906. * @param {object|Array} loopable - The object or array to be iterated.
  1907. * @param {function} fn - The function to call for each item.
  1908. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1909. * @param {boolean} [reverse] - If true, iterates backward on the loopable.
  1910. */
  1911. each: function(loopable, fn, thisArg, reverse) {
  1912. var i, len, keys;
  1913. if (helpers.isArray(loopable)) {
  1914. len = loopable.length;
  1915. if (reverse) {
  1916. for (i = len - 1; i >= 0; i--) {
  1917. fn.call(thisArg, loopable[i], i);
  1918. }
  1919. } else {
  1920. for (i = 0; i < len; i++) {
  1921. fn.call(thisArg, loopable[i], i);
  1922. }
  1923. }
  1924. } else if (helpers.isObject(loopable)) {
  1925. keys = Object.keys(loopable);
  1926. len = keys.length;
  1927. for (i = 0; i < len; i++) {
  1928. fn.call(thisArg, loopable[keys[i]], keys[i]);
  1929. }
  1930. }
  1931. },
  1932. /**
  1933. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  1934. * @see https://stackoverflow.com/a/14853974
  1935. * @param {Array} a0 - The array to compare
  1936. * @param {Array} a1 - The array to compare
  1937. * @returns {boolean}
  1938. */
  1939. arrayEquals: function(a0, a1) {
  1940. var i, ilen, v0, v1;
  1941. if (!a0 || !a1 || a0.length !== a1.length) {
  1942. return false;
  1943. }
  1944. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  1945. v0 = a0[i];
  1946. v1 = a1[i];
  1947. if (v0 instanceof Array && v1 instanceof Array) {
  1948. if (!helpers.arrayEquals(v0, v1)) {
  1949. return false;
  1950. }
  1951. } else if (v0 !== v1) {
  1952. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  1953. return false;
  1954. }
  1955. }
  1956. return true;
  1957. },
  1958. /**
  1959. * Returns a deep copy of `source` without keeping references on objects and arrays.
  1960. * @param {*} source - The value to clone.
  1961. * @returns {*}
  1962. */
  1963. clone: function(source) {
  1964. if (helpers.isArray(source)) {
  1965. return source.map(helpers.clone);
  1966. }
  1967. if (helpers.isObject(source)) {
  1968. var target = Object.create(source);
  1969. var keys = Object.keys(source);
  1970. var klen = keys.length;
  1971. var k = 0;
  1972. for (; k < klen; ++k) {
  1973. target[keys[k]] = helpers.clone(source[keys[k]]);
  1974. }
  1975. return target;
  1976. }
  1977. return source;
  1978. },
  1979. /**
  1980. * The default merger when Chart.helpers.merge is called without merger option.
  1981. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
  1982. * @private
  1983. */
  1984. _merger: function(key, target, source, options) {
  1985. if (!isValidKey(key)) {
  1986. // We want to ensure we do not copy prototypes over
  1987. // as this can pollute global namespaces
  1988. return;
  1989. }
  1990. var tval = target[key];
  1991. var sval = source[key];
  1992. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1993. helpers.merge(tval, sval, options);
  1994. } else {
  1995. target[key] = helpers.clone(sval);
  1996. }
  1997. },
  1998. /**
  1999. * Merges source[key] in target[key] only if target[key] is undefined.
  2000. * @private
  2001. */
  2002. _mergerIf: function(key, target, source) {
  2003. if (!isValidKey(key)) {
  2004. // We want to ensure we do not copy prototypes over
  2005. // as this can pollute global namespaces
  2006. return;
  2007. }
  2008. var tval = target[key];
  2009. var sval = source[key];
  2010. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  2011. helpers.mergeIf(tval, sval);
  2012. } else if (!target.hasOwnProperty(key)) {
  2013. target[key] = helpers.clone(sval);
  2014. }
  2015. },
  2016. /**
  2017. * Recursively deep copies `source` properties into `target` with the given `options`.
  2018. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2019. * @param {object} target - The target object in which all sources are merged into.
  2020. * @param {object|object[]} source - Object(s) to merge into `target`.
  2021. * @param {object} [options] - Merging options:
  2022. * @param {function} [options.merger] - The merge method (key, target, source, options)
  2023. * @returns {object} The `target` object.
  2024. */
  2025. merge: function(target, source, options) {
  2026. var sources = helpers.isArray(source) ? source : [source];
  2027. var ilen = sources.length;
  2028. var merge, i, keys, klen, k;
  2029. if (!helpers.isObject(target)) {
  2030. return target;
  2031. }
  2032. options = options || {};
  2033. merge = options.merger || helpers._merger;
  2034. for (i = 0; i < ilen; ++i) {
  2035. source = sources[i];
  2036. if (!helpers.isObject(source)) {
  2037. continue;
  2038. }
  2039. keys = Object.keys(source);
  2040. for (k = 0, klen = keys.length; k < klen; ++k) {
  2041. merge(keys[k], target, source, options);
  2042. }
  2043. }
  2044. return target;
  2045. },
  2046. /**
  2047. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  2048. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2049. * @param {object} target - The target object in which all sources are merged into.
  2050. * @param {object|object[]} source - Object(s) to merge into `target`.
  2051. * @returns {object} The `target` object.
  2052. */
  2053. mergeIf: function(target, source) {
  2054. return helpers.merge(target, source, {merger: helpers._mergerIf});
  2055. },
  2056. /**
  2057. * Applies the contents of two or more objects together into the first object.
  2058. * @param {object} target - The target object in which all objects are merged into.
  2059. * @param {object} arg1 - Object containing additional properties to merge in target.
  2060. * @param {object} argN - Additional objects containing properties to merge in target.
  2061. * @returns {object} The `target` object.
  2062. */
  2063. extend: Object.assign || function(target) {
  2064. return helpers.merge(target, [].slice.call(arguments, 1), {
  2065. merger: function(key, dst, src) {
  2066. dst[key] = src[key];
  2067. }
  2068. });
  2069. },
  2070. /**
  2071. * Basic javascript inheritance based on the model created in Backbone.js
  2072. */
  2073. inherits: function(extensions) {
  2074. var me = this;
  2075. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
  2076. return me.apply(this, arguments);
  2077. };
  2078. var Surrogate = function() {
  2079. this.constructor = ChartElement;
  2080. };
  2081. Surrogate.prototype = me.prototype;
  2082. ChartElement.prototype = new Surrogate();
  2083. ChartElement.extend = helpers.inherits;
  2084. if (extensions) {
  2085. helpers.extend(ChartElement.prototype, extensions);
  2086. }
  2087. ChartElement.__super__ = me.prototype;
  2088. return ChartElement;
  2089. },
  2090. _deprecated: function(scope, value, previous, current) {
  2091. if (value !== undefined) {
  2092. console.warn(scope + ': "' + previous +
  2093. '" is deprecated. Please use "' + current + '" instead');
  2094. }
  2095. }
  2096. };
  2097. var helpers_core = helpers;
  2098. // DEPRECATIONS
  2099. /**
  2100. * Provided for backward compatibility, use Chart.helpers.callback instead.
  2101. * @function Chart.helpers.callCallback
  2102. * @deprecated since version 2.6.0
  2103. * @todo remove at version 3
  2104. * @private
  2105. */
  2106. helpers.callCallback = helpers.callback;
  2107. /**
  2108. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  2109. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  2110. * @function Chart.helpers.indexOf
  2111. * @deprecated since version 2.7.0
  2112. * @todo remove at version 3
  2113. * @private
  2114. */
  2115. helpers.indexOf = function(array, item, fromIndex) {
  2116. return Array.prototype.indexOf.call(array, item, fromIndex);
  2117. };
  2118. /**
  2119. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  2120. * @function Chart.helpers.getValueOrDefault
  2121. * @deprecated since version 2.7.0
  2122. * @todo remove at version 3
  2123. * @private
  2124. */
  2125. helpers.getValueOrDefault = helpers.valueOrDefault;
  2126. /**
  2127. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  2128. * @function Chart.helpers.getValueAtIndexOrDefault
  2129. * @deprecated since version 2.7.0
  2130. * @todo remove at version 3
  2131. * @private
  2132. */
  2133. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  2134. /**
  2135. * Easing functions adapted from Robert Penner's easing equations.
  2136. * @namespace Chart.helpers.easingEffects
  2137. * @see http://www.robertpenner.com/easing/
  2138. */
  2139. var effects = {
  2140. linear: function(t) {
  2141. return t;
  2142. },
  2143. easeInQuad: function(t) {
  2144. return t * t;
  2145. },
  2146. easeOutQuad: function(t) {
  2147. return -t * (t - 2);
  2148. },
  2149. easeInOutQuad: function(t) {
  2150. if ((t /= 0.5) < 1) {
  2151. return 0.5 * t * t;
  2152. }
  2153. return -0.5 * ((--t) * (t - 2) - 1);
  2154. },
  2155. easeInCubic: function(t) {
  2156. return t * t * t;
  2157. },
  2158. easeOutCubic: function(t) {
  2159. return (t = t - 1) * t * t + 1;
  2160. },
  2161. easeInOutCubic: function(t) {
  2162. if ((t /= 0.5) < 1) {
  2163. return 0.5 * t * t * t;
  2164. }
  2165. return 0.5 * ((t -= 2) * t * t + 2);
  2166. },
  2167. easeInQuart: function(t) {
  2168. return t * t * t * t;
  2169. },
  2170. easeOutQuart: function(t) {
  2171. return -((t = t - 1) * t * t * t - 1);
  2172. },
  2173. easeInOutQuart: function(t) {
  2174. if ((t /= 0.5) < 1) {
  2175. return 0.5 * t * t * t * t;
  2176. }
  2177. return -0.5 * ((t -= 2) * t * t * t - 2);
  2178. },
  2179. easeInQuint: function(t) {
  2180. return t * t * t * t * t;
  2181. },
  2182. easeOutQuint: function(t) {
  2183. return (t = t - 1) * t * t * t * t + 1;
  2184. },
  2185. easeInOutQuint: function(t) {
  2186. if ((t /= 0.5) < 1) {
  2187. return 0.5 * t * t * t * t * t;
  2188. }
  2189. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  2190. },
  2191. easeInSine: function(t) {
  2192. return -Math.cos(t * (Math.PI / 2)) + 1;
  2193. },
  2194. easeOutSine: function(t) {
  2195. return Math.sin(t * (Math.PI / 2));
  2196. },
  2197. easeInOutSine: function(t) {
  2198. return -0.5 * (Math.cos(Math.PI * t) - 1);
  2199. },
  2200. easeInExpo: function(t) {
  2201. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  2202. },
  2203. easeOutExpo: function(t) {
  2204. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  2205. },
  2206. easeInOutExpo: function(t) {
  2207. if (t === 0) {
  2208. return 0;
  2209. }
  2210. if (t === 1) {
  2211. return 1;
  2212. }
  2213. if ((t /= 0.5) < 1) {
  2214. return 0.5 * Math.pow(2, 10 * (t - 1));
  2215. }
  2216. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  2217. },
  2218. easeInCirc: function(t) {
  2219. if (t >= 1) {
  2220. return t;
  2221. }
  2222. return -(Math.sqrt(1 - t * t) - 1);
  2223. },
  2224. easeOutCirc: function(t) {
  2225. return Math.sqrt(1 - (t = t - 1) * t);
  2226. },
  2227. easeInOutCirc: function(t) {
  2228. if ((t /= 0.5) < 1) {
  2229. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  2230. }
  2231. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  2232. },
  2233. easeInElastic: function(t) {
  2234. var s = 1.70158;
  2235. var p = 0;
  2236. var a = 1;
  2237. if (t === 0) {
  2238. return 0;
  2239. }
  2240. if (t === 1) {
  2241. return 1;
  2242. }
  2243. if (!p) {
  2244. p = 0.3;
  2245. }
  2246. if (a < 1) {
  2247. a = 1;
  2248. s = p / 4;
  2249. } else {
  2250. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2251. }
  2252. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2253. },
  2254. easeOutElastic: function(t) {
  2255. var s = 1.70158;
  2256. var p = 0;
  2257. var a = 1;
  2258. if (t === 0) {
  2259. return 0;
  2260. }
  2261. if (t === 1) {
  2262. return 1;
  2263. }
  2264. if (!p) {
  2265. p = 0.3;
  2266. }
  2267. if (a < 1) {
  2268. a = 1;
  2269. s = p / 4;
  2270. } else {
  2271. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2272. }
  2273. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  2274. },
  2275. easeInOutElastic: function(t) {
  2276. var s = 1.70158;
  2277. var p = 0;
  2278. var a = 1;
  2279. if (t === 0) {
  2280. return 0;
  2281. }
  2282. if ((t /= 0.5) === 2) {
  2283. return 1;
  2284. }
  2285. if (!p) {
  2286. p = 0.45;
  2287. }
  2288. if (a < 1) {
  2289. a = 1;
  2290. s = p / 4;
  2291. } else {
  2292. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2293. }
  2294. if (t < 1) {
  2295. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2296. }
  2297. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2298. },
  2299. easeInBack: function(t) {
  2300. var s = 1.70158;
  2301. return t * t * ((s + 1) * t - s);
  2302. },
  2303. easeOutBack: function(t) {
  2304. var s = 1.70158;
  2305. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  2306. },
  2307. easeInOutBack: function(t) {
  2308. var s = 1.70158;
  2309. if ((t /= 0.5) < 1) {
  2310. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  2311. }
  2312. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  2313. },
  2314. easeInBounce: function(t) {
  2315. return 1 - effects.easeOutBounce(1 - t);
  2316. },
  2317. easeOutBounce: function(t) {
  2318. if (t < (1 / 2.75)) {
  2319. return 7.5625 * t * t;
  2320. }
  2321. if (t < (2 / 2.75)) {
  2322. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  2323. }
  2324. if (t < (2.5 / 2.75)) {
  2325. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  2326. }
  2327. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  2328. },
  2329. easeInOutBounce: function(t) {
  2330. if (t < 0.5) {
  2331. return effects.easeInBounce(t * 2) * 0.5;
  2332. }
  2333. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  2334. }
  2335. };
  2336. var helpers_easing = {
  2337. effects: effects
  2338. };
  2339. // DEPRECATIONS
  2340. /**
  2341. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  2342. * @function Chart.helpers.easingEffects
  2343. * @deprecated since version 2.7.0
  2344. * @todo remove at version 3
  2345. * @private
  2346. */
  2347. helpers_core.easingEffects = effects;
  2348. var PI = Math.PI;
  2349. var RAD_PER_DEG = PI / 180;
  2350. var DOUBLE_PI = PI * 2;
  2351. var HALF_PI = PI / 2;
  2352. var QUARTER_PI = PI / 4;
  2353. var TWO_THIRDS_PI = PI * 2 / 3;
  2354. /**
  2355. * @namespace Chart.helpers.canvas
  2356. */
  2357. var exports$1 = {
  2358. /**
  2359. * Clears the entire canvas associated to the given `chart`.
  2360. * @param {Chart} chart - The chart for which to clear the canvas.
  2361. */
  2362. clear: function(chart) {
  2363. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  2364. },
  2365. /**
  2366. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  2367. * given size (width, height) and the same `radius` for all corners.
  2368. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  2369. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  2370. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  2371. * @param {number} width - The rectangle's width.
  2372. * @param {number} height - The rectangle's height.
  2373. * @param {number} radius - The rounded amount (in pixels) for the four corners.
  2374. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  2375. */
  2376. roundedRect: function(ctx, x, y, width, height, radius) {
  2377. if (radius) {
  2378. var r = Math.min(radius, height / 2, width / 2);
  2379. var left = x + r;
  2380. var top = y + r;
  2381. var right = x + width - r;
  2382. var bottom = y + height - r;
  2383. ctx.moveTo(x, top);
  2384. if (left < right && top < bottom) {
  2385. ctx.arc(left, top, r, -PI, -HALF_PI);
  2386. ctx.arc(right, top, r, -HALF_PI, 0);
  2387. ctx.arc(right, bottom, r, 0, HALF_PI);
  2388. ctx.arc(left, bottom, r, HALF_PI, PI);
  2389. } else if (left < right) {
  2390. ctx.moveTo(left, y);
  2391. ctx.arc(right, top, r, -HALF_PI, HALF_PI);
  2392. ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
  2393. } else if (top < bottom) {
  2394. ctx.arc(left, top, r, -PI, 0);
  2395. ctx.arc(left, bottom, r, 0, PI);
  2396. } else {
  2397. ctx.arc(left, top, r, -PI, PI);
  2398. }
  2399. ctx.closePath();
  2400. ctx.moveTo(x, y);
  2401. } else {
  2402. ctx.rect(x, y, width, height);
  2403. }
  2404. },
  2405. drawPoint: function(ctx, style, radius, x, y, rotation) {
  2406. var type, xOffset, yOffset, size, cornerRadius;
  2407. var rad = (rotation || 0) * RAD_PER_DEG;
  2408. if (style && typeof style === 'object') {
  2409. type = style.toString();
  2410. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  2411. ctx.save();
  2412. ctx.translate(x, y);
  2413. ctx.rotate(rad);
  2414. ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
  2415. ctx.restore();
  2416. return;
  2417. }
  2418. }
  2419. if (isNaN(radius) || radius <= 0) {
  2420. return;
  2421. }
  2422. ctx.beginPath();
  2423. switch (style) {
  2424. // Default includes circle
  2425. default:
  2426. ctx.arc(x, y, radius, 0, DOUBLE_PI);
  2427. ctx.closePath();
  2428. break;
  2429. case 'triangle':
  2430. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2431. rad += TWO_THIRDS_PI;
  2432. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2433. rad += TWO_THIRDS_PI;
  2434. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2435. ctx.closePath();
  2436. break;
  2437. case 'rectRounded':
  2438. // NOTE: the rounded rect implementation changed to use `arc` instead of
  2439. // `quadraticCurveTo` since it generates better results when rect is
  2440. // almost a circle. 0.516 (instead of 0.5) produces results with visually
  2441. // closer proportion to the previous impl and it is inscribed in the
  2442. // circle with `radius`. For more details, see the following PRs:
  2443. // https://github.com/chartjs/Chart.js/issues/5597
  2444. // https://github.com/chartjs/Chart.js/issues/5858
  2445. cornerRadius = radius * 0.516;
  2446. size = radius - cornerRadius;
  2447. xOffset = Math.cos(rad + QUARTER_PI) * size;
  2448. yOffset = Math.sin(rad + QUARTER_PI) * size;
  2449. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  2450. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  2451. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  2452. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  2453. ctx.closePath();
  2454. break;
  2455. case 'rect':
  2456. if (!rotation) {
  2457. size = Math.SQRT1_2 * radius;
  2458. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  2459. break;
  2460. }
  2461. rad += QUARTER_PI;
  2462. /* falls through */
  2463. case 'rectRot':
  2464. xOffset = Math.cos(rad) * radius;
  2465. yOffset = Math.sin(rad) * radius;
  2466. ctx.moveTo(x - xOffset, y - yOffset);
  2467. ctx.lineTo(x + yOffset, y - xOffset);
  2468. ctx.lineTo(x + xOffset, y + yOffset);
  2469. ctx.lineTo(x - yOffset, y + xOffset);
  2470. ctx.closePath();
  2471. break;
  2472. case 'crossRot':
  2473. rad += QUARTER_PI;
  2474. /* falls through */
  2475. case 'cross':
  2476. xOffset = Math.cos(rad) * radius;
  2477. yOffset = Math.sin(rad) * radius;
  2478. ctx.moveTo(x - xOffset, y - yOffset);
  2479. ctx.lineTo(x + xOffset, y + yOffset);
  2480. ctx.moveTo(x + yOffset, y - xOffset);
  2481. ctx.lineTo(x - yOffset, y + xOffset);
  2482. break;
  2483. case 'star':
  2484. xOffset = Math.cos(rad) * radius;
  2485. yOffset = Math.sin(rad) * radius;
  2486. ctx.moveTo(x - xOffset, y - yOffset);
  2487. ctx.lineTo(x + xOffset, y + yOffset);
  2488. ctx.moveTo(x + yOffset, y - xOffset);
  2489. ctx.lineTo(x - yOffset, y + xOffset);
  2490. rad += QUARTER_PI;
  2491. xOffset = Math.cos(rad) * radius;
  2492. yOffset = Math.sin(rad) * radius;
  2493. ctx.moveTo(x - xOffset, y - yOffset);
  2494. ctx.lineTo(x + xOffset, y + yOffset);
  2495. ctx.moveTo(x + yOffset, y - xOffset);
  2496. ctx.lineTo(x - yOffset, y + xOffset);
  2497. break;
  2498. case 'line':
  2499. xOffset = Math.cos(rad) * radius;
  2500. yOffset = Math.sin(rad) * radius;
  2501. ctx.moveTo(x - xOffset, y - yOffset);
  2502. ctx.lineTo(x + xOffset, y + yOffset);
  2503. break;
  2504. case 'dash':
  2505. ctx.moveTo(x, y);
  2506. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  2507. break;
  2508. }
  2509. ctx.fill();
  2510. ctx.stroke();
  2511. },
  2512. /**
  2513. * Returns true if the point is inside the rectangle
  2514. * @param {object} point - The point to test
  2515. * @param {object} area - The rectangle
  2516. * @returns {boolean}
  2517. * @private
  2518. */
  2519. _isPointInArea: function(point, area) {
  2520. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  2521. return point.x > area.left - epsilon && point.x < area.right + epsilon &&
  2522. point.y > area.top - epsilon && point.y < area.bottom + epsilon;
  2523. },
  2524. clipArea: function(ctx, area) {
  2525. ctx.save();
  2526. ctx.beginPath();
  2527. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  2528. ctx.clip();
  2529. },
  2530. unclipArea: function(ctx) {
  2531. ctx.restore();
  2532. },
  2533. lineTo: function(ctx, previous, target, flip) {
  2534. var stepped = target.steppedLine;
  2535. if (stepped) {
  2536. if (stepped === 'middle') {
  2537. var midpoint = (previous.x + target.x) / 2.0;
  2538. ctx.lineTo(midpoint, flip ? target.y : previous.y);
  2539. ctx.lineTo(midpoint, flip ? previous.y : target.y);
  2540. } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
  2541. ctx.lineTo(previous.x, target.y);
  2542. } else {
  2543. ctx.lineTo(target.x, previous.y);
  2544. }
  2545. ctx.lineTo(target.x, target.y);
  2546. return;
  2547. }
  2548. if (!target.tension) {
  2549. ctx.lineTo(target.x, target.y);
  2550. return;
  2551. }
  2552. ctx.bezierCurveTo(
  2553. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  2554. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  2555. flip ? target.controlPointNextX : target.controlPointPreviousX,
  2556. flip ? target.controlPointNextY : target.controlPointPreviousY,
  2557. target.x,
  2558. target.y);
  2559. }
  2560. };
  2561. var helpers_canvas = exports$1;
  2562. // DEPRECATIONS
  2563. /**
  2564. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  2565. * @namespace Chart.helpers.clear
  2566. * @deprecated since version 2.7.0
  2567. * @todo remove at version 3
  2568. * @private
  2569. */
  2570. helpers_core.clear = exports$1.clear;
  2571. /**
  2572. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  2573. * @namespace Chart.helpers.drawRoundedRectangle
  2574. * @deprecated since version 2.7.0
  2575. * @todo remove at version 3
  2576. * @private
  2577. */
  2578. helpers_core.drawRoundedRectangle = function(ctx) {
  2579. ctx.beginPath();
  2580. exports$1.roundedRect.apply(exports$1, arguments);
  2581. };
  2582. var defaults = {
  2583. /**
  2584. * @private
  2585. */
  2586. _set: function(scope, values) {
  2587. return helpers_core.merge(this[scope] || (this[scope] = {}), values);
  2588. }
  2589. };
  2590. // TODO(v3): remove 'global' from namespace. all default are global and
  2591. // there's inconsistency around which options are under 'global'
  2592. defaults._set('global', {
  2593. defaultColor: 'rgba(0,0,0,0.1)',
  2594. defaultFontColor: '#666',
  2595. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  2596. defaultFontSize: 12,
  2597. defaultFontStyle: 'normal',
  2598. defaultLineHeight: 1.2,
  2599. showLines: true
  2600. });
  2601. var core_defaults = defaults;
  2602. var valueOrDefault = helpers_core.valueOrDefault;
  2603. /**
  2604. * Converts the given font object into a CSS font string.
  2605. * @param {object} font - A font object.
  2606. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
  2607. * @private
  2608. */
  2609. function toFontString(font) {
  2610. if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
  2611. return null;
  2612. }
  2613. return (font.style ? font.style + ' ' : '')
  2614. + (font.weight ? font.weight + ' ' : '')
  2615. + font.size + 'px '
  2616. + font.family;
  2617. }
  2618. /**
  2619. * @alias Chart.helpers.options
  2620. * @namespace
  2621. */
  2622. var helpers_options = {
  2623. /**
  2624. * Converts the given line height `value` in pixels for a specific font `size`.
  2625. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  2626. * @param {number} size - The font size (in pixels) used to resolve relative `value`.
  2627. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
  2628. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  2629. * @since 2.7.0
  2630. */
  2631. toLineHeight: function(value, size) {
  2632. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  2633. if (!matches || matches[1] === 'normal') {
  2634. return size * 1.2;
  2635. }
  2636. value = +matches[2];
  2637. switch (matches[3]) {
  2638. case 'px':
  2639. return value;
  2640. case '%':
  2641. value /= 100;
  2642. break;
  2643. }
  2644. return size * value;
  2645. },
  2646. /**
  2647. * Converts the given value into a padding object with pre-computed width/height.
  2648. * @param {number|object} value - If a number, set the value to all TRBL component,
  2649. * else, if and object, use defined properties and sets undefined ones to 0.
  2650. * @returns {object} The padding values (top, right, bottom, left, width, height)
  2651. * @since 2.7.0
  2652. */
  2653. toPadding: function(value) {
  2654. var t, r, b, l;
  2655. if (helpers_core.isObject(value)) {
  2656. t = +value.top || 0;
  2657. r = +value.right || 0;
  2658. b = +value.bottom || 0;
  2659. l = +value.left || 0;
  2660. } else {
  2661. t = r = b = l = +value || 0;
  2662. }
  2663. return {
  2664. top: t,
  2665. right: r,
  2666. bottom: b,
  2667. left: l,
  2668. height: t + b,
  2669. width: l + r
  2670. };
  2671. },
  2672. /**
  2673. * Parses font options and returns the font object.
  2674. * @param {object} options - A object that contains font options to be parsed.
  2675. * @return {object} The font object.
  2676. * @todo Support font.* options and renamed to toFont().
  2677. * @private
  2678. */
  2679. _parseFont: function(options) {
  2680. var globalDefaults = core_defaults.global;
  2681. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  2682. var font = {
  2683. family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
  2684. lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
  2685. size: size,
  2686. style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
  2687. weight: null,
  2688. string: ''
  2689. };
  2690. font.string = toFontString(font);
  2691. return font;
  2692. },
  2693. /**
  2694. * Evaluates the given `inputs` sequentially and returns the first defined value.
  2695. * @param {Array} inputs - An array of values, falling back to the last value.
  2696. * @param {object} [context] - If defined and the current value is a function, the value
  2697. * is called with `context` as first argument and the result becomes the new input.
  2698. * @param {number} [index] - If defined and the current value is an array, the value
  2699. * at `index` become the new input.
  2700. * @param {object} [info] - object to return information about resolution in
  2701. * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable.
  2702. * @since 2.7.0
  2703. */
  2704. resolve: function(inputs, context, index, info) {
  2705. var cacheable = true;
  2706. var i, ilen, value;
  2707. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  2708. value = inputs[i];
  2709. if (value === undefined) {
  2710. continue;
  2711. }
  2712. if (context !== undefined && typeof value === 'function') {
  2713. value = value(context);
  2714. cacheable = false;
  2715. }
  2716. if (index !== undefined && helpers_core.isArray(value)) {
  2717. value = value[index];
  2718. cacheable = false;
  2719. }
  2720. if (value !== undefined) {
  2721. if (info && !cacheable) {
  2722. info.cacheable = false;
  2723. }
  2724. return value;
  2725. }
  2726. }
  2727. }
  2728. };
  2729. /**
  2730. * @alias Chart.helpers.math
  2731. * @namespace
  2732. */
  2733. var exports$2 = {
  2734. /**
  2735. * Returns an array of factors sorted from 1 to sqrt(value)
  2736. * @private
  2737. */
  2738. _factorize: function(value) {
  2739. var result = [];
  2740. var sqrt = Math.sqrt(value);
  2741. var i;
  2742. for (i = 1; i < sqrt; i++) {
  2743. if (value % i === 0) {
  2744. result.push(i);
  2745. result.push(value / i);
  2746. }
  2747. }
  2748. if (sqrt === (sqrt | 0)) { // if value is a square number
  2749. result.push(sqrt);
  2750. }
  2751. result.sort(function(a, b) {
  2752. return a - b;
  2753. }).pop();
  2754. return result;
  2755. },
  2756. log10: Math.log10 || function(x) {
  2757. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  2758. // Check for whole powers of 10,
  2759. // which due to floating point rounding error should be corrected.
  2760. var powerOf10 = Math.round(exponent);
  2761. var isPowerOf10 = x === Math.pow(10, powerOf10);
  2762. return isPowerOf10 ? powerOf10 : exponent;
  2763. }
  2764. };
  2765. var helpers_math = exports$2;
  2766. // DEPRECATIONS
  2767. /**
  2768. * Provided for backward compatibility, use Chart.helpers.math.log10 instead.
  2769. * @namespace Chart.helpers.log10
  2770. * @deprecated since version 2.9.0
  2771. * @todo remove at version 3
  2772. * @private
  2773. */
  2774. helpers_core.log10 = exports$2.log10;
  2775. var getRtlAdapter = function(rectX, width) {
  2776. return {
  2777. x: function(x) {
  2778. return rectX + rectX + width - x;
  2779. },
  2780. setWidth: function(w) {
  2781. width = w;
  2782. },
  2783. textAlign: function(align) {
  2784. if (align === 'center') {
  2785. return align;
  2786. }
  2787. return align === 'right' ? 'left' : 'right';
  2788. },
  2789. xPlus: function(x, value) {
  2790. return x - value;
  2791. },
  2792. leftForLtr: function(x, itemWidth) {
  2793. return x - itemWidth;
  2794. },
  2795. };
  2796. };
  2797. var getLtrAdapter = function() {
  2798. return {
  2799. x: function(x) {
  2800. return x;
  2801. },
  2802. setWidth: function(w) { // eslint-disable-line no-unused-vars
  2803. },
  2804. textAlign: function(align) {
  2805. return align;
  2806. },
  2807. xPlus: function(x, value) {
  2808. return x + value;
  2809. },
  2810. leftForLtr: function(x, _itemWidth) { // eslint-disable-line no-unused-vars
  2811. return x;
  2812. },
  2813. };
  2814. };
  2815. var getAdapter = function(rtl, rectX, width) {
  2816. return rtl ? getRtlAdapter(rectX, width) : getLtrAdapter();
  2817. };
  2818. var overrideTextDirection = function(ctx, direction) {
  2819. var style, original;
  2820. if (direction === 'ltr' || direction === 'rtl') {
  2821. style = ctx.canvas.style;
  2822. original = [
  2823. style.getPropertyValue('direction'),
  2824. style.getPropertyPriority('direction'),
  2825. ];
  2826. style.setProperty('direction', direction, 'important');
  2827. ctx.prevTextDirection = original;
  2828. }
  2829. };
  2830. var restoreTextDirection = function(ctx) {
  2831. var original = ctx.prevTextDirection;
  2832. if (original !== undefined) {
  2833. delete ctx.prevTextDirection;
  2834. ctx.canvas.style.setProperty('direction', original[0], original[1]);
  2835. }
  2836. };
  2837. var helpers_rtl = {
  2838. getRtlAdapter: getAdapter,
  2839. overrideTextDirection: overrideTextDirection,
  2840. restoreTextDirection: restoreTextDirection,
  2841. };
  2842. var helpers$1 = helpers_core;
  2843. var easing = helpers_easing;
  2844. var canvas = helpers_canvas;
  2845. var options = helpers_options;
  2846. var math = helpers_math;
  2847. var rtl = helpers_rtl;
  2848. helpers$1.easing = easing;
  2849. helpers$1.canvas = canvas;
  2850. helpers$1.options = options;
  2851. helpers$1.math = math;
  2852. helpers$1.rtl = rtl;
  2853. function interpolate(start, view, model, ease) {
  2854. var keys = Object.keys(model);
  2855. var i, ilen, key, actual, origin, target, type, c0, c1;
  2856. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  2857. key = keys[i];
  2858. target = model[key];
  2859. // if a value is added to the model after pivot() has been called, the view
  2860. // doesn't contain it, so let's initialize the view to the target value.
  2861. if (!view.hasOwnProperty(key)) {
  2862. view[key] = target;
  2863. }
  2864. actual = view[key];
  2865. if (actual === target || key[0] === '_') {
  2866. continue;
  2867. }
  2868. if (!start.hasOwnProperty(key)) {
  2869. start[key] = actual;
  2870. }
  2871. origin = start[key];
  2872. type = typeof target;
  2873. if (type === typeof origin) {
  2874. if (type === 'string') {
  2875. c0 = chartjsColor(origin);
  2876. if (c0.valid) {
  2877. c1 = chartjsColor(target);
  2878. if (c1.valid) {
  2879. view[key] = c1.mix(c0, ease).rgbString();
  2880. continue;
  2881. }
  2882. }
  2883. } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
  2884. view[key] = origin + (target - origin) * ease;
  2885. continue;
  2886. }
  2887. }
  2888. view[key] = target;
  2889. }
  2890. }
  2891. var Element = function(configuration) {
  2892. helpers$1.extend(this, configuration);
  2893. this.initialize.apply(this, arguments);
  2894. };
  2895. helpers$1.extend(Element.prototype, {
  2896. _type: undefined,
  2897. initialize: function() {
  2898. this.hidden = false;
  2899. },
  2900. pivot: function() {
  2901. var me = this;
  2902. if (!me._view) {
  2903. me._view = helpers$1.extend({}, me._model);
  2904. }
  2905. me._start = {};
  2906. return me;
  2907. },
  2908. transition: function(ease) {
  2909. var me = this;
  2910. var model = me._model;
  2911. var start = me._start;
  2912. var view = me._view;
  2913. // No animation -> No Transition
  2914. if (!model || ease === 1) {
  2915. me._view = helpers$1.extend({}, model);
  2916. me._start = null;
  2917. return me;
  2918. }
  2919. if (!view) {
  2920. view = me._view = {};
  2921. }
  2922. if (!start) {
  2923. start = me._start = {};
  2924. }
  2925. interpolate(start, view, model, ease);
  2926. return me;
  2927. },
  2928. tooltipPosition: function() {
  2929. return {
  2930. x: this._model.x,
  2931. y: this._model.y
  2932. };
  2933. },
  2934. hasValue: function() {
  2935. return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
  2936. }
  2937. });
  2938. Element.extend = helpers$1.inherits;
  2939. var core_element = Element;
  2940. var exports$3 = core_element.extend({
  2941. chart: null, // the animation associated chart instance
  2942. currentStep: 0, // the current animation step
  2943. numSteps: 60, // default number of steps
  2944. easing: '', // the easing to use for this animation
  2945. render: null, // render function used by the animation service
  2946. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  2947. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  2948. });
  2949. var core_animation = exports$3;
  2950. // DEPRECATIONS
  2951. /**
  2952. * Provided for backward compatibility, use Chart.Animation instead
  2953. * @prop Chart.Animation#animationObject
  2954. * @deprecated since version 2.6.0
  2955. * @todo remove at version 3
  2956. */
  2957. Object.defineProperty(exports$3.prototype, 'animationObject', {
  2958. get: function() {
  2959. return this;
  2960. }
  2961. });
  2962. /**
  2963. * Provided for backward compatibility, use Chart.Animation#chart instead
  2964. * @prop Chart.Animation#chartInstance
  2965. * @deprecated since version 2.6.0
  2966. * @todo remove at version 3
  2967. */
  2968. Object.defineProperty(exports$3.prototype, 'chartInstance', {
  2969. get: function() {
  2970. return this.chart;
  2971. },
  2972. set: function(value) {
  2973. this.chart = value;
  2974. }
  2975. });
  2976. core_defaults._set('global', {
  2977. animation: {
  2978. duration: 1000,
  2979. easing: 'easeOutQuart',
  2980. onProgress: helpers$1.noop,
  2981. onComplete: helpers$1.noop
  2982. }
  2983. });
  2984. var core_animations = {
  2985. animations: [],
  2986. request: null,
  2987. /**
  2988. * @param {Chart} chart - The chart to animate.
  2989. * @param {Chart.Animation} animation - The animation that we will animate.
  2990. * @param {number} duration - The animation duration in ms.
  2991. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  2992. */
  2993. addAnimation: function(chart, animation, duration, lazy) {
  2994. var animations = this.animations;
  2995. var i, ilen;
  2996. animation.chart = chart;
  2997. animation.startTime = Date.now();
  2998. animation.duration = duration;
  2999. if (!lazy) {
  3000. chart.animating = true;
  3001. }
  3002. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  3003. if (animations[i].chart === chart) {
  3004. animations[i] = animation;
  3005. return;
  3006. }
  3007. }
  3008. animations.push(animation);
  3009. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  3010. if (animations.length === 1) {
  3011. this.requestAnimationFrame();
  3012. }
  3013. },
  3014. cancelAnimation: function(chart) {
  3015. var index = helpers$1.findIndex(this.animations, function(animation) {
  3016. return animation.chart === chart;
  3017. });
  3018. if (index !== -1) {
  3019. this.animations.splice(index, 1);
  3020. chart.animating = false;
  3021. }
  3022. },
  3023. requestAnimationFrame: function() {
  3024. var me = this;
  3025. if (me.request === null) {
  3026. // Skip animation frame requests until the active one is executed.
  3027. // This can happen when processing mouse events, e.g. 'mousemove'
  3028. // and 'mouseout' events will trigger multiple renders.
  3029. me.request = helpers$1.requestAnimFrame.call(window, function() {
  3030. me.request = null;
  3031. me.startDigest();
  3032. });
  3033. }
  3034. },
  3035. /**
  3036. * @private
  3037. */
  3038. startDigest: function() {
  3039. var me = this;
  3040. me.advance();
  3041. // Do we have more stuff to animate?
  3042. if (me.animations.length > 0) {
  3043. me.requestAnimationFrame();
  3044. }
  3045. },
  3046. /**
  3047. * @private
  3048. */
  3049. advance: function() {
  3050. var animations = this.animations;
  3051. var animation, chart, numSteps, nextStep;
  3052. var i = 0;
  3053. // 1 animation per chart, so we are looping charts here
  3054. while (i < animations.length) {
  3055. animation = animations[i];
  3056. chart = animation.chart;
  3057. numSteps = animation.numSteps;
  3058. // Make sure that currentStep starts at 1
  3059. // https://github.com/chartjs/Chart.js/issues/6104
  3060. nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
  3061. animation.currentStep = Math.min(nextStep, numSteps);
  3062. helpers$1.callback(animation.render, [chart, animation], chart);
  3063. helpers$1.callback(animation.onAnimationProgress, [animation], chart);
  3064. if (animation.currentStep >= numSteps) {
  3065. helpers$1.callback(animation.onAnimationComplete, [animation], chart);
  3066. chart.animating = false;
  3067. animations.splice(i, 1);
  3068. } else {
  3069. ++i;
  3070. }
  3071. }
  3072. }
  3073. };
  3074. var resolve = helpers$1.options.resolve;
  3075. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  3076. /**
  3077. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  3078. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  3079. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  3080. */
  3081. function listenArrayEvents(array, listener) {
  3082. if (array._chartjs) {
  3083. array._chartjs.listeners.push(listener);
  3084. return;
  3085. }
  3086. Object.defineProperty(array, '_chartjs', {
  3087. configurable: true,
  3088. enumerable: false,
  3089. value: {
  3090. listeners: [listener]
  3091. }
  3092. });
  3093. arrayEvents.forEach(function(key) {
  3094. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  3095. var base = array[key];
  3096. Object.defineProperty(array, key, {
  3097. configurable: true,
  3098. enumerable: false,
  3099. value: function() {
  3100. var args = Array.prototype.slice.call(arguments);
  3101. var res = base.apply(this, args);
  3102. helpers$1.each(array._chartjs.listeners, function(object) {
  3103. if (typeof object[method] === 'function') {
  3104. object[method].apply(object, args);
  3105. }
  3106. });
  3107. return res;
  3108. }
  3109. });
  3110. });
  3111. }
  3112. /**
  3113. * Removes the given array event listener and cleanup extra attached properties (such as
  3114. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  3115. */
  3116. function unlistenArrayEvents(array, listener) {
  3117. var stub = array._chartjs;
  3118. if (!stub) {
  3119. return;
  3120. }
  3121. var listeners = stub.listeners;
  3122. var index = listeners.indexOf(listener);
  3123. if (index !== -1) {
  3124. listeners.splice(index, 1);
  3125. }
  3126. if (listeners.length > 0) {
  3127. return;
  3128. }
  3129. arrayEvents.forEach(function(key) {
  3130. delete array[key];
  3131. });
  3132. delete array._chartjs;
  3133. }
  3134. // Base class for all dataset controllers (line, bar, etc)
  3135. var DatasetController = function(chart, datasetIndex) {
  3136. this.initialize(chart, datasetIndex);
  3137. };
  3138. helpers$1.extend(DatasetController.prototype, {
  3139. /**
  3140. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  3141. * @type {Chart.core.element}
  3142. */
  3143. datasetElementType: null,
  3144. /**
  3145. * Element type used to generate a meta data (e.g. Chart.element.Point).
  3146. * @type {Chart.core.element}
  3147. */
  3148. dataElementType: null,
  3149. /**
  3150. * Dataset element option keys to be resolved in _resolveDatasetElementOptions.
  3151. * A derived controller may override this to resolve controller-specific options.
  3152. * The keys defined here are for backward compatibility for legend styles.
  3153. * @private
  3154. */
  3155. _datasetElementOptions: [
  3156. 'backgroundColor',
  3157. 'borderCapStyle',
  3158. 'borderColor',
  3159. 'borderDash',
  3160. 'borderDashOffset',
  3161. 'borderJoinStyle',
  3162. 'borderWidth'
  3163. ],
  3164. /**
  3165. * Data element option keys to be resolved in _resolveDataElementOptions.
  3166. * A derived controller may override this to resolve controller-specific options.
  3167. * The keys defined here are for backward compatibility for legend styles.
  3168. * @private
  3169. */
  3170. _dataElementOptions: [
  3171. 'backgroundColor',
  3172. 'borderColor',
  3173. 'borderWidth',
  3174. 'pointStyle'
  3175. ],
  3176. initialize: function(chart, datasetIndex) {
  3177. var me = this;
  3178. me.chart = chart;
  3179. me.index = datasetIndex;
  3180. me.linkScales();
  3181. me.addElements();
  3182. me._type = me.getMeta().type;
  3183. },
  3184. updateIndex: function(datasetIndex) {
  3185. this.index = datasetIndex;
  3186. },
  3187. linkScales: function() {
  3188. var me = this;
  3189. var meta = me.getMeta();
  3190. var chart = me.chart;
  3191. var scales = chart.scales;
  3192. var dataset = me.getDataset();
  3193. var scalesOpts = chart.options.scales;
  3194. if (meta.xAxisID === null || !(meta.xAxisID in scales) || dataset.xAxisID) {
  3195. meta.xAxisID = dataset.xAxisID || scalesOpts.xAxes[0].id;
  3196. }
  3197. if (meta.yAxisID === null || !(meta.yAxisID in scales) || dataset.yAxisID) {
  3198. meta.yAxisID = dataset.yAxisID || scalesOpts.yAxes[0].id;
  3199. }
  3200. },
  3201. getDataset: function() {
  3202. return this.chart.data.datasets[this.index];
  3203. },
  3204. getMeta: function() {
  3205. return this.chart.getDatasetMeta(this.index);
  3206. },
  3207. getScaleForId: function(scaleID) {
  3208. return this.chart.scales[scaleID];
  3209. },
  3210. /**
  3211. * @private
  3212. */
  3213. _getValueScaleId: function() {
  3214. return this.getMeta().yAxisID;
  3215. },
  3216. /**
  3217. * @private
  3218. */
  3219. _getIndexScaleId: function() {
  3220. return this.getMeta().xAxisID;
  3221. },
  3222. /**
  3223. * @private
  3224. */
  3225. _getValueScale: function() {
  3226. return this.getScaleForId(this._getValueScaleId());
  3227. },
  3228. /**
  3229. * @private
  3230. */
  3231. _getIndexScale: function() {
  3232. return this.getScaleForId(this._getIndexScaleId());
  3233. },
  3234. reset: function() {
  3235. this._update(true);
  3236. },
  3237. /**
  3238. * @private
  3239. */
  3240. destroy: function() {
  3241. if (this._data) {
  3242. unlistenArrayEvents(this._data, this);
  3243. }
  3244. },
  3245. createMetaDataset: function() {
  3246. var me = this;
  3247. var type = me.datasetElementType;
  3248. return type && new type({
  3249. _chart: me.chart,
  3250. _datasetIndex: me.index
  3251. });
  3252. },
  3253. createMetaData: function(index) {
  3254. var me = this;
  3255. var type = me.dataElementType;
  3256. return type && new type({
  3257. _chart: me.chart,
  3258. _datasetIndex: me.index,
  3259. _index: index
  3260. });
  3261. },
  3262. addElements: function() {
  3263. var me = this;
  3264. var meta = me.getMeta();
  3265. var data = me.getDataset().data || [];
  3266. var metaData = meta.data;
  3267. var i, ilen;
  3268. for (i = 0, ilen = data.length; i < ilen; ++i) {
  3269. metaData[i] = metaData[i] || me.createMetaData(i);
  3270. }
  3271. meta.dataset = meta.dataset || me.createMetaDataset();
  3272. },
  3273. addElementAndReset: function(index) {
  3274. var element = this.createMetaData(index);
  3275. this.getMeta().data.splice(index, 0, element);
  3276. this.updateElement(element, index, true);
  3277. },
  3278. buildOrUpdateElements: function() {
  3279. var me = this;
  3280. var dataset = me.getDataset();
  3281. var data = dataset.data || (dataset.data = []);
  3282. // In order to correctly handle data addition/deletion animation (an thus simulate
  3283. // real-time charts), we need to monitor these data modifications and synchronize
  3284. // the internal meta data accordingly.
  3285. if (me._data !== data) {
  3286. if (me._data) {
  3287. // This case happens when the user replaced the data array instance.
  3288. unlistenArrayEvents(me._data, me);
  3289. }
  3290. if (data && Object.isExtensible(data)) {
  3291. listenArrayEvents(data, me);
  3292. }
  3293. me._data = data;
  3294. }
  3295. // Re-sync meta data in case the user replaced the data array or if we missed
  3296. // any updates and so make sure that we handle number of datapoints changing.
  3297. me.resyncElements();
  3298. },
  3299. /**
  3300. * Returns the merged user-supplied and default dataset-level options
  3301. * @private
  3302. */
  3303. _configure: function() {
  3304. var me = this;
  3305. me._config = helpers$1.merge(Object.create(null), [
  3306. me.chart.options.datasets[me._type],
  3307. me.getDataset(),
  3308. ], {
  3309. merger: function(key, target, source) {
  3310. if (key !== '_meta' && key !== 'data') {
  3311. helpers$1._merger(key, target, source);
  3312. }
  3313. }
  3314. });
  3315. },
  3316. _update: function(reset) {
  3317. var me = this;
  3318. me._configure();
  3319. me._cachedDataOpts = null;
  3320. me.update(reset);
  3321. },
  3322. update: helpers$1.noop,
  3323. transition: function(easingValue) {
  3324. var meta = this.getMeta();
  3325. var elements = meta.data || [];
  3326. var ilen = elements.length;
  3327. var i = 0;
  3328. for (; i < ilen; ++i) {
  3329. elements[i].transition(easingValue);
  3330. }
  3331. if (meta.dataset) {
  3332. meta.dataset.transition(easingValue);
  3333. }
  3334. },
  3335. draw: function() {
  3336. var meta = this.getMeta();
  3337. var elements = meta.data || [];
  3338. var ilen = elements.length;
  3339. var i = 0;
  3340. if (meta.dataset) {
  3341. meta.dataset.draw();
  3342. }
  3343. for (; i < ilen; ++i) {
  3344. elements[i].draw();
  3345. }
  3346. },
  3347. /**
  3348. * Returns a set of predefined style properties that should be used to represent the dataset
  3349. * or the data if the index is specified
  3350. * @param {number} index - data index
  3351. * @return {IStyleInterface} style object
  3352. */
  3353. getStyle: function(index) {
  3354. var me = this;
  3355. var meta = me.getMeta();
  3356. var dataset = meta.dataset;
  3357. var style;
  3358. me._configure();
  3359. if (dataset && index === undefined) {
  3360. style = me._resolveDatasetElementOptions(dataset || {});
  3361. } else {
  3362. index = index || 0;
  3363. style = me._resolveDataElementOptions(meta.data[index] || {}, index);
  3364. }
  3365. if (style.fill === false || style.fill === null) {
  3366. style.backgroundColor = style.borderColor;
  3367. }
  3368. return style;
  3369. },
  3370. /**
  3371. * @private
  3372. */
  3373. _resolveDatasetElementOptions: function(element, hover) {
  3374. var me = this;
  3375. var chart = me.chart;
  3376. var datasetOpts = me._config;
  3377. var custom = element.custom || {};
  3378. var options = chart.options.elements[me.datasetElementType.prototype._type] || {};
  3379. var elementOptions = me._datasetElementOptions;
  3380. var values = {};
  3381. var i, ilen, key, readKey;
  3382. // Scriptable options
  3383. var context = {
  3384. chart: chart,
  3385. dataset: me.getDataset(),
  3386. datasetIndex: me.index,
  3387. hover: hover
  3388. };
  3389. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3390. key = elementOptions[i];
  3391. readKey = hover ? 'hover' + key.charAt(0).toUpperCase() + key.slice(1) : key;
  3392. values[key] = resolve([
  3393. custom[readKey],
  3394. datasetOpts[readKey],
  3395. options[readKey]
  3396. ], context);
  3397. }
  3398. return values;
  3399. },
  3400. /**
  3401. * @private
  3402. */
  3403. _resolveDataElementOptions: function(element, index) {
  3404. var me = this;
  3405. var custom = element && element.custom;
  3406. var cached = me._cachedDataOpts;
  3407. if (cached && !custom) {
  3408. return cached;
  3409. }
  3410. var chart = me.chart;
  3411. var datasetOpts = me._config;
  3412. var options = chart.options.elements[me.dataElementType.prototype._type] || {};
  3413. var elementOptions = me._dataElementOptions;
  3414. var values = {};
  3415. // Scriptable options
  3416. var context = {
  3417. chart: chart,
  3418. dataIndex: index,
  3419. dataset: me.getDataset(),
  3420. datasetIndex: me.index
  3421. };
  3422. // `resolve` sets cacheable to `false` if any option is indexed or scripted
  3423. var info = {cacheable: !custom};
  3424. var keys, i, ilen, key;
  3425. custom = custom || {};
  3426. if (helpers$1.isArray(elementOptions)) {
  3427. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3428. key = elementOptions[i];
  3429. values[key] = resolve([
  3430. custom[key],
  3431. datasetOpts[key],
  3432. options[key]
  3433. ], context, index, info);
  3434. }
  3435. } else {
  3436. keys = Object.keys(elementOptions);
  3437. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3438. key = keys[i];
  3439. values[key] = resolve([
  3440. custom[key],
  3441. datasetOpts[elementOptions[key]],
  3442. datasetOpts[key],
  3443. options[key]
  3444. ], context, index, info);
  3445. }
  3446. }
  3447. if (info.cacheable) {
  3448. me._cachedDataOpts = Object.freeze(values);
  3449. }
  3450. return values;
  3451. },
  3452. removeHoverStyle: function(element) {
  3453. helpers$1.merge(element._model, element.$previousStyle || {});
  3454. delete element.$previousStyle;
  3455. },
  3456. setHoverStyle: function(element) {
  3457. var dataset = this.chart.data.datasets[element._datasetIndex];
  3458. var index = element._index;
  3459. var custom = element.custom || {};
  3460. var model = element._model;
  3461. var getHoverColor = helpers$1.getHoverColor;
  3462. element.$previousStyle = {
  3463. backgroundColor: model.backgroundColor,
  3464. borderColor: model.borderColor,
  3465. borderWidth: model.borderWidth
  3466. };
  3467. model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
  3468. model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
  3469. model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
  3470. },
  3471. /**
  3472. * @private
  3473. */
  3474. _removeDatasetHoverStyle: function() {
  3475. var element = this.getMeta().dataset;
  3476. if (element) {
  3477. this.removeHoverStyle(element);
  3478. }
  3479. },
  3480. /**
  3481. * @private
  3482. */
  3483. _setDatasetHoverStyle: function() {
  3484. var element = this.getMeta().dataset;
  3485. var prev = {};
  3486. var i, ilen, key, keys, hoverOptions, model;
  3487. if (!element) {
  3488. return;
  3489. }
  3490. model = element._model;
  3491. hoverOptions = this._resolveDatasetElementOptions(element, true);
  3492. keys = Object.keys(hoverOptions);
  3493. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3494. key = keys[i];
  3495. prev[key] = model[key];
  3496. model[key] = hoverOptions[key];
  3497. }
  3498. element.$previousStyle = prev;
  3499. },
  3500. /**
  3501. * @private
  3502. */
  3503. resyncElements: function() {
  3504. var me = this;
  3505. var meta = me.getMeta();
  3506. var data = me.getDataset().data;
  3507. var numMeta = meta.data.length;
  3508. var numData = data.length;
  3509. if (numData < numMeta) {
  3510. meta.data.splice(numData, numMeta - numData);
  3511. } else if (numData > numMeta) {
  3512. me.insertElements(numMeta, numData - numMeta);
  3513. }
  3514. },
  3515. /**
  3516. * @private
  3517. */
  3518. insertElements: function(start, count) {
  3519. for (var i = 0; i < count; ++i) {
  3520. this.addElementAndReset(start + i);
  3521. }
  3522. },
  3523. /**
  3524. * @private
  3525. */
  3526. onDataPush: function() {
  3527. var count = arguments.length;
  3528. this.insertElements(this.getDataset().data.length - count, count);
  3529. },
  3530. /**
  3531. * @private
  3532. */
  3533. onDataPop: function() {
  3534. this.getMeta().data.pop();
  3535. },
  3536. /**
  3537. * @private
  3538. */
  3539. onDataShift: function() {
  3540. this.getMeta().data.shift();
  3541. },
  3542. /**
  3543. * @private
  3544. */
  3545. onDataSplice: function(start, count) {
  3546. this.getMeta().data.splice(start, count);
  3547. this.insertElements(start, arguments.length - 2);
  3548. },
  3549. /**
  3550. * @private
  3551. */
  3552. onDataUnshift: function() {
  3553. this.insertElements(0, arguments.length);
  3554. }
  3555. });
  3556. DatasetController.extend = helpers$1.inherits;
  3557. var core_datasetController = DatasetController;
  3558. var TAU = Math.PI * 2;
  3559. core_defaults._set('global', {
  3560. elements: {
  3561. arc: {
  3562. backgroundColor: core_defaults.global.defaultColor,
  3563. borderColor: '#fff',
  3564. borderWidth: 2,
  3565. borderAlign: 'center'
  3566. }
  3567. }
  3568. });
  3569. function clipArc(ctx, arc) {
  3570. var startAngle = arc.startAngle;
  3571. var endAngle = arc.endAngle;
  3572. var pixelMargin = arc.pixelMargin;
  3573. var angleMargin = pixelMargin / arc.outerRadius;
  3574. var x = arc.x;
  3575. var y = arc.y;
  3576. // Draw an inner border by cliping the arc and drawing a double-width border
  3577. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  3578. ctx.beginPath();
  3579. ctx.arc(x, y, arc.outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  3580. if (arc.innerRadius > pixelMargin) {
  3581. angleMargin = pixelMargin / arc.innerRadius;
  3582. ctx.arc(x, y, arc.innerRadius - pixelMargin, endAngle + angleMargin, startAngle - angleMargin, true);
  3583. } else {
  3584. ctx.arc(x, y, pixelMargin, endAngle + Math.PI / 2, startAngle - Math.PI / 2);
  3585. }
  3586. ctx.closePath();
  3587. ctx.clip();
  3588. }
  3589. function drawFullCircleBorders(ctx, vm, arc, inner) {
  3590. var endAngle = arc.endAngle;
  3591. var i;
  3592. if (inner) {
  3593. arc.endAngle = arc.startAngle + TAU;
  3594. clipArc(ctx, arc);
  3595. arc.endAngle = endAngle;
  3596. if (arc.endAngle === arc.startAngle && arc.fullCircles) {
  3597. arc.endAngle += TAU;
  3598. arc.fullCircles--;
  3599. }
  3600. }
  3601. ctx.beginPath();
  3602. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.startAngle + TAU, arc.startAngle, true);
  3603. for (i = 0; i < arc.fullCircles; ++i) {
  3604. ctx.stroke();
  3605. }
  3606. ctx.beginPath();
  3607. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.startAngle + TAU);
  3608. for (i = 0; i < arc.fullCircles; ++i) {
  3609. ctx.stroke();
  3610. }
  3611. }
  3612. function drawBorder(ctx, vm, arc) {
  3613. var inner = vm.borderAlign === 'inner';
  3614. if (inner) {
  3615. ctx.lineWidth = vm.borderWidth * 2;
  3616. ctx.lineJoin = 'round';
  3617. } else {
  3618. ctx.lineWidth = vm.borderWidth;
  3619. ctx.lineJoin = 'bevel';
  3620. }
  3621. if (arc.fullCircles) {
  3622. drawFullCircleBorders(ctx, vm, arc, inner);
  3623. }
  3624. if (inner) {
  3625. clipArc(ctx, arc);
  3626. }
  3627. ctx.beginPath();
  3628. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.endAngle);
  3629. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3630. ctx.closePath();
  3631. ctx.stroke();
  3632. }
  3633. var element_arc = core_element.extend({
  3634. _type: 'arc',
  3635. inLabelRange: function(mouseX) {
  3636. var vm = this._view;
  3637. if (vm) {
  3638. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  3639. }
  3640. return false;
  3641. },
  3642. inRange: function(chartX, chartY) {
  3643. var vm = this._view;
  3644. if (vm) {
  3645. var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
  3646. var angle = pointRelativePosition.angle;
  3647. var distance = pointRelativePosition.distance;
  3648. // Sanitise angle range
  3649. var startAngle = vm.startAngle;
  3650. var endAngle = vm.endAngle;
  3651. while (endAngle < startAngle) {
  3652. endAngle += TAU;
  3653. }
  3654. while (angle > endAngle) {
  3655. angle -= TAU;
  3656. }
  3657. while (angle < startAngle) {
  3658. angle += TAU;
  3659. }
  3660. // Check if within the range of the open/close angle
  3661. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  3662. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  3663. return (betweenAngles && withinRadius);
  3664. }
  3665. return false;
  3666. },
  3667. getCenterPoint: function() {
  3668. var vm = this._view;
  3669. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  3670. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  3671. return {
  3672. x: vm.x + Math.cos(halfAngle) * halfRadius,
  3673. y: vm.y + Math.sin(halfAngle) * halfRadius
  3674. };
  3675. },
  3676. getArea: function() {
  3677. var vm = this._view;
  3678. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  3679. },
  3680. tooltipPosition: function() {
  3681. var vm = this._view;
  3682. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  3683. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  3684. return {
  3685. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  3686. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  3687. };
  3688. },
  3689. draw: function() {
  3690. var ctx = this._chart.ctx;
  3691. var vm = this._view;
  3692. var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
  3693. var arc = {
  3694. x: vm.x,
  3695. y: vm.y,
  3696. innerRadius: vm.innerRadius,
  3697. outerRadius: Math.max(vm.outerRadius - pixelMargin, 0),
  3698. pixelMargin: pixelMargin,
  3699. startAngle: vm.startAngle,
  3700. endAngle: vm.endAngle,
  3701. fullCircles: Math.floor(vm.circumference / TAU)
  3702. };
  3703. var i;
  3704. ctx.save();
  3705. ctx.fillStyle = vm.backgroundColor;
  3706. ctx.strokeStyle = vm.borderColor;
  3707. if (arc.fullCircles) {
  3708. arc.endAngle = arc.startAngle + TAU;
  3709. ctx.beginPath();
  3710. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3711. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3712. ctx.closePath();
  3713. for (i = 0; i < arc.fullCircles; ++i) {
  3714. ctx.fill();
  3715. }
  3716. arc.endAngle = arc.startAngle + vm.circumference % TAU;
  3717. }
  3718. ctx.beginPath();
  3719. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3720. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3721. ctx.closePath();
  3722. ctx.fill();
  3723. if (vm.borderWidth) {
  3724. drawBorder(ctx, vm, arc);
  3725. }
  3726. ctx.restore();
  3727. }
  3728. });
  3729. var valueOrDefault$1 = helpers$1.valueOrDefault;
  3730. var defaultColor = core_defaults.global.defaultColor;
  3731. core_defaults._set('global', {
  3732. elements: {
  3733. line: {
  3734. tension: 0.4,
  3735. backgroundColor: defaultColor,
  3736. borderWidth: 3,
  3737. borderColor: defaultColor,
  3738. borderCapStyle: 'butt',
  3739. borderDash: [],
  3740. borderDashOffset: 0.0,
  3741. borderJoinStyle: 'miter',
  3742. capBezierPoints: true,
  3743. fill: true, // do we fill in the area between the line and its base axis
  3744. }
  3745. }
  3746. });
  3747. var element_line = core_element.extend({
  3748. _type: 'line',
  3749. draw: function() {
  3750. var me = this;
  3751. var vm = me._view;
  3752. var ctx = me._chart.ctx;
  3753. var spanGaps = vm.spanGaps;
  3754. var points = me._children.slice(); // clone array
  3755. var globalDefaults = core_defaults.global;
  3756. var globalOptionLineElements = globalDefaults.elements.line;
  3757. var lastDrawnIndex = -1;
  3758. var closePath = me._loop;
  3759. var index, previous, currentVM;
  3760. if (!points.length) {
  3761. return;
  3762. }
  3763. if (me._loop) {
  3764. for (index = 0; index < points.length; ++index) {
  3765. previous = helpers$1.previousItem(points, index);
  3766. // If the line has an open path, shift the point array
  3767. if (!points[index]._view.skip && previous._view.skip) {
  3768. points = points.slice(index).concat(points.slice(0, index));
  3769. closePath = spanGaps;
  3770. break;
  3771. }
  3772. }
  3773. // If the line has a close path, add the first point again
  3774. if (closePath) {
  3775. points.push(points[0]);
  3776. }
  3777. }
  3778. ctx.save();
  3779. // Stroke Line Options
  3780. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  3781. // IE 9 and 10 do not support line dash
  3782. if (ctx.setLineDash) {
  3783. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  3784. }
  3785. ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
  3786. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  3787. ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
  3788. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  3789. // Stroke Line
  3790. ctx.beginPath();
  3791. // First point moves to it's starting position no matter what
  3792. currentVM = points[0]._view;
  3793. if (!currentVM.skip) {
  3794. ctx.moveTo(currentVM.x, currentVM.y);
  3795. lastDrawnIndex = 0;
  3796. }
  3797. for (index = 1; index < points.length; ++index) {
  3798. currentVM = points[index]._view;
  3799. previous = lastDrawnIndex === -1 ? helpers$1.previousItem(points, index) : points[lastDrawnIndex];
  3800. if (!currentVM.skip) {
  3801. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  3802. // There was a gap and this is the first point after the gap
  3803. ctx.moveTo(currentVM.x, currentVM.y);
  3804. } else {
  3805. // Line to next point
  3806. helpers$1.canvas.lineTo(ctx, previous._view, currentVM);
  3807. }
  3808. lastDrawnIndex = index;
  3809. }
  3810. }
  3811. if (closePath) {
  3812. ctx.closePath();
  3813. }
  3814. ctx.stroke();
  3815. ctx.restore();
  3816. }
  3817. });
  3818. var valueOrDefault$2 = helpers$1.valueOrDefault;
  3819. var defaultColor$1 = core_defaults.global.defaultColor;
  3820. core_defaults._set('global', {
  3821. elements: {
  3822. point: {
  3823. radius: 3,
  3824. pointStyle: 'circle',
  3825. backgroundColor: defaultColor$1,
  3826. borderColor: defaultColor$1,
  3827. borderWidth: 1,
  3828. // Hover
  3829. hitRadius: 1,
  3830. hoverRadius: 4,
  3831. hoverBorderWidth: 1
  3832. }
  3833. }
  3834. });
  3835. function xRange(mouseX) {
  3836. var vm = this._view;
  3837. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  3838. }
  3839. function yRange(mouseY) {
  3840. var vm = this._view;
  3841. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  3842. }
  3843. var element_point = core_element.extend({
  3844. _type: 'point',
  3845. inRange: function(mouseX, mouseY) {
  3846. var vm = this._view;
  3847. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  3848. },
  3849. inLabelRange: xRange,
  3850. inXRange: xRange,
  3851. inYRange: yRange,
  3852. getCenterPoint: function() {
  3853. var vm = this._view;
  3854. return {
  3855. x: vm.x,
  3856. y: vm.y
  3857. };
  3858. },
  3859. getArea: function() {
  3860. return Math.PI * Math.pow(this._view.radius, 2);
  3861. },
  3862. tooltipPosition: function() {
  3863. var vm = this._view;
  3864. return {
  3865. x: vm.x,
  3866. y: vm.y,
  3867. padding: vm.radius + vm.borderWidth
  3868. };
  3869. },
  3870. draw: function(chartArea) {
  3871. var vm = this._view;
  3872. var ctx = this._chart.ctx;
  3873. var pointStyle = vm.pointStyle;
  3874. var rotation = vm.rotation;
  3875. var radius = vm.radius;
  3876. var x = vm.x;
  3877. var y = vm.y;
  3878. var globalDefaults = core_defaults.global;
  3879. var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
  3880. if (vm.skip) {
  3881. return;
  3882. }
  3883. // Clipping for Points.
  3884. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
  3885. ctx.strokeStyle = vm.borderColor || defaultColor;
  3886. ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
  3887. ctx.fillStyle = vm.backgroundColor || defaultColor;
  3888. helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  3889. }
  3890. }
  3891. });
  3892. var defaultColor$2 = core_defaults.global.defaultColor;
  3893. core_defaults._set('global', {
  3894. elements: {
  3895. rectangle: {
  3896. backgroundColor: defaultColor$2,
  3897. borderColor: defaultColor$2,
  3898. borderSkipped: 'bottom',
  3899. borderWidth: 0
  3900. }
  3901. }
  3902. });
  3903. function isVertical(vm) {
  3904. return vm && vm.width !== undefined;
  3905. }
  3906. /**
  3907. * Helper function to get the bounds of the bar regardless of the orientation
  3908. * @param bar {Chart.Element.Rectangle} the bar
  3909. * @return {Bounds} bounds of the bar
  3910. * @private
  3911. */
  3912. function getBarBounds(vm) {
  3913. var x1, x2, y1, y2, half;
  3914. if (isVertical(vm)) {
  3915. half = vm.width / 2;
  3916. x1 = vm.x - half;
  3917. x2 = vm.x + half;
  3918. y1 = Math.min(vm.y, vm.base);
  3919. y2 = Math.max(vm.y, vm.base);
  3920. } else {
  3921. half = vm.height / 2;
  3922. x1 = Math.min(vm.x, vm.base);
  3923. x2 = Math.max(vm.x, vm.base);
  3924. y1 = vm.y - half;
  3925. y2 = vm.y + half;
  3926. }
  3927. return {
  3928. left: x1,
  3929. top: y1,
  3930. right: x2,
  3931. bottom: y2
  3932. };
  3933. }
  3934. function swap(orig, v1, v2) {
  3935. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  3936. }
  3937. function parseBorderSkipped(vm) {
  3938. var edge = vm.borderSkipped;
  3939. var res = {};
  3940. if (!edge) {
  3941. return res;
  3942. }
  3943. if (vm.horizontal) {
  3944. if (vm.base > vm.x) {
  3945. edge = swap(edge, 'left', 'right');
  3946. }
  3947. } else if (vm.base < vm.y) {
  3948. edge = swap(edge, 'bottom', 'top');
  3949. }
  3950. res[edge] = true;
  3951. return res;
  3952. }
  3953. function parseBorderWidth(vm, maxW, maxH) {
  3954. var value = vm.borderWidth;
  3955. var skip = parseBorderSkipped(vm);
  3956. var t, r, b, l;
  3957. if (helpers$1.isObject(value)) {
  3958. t = +value.top || 0;
  3959. r = +value.right || 0;
  3960. b = +value.bottom || 0;
  3961. l = +value.left || 0;
  3962. } else {
  3963. t = r = b = l = +value || 0;
  3964. }
  3965. return {
  3966. t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
  3967. r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
  3968. b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
  3969. l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
  3970. };
  3971. }
  3972. function boundingRects(vm) {
  3973. var bounds = getBarBounds(vm);
  3974. var width = bounds.right - bounds.left;
  3975. var height = bounds.bottom - bounds.top;
  3976. var border = parseBorderWidth(vm, width / 2, height / 2);
  3977. return {
  3978. outer: {
  3979. x: bounds.left,
  3980. y: bounds.top,
  3981. w: width,
  3982. h: height
  3983. },
  3984. inner: {
  3985. x: bounds.left + border.l,
  3986. y: bounds.top + border.t,
  3987. w: width - border.l - border.r,
  3988. h: height - border.t - border.b
  3989. }
  3990. };
  3991. }
  3992. function inRange(vm, x, y) {
  3993. var skipX = x === null;
  3994. var skipY = y === null;
  3995. var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
  3996. return bounds
  3997. && (skipX || x >= bounds.left && x <= bounds.right)
  3998. && (skipY || y >= bounds.top && y <= bounds.bottom);
  3999. }
  4000. var element_rectangle = core_element.extend({
  4001. _type: 'rectangle',
  4002. draw: function() {
  4003. var ctx = this._chart.ctx;
  4004. var vm = this._view;
  4005. var rects = boundingRects(vm);
  4006. var outer = rects.outer;
  4007. var inner = rects.inner;
  4008. ctx.fillStyle = vm.backgroundColor;
  4009. ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
  4010. if (outer.w === inner.w && outer.h === inner.h) {
  4011. return;
  4012. }
  4013. ctx.save();
  4014. ctx.beginPath();
  4015. ctx.rect(outer.x, outer.y, outer.w, outer.h);
  4016. ctx.clip();
  4017. ctx.fillStyle = vm.borderColor;
  4018. ctx.rect(inner.x, inner.y, inner.w, inner.h);
  4019. ctx.fill('evenodd');
  4020. ctx.restore();
  4021. },
  4022. height: function() {
  4023. var vm = this._view;
  4024. return vm.base - vm.y;
  4025. },
  4026. inRange: function(mouseX, mouseY) {
  4027. return inRange(this._view, mouseX, mouseY);
  4028. },
  4029. inLabelRange: function(mouseX, mouseY) {
  4030. var vm = this._view;
  4031. return isVertical(vm)
  4032. ? inRange(vm, mouseX, null)
  4033. : inRange(vm, null, mouseY);
  4034. },
  4035. inXRange: function(mouseX) {
  4036. return inRange(this._view, mouseX, null);
  4037. },
  4038. inYRange: function(mouseY) {
  4039. return inRange(this._view, null, mouseY);
  4040. },
  4041. getCenterPoint: function() {
  4042. var vm = this._view;
  4043. var x, y;
  4044. if (isVertical(vm)) {
  4045. x = vm.x;
  4046. y = (vm.y + vm.base) / 2;
  4047. } else {
  4048. x = (vm.x + vm.base) / 2;
  4049. y = vm.y;
  4050. }
  4051. return {x: x, y: y};
  4052. },
  4053. getArea: function() {
  4054. var vm = this._view;
  4055. return isVertical(vm)
  4056. ? vm.width * Math.abs(vm.y - vm.base)
  4057. : vm.height * Math.abs(vm.x - vm.base);
  4058. },
  4059. tooltipPosition: function() {
  4060. var vm = this._view;
  4061. return {
  4062. x: vm.x,
  4063. y: vm.y
  4064. };
  4065. }
  4066. });
  4067. var elements = {};
  4068. var Arc = element_arc;
  4069. var Line = element_line;
  4070. var Point = element_point;
  4071. var Rectangle = element_rectangle;
  4072. elements.Arc = Arc;
  4073. elements.Line = Line;
  4074. elements.Point = Point;
  4075. elements.Rectangle = Rectangle;
  4076. var deprecated = helpers$1._deprecated;
  4077. var valueOrDefault$3 = helpers$1.valueOrDefault;
  4078. core_defaults._set('bar', {
  4079. hover: {
  4080. mode: 'label'
  4081. },
  4082. scales: {
  4083. xAxes: [{
  4084. type: 'category',
  4085. offset: true,
  4086. gridLines: {
  4087. offsetGridLines: true
  4088. }
  4089. }],
  4090. yAxes: [{
  4091. type: 'linear'
  4092. }]
  4093. }
  4094. });
  4095. core_defaults._set('global', {
  4096. datasets: {
  4097. bar: {
  4098. categoryPercentage: 0.8,
  4099. barPercentage: 0.9
  4100. }
  4101. }
  4102. });
  4103. /**
  4104. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  4105. * @private
  4106. */
  4107. function computeMinSampleSize(scale, pixels) {
  4108. var min = scale._length;
  4109. var prev, curr, i, ilen;
  4110. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  4111. min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
  4112. }
  4113. for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) {
  4114. curr = scale.getPixelForTick(i);
  4115. min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;
  4116. prev = curr;
  4117. }
  4118. return min;
  4119. }
  4120. /**
  4121. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  4122. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  4123. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  4124. * @private
  4125. */
  4126. function computeFitCategoryTraits(index, ruler, options) {
  4127. var thickness = options.barThickness;
  4128. var count = ruler.stackCount;
  4129. var curr = ruler.pixels[index];
  4130. var min = helpers$1.isNullOrUndef(thickness)
  4131. ? computeMinSampleSize(ruler.scale, ruler.pixels)
  4132. : -1;
  4133. var size, ratio;
  4134. if (helpers$1.isNullOrUndef(thickness)) {
  4135. size = min * options.categoryPercentage;
  4136. ratio = options.barPercentage;
  4137. } else {
  4138. // When bar thickness is enforced, category and bar percentages are ignored.
  4139. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  4140. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  4141. size = thickness * count;
  4142. ratio = 1;
  4143. }
  4144. return {
  4145. chunk: size / count,
  4146. ratio: ratio,
  4147. start: curr - (size / 2)
  4148. };
  4149. }
  4150. /**
  4151. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  4152. * percentage options are 1), based on the previous and following categories. This mode
  4153. * generates bars with different widths when data are not evenly spaced.
  4154. * @private
  4155. */
  4156. function computeFlexCategoryTraits(index, ruler, options) {
  4157. var pixels = ruler.pixels;
  4158. var curr = pixels[index];
  4159. var prev = index > 0 ? pixels[index - 1] : null;
  4160. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  4161. var percent = options.categoryPercentage;
  4162. var start, size;
  4163. if (prev === null) {
  4164. // first data: its size is double based on the next point or,
  4165. // if it's also the last data, we use the scale size.
  4166. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  4167. }
  4168. if (next === null) {
  4169. // last data: its size is also double based on the previous point.
  4170. next = curr + curr - prev;
  4171. }
  4172. start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  4173. size = Math.abs(next - prev) / 2 * percent;
  4174. return {
  4175. chunk: size / ruler.stackCount,
  4176. ratio: options.barPercentage,
  4177. start: start
  4178. };
  4179. }
  4180. var controller_bar = core_datasetController.extend({
  4181. dataElementType: elements.Rectangle,
  4182. /**
  4183. * @private
  4184. */
  4185. _dataElementOptions: [
  4186. 'backgroundColor',
  4187. 'borderColor',
  4188. 'borderSkipped',
  4189. 'borderWidth',
  4190. 'barPercentage',
  4191. 'barThickness',
  4192. 'categoryPercentage',
  4193. 'maxBarThickness',
  4194. 'minBarLength'
  4195. ],
  4196. initialize: function() {
  4197. var me = this;
  4198. var meta, scaleOpts;
  4199. core_datasetController.prototype.initialize.apply(me, arguments);
  4200. meta = me.getMeta();
  4201. meta.stack = me.getDataset().stack;
  4202. meta.bar = true;
  4203. scaleOpts = me._getIndexScale().options;
  4204. deprecated('bar chart', scaleOpts.barPercentage, 'scales.[x/y]Axes.barPercentage', 'dataset.barPercentage');
  4205. deprecated('bar chart', scaleOpts.barThickness, 'scales.[x/y]Axes.barThickness', 'dataset.barThickness');
  4206. deprecated('bar chart', scaleOpts.categoryPercentage, 'scales.[x/y]Axes.categoryPercentage', 'dataset.categoryPercentage');
  4207. deprecated('bar chart', me._getValueScale().options.minBarLength, 'scales.[x/y]Axes.minBarLength', 'dataset.minBarLength');
  4208. deprecated('bar chart', scaleOpts.maxBarThickness, 'scales.[x/y]Axes.maxBarThickness', 'dataset.maxBarThickness');
  4209. },
  4210. update: function(reset) {
  4211. var me = this;
  4212. var rects = me.getMeta().data;
  4213. var i, ilen;
  4214. me._ruler = me.getRuler();
  4215. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  4216. me.updateElement(rects[i], i, reset);
  4217. }
  4218. },
  4219. updateElement: function(rectangle, index, reset) {
  4220. var me = this;
  4221. var meta = me.getMeta();
  4222. var dataset = me.getDataset();
  4223. var options = me._resolveDataElementOptions(rectangle, index);
  4224. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  4225. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  4226. rectangle._datasetIndex = me.index;
  4227. rectangle._index = index;
  4228. rectangle._model = {
  4229. backgroundColor: options.backgroundColor,
  4230. borderColor: options.borderColor,
  4231. borderSkipped: options.borderSkipped,
  4232. borderWidth: options.borderWidth,
  4233. datasetLabel: dataset.label,
  4234. label: me.chart.data.labels[index]
  4235. };
  4236. if (helpers$1.isArray(dataset.data[index])) {
  4237. rectangle._model.borderSkipped = null;
  4238. }
  4239. me._updateElementGeometry(rectangle, index, reset, options);
  4240. rectangle.pivot();
  4241. },
  4242. /**
  4243. * @private
  4244. */
  4245. _updateElementGeometry: function(rectangle, index, reset, options) {
  4246. var me = this;
  4247. var model = rectangle._model;
  4248. var vscale = me._getValueScale();
  4249. var base = vscale.getBasePixel();
  4250. var horizontal = vscale.isHorizontal();
  4251. var ruler = me._ruler || me.getRuler();
  4252. var vpixels = me.calculateBarValuePixels(me.index, index, options);
  4253. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler, options);
  4254. model.horizontal = horizontal;
  4255. model.base = reset ? base : vpixels.base;
  4256. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  4257. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  4258. model.height = horizontal ? ipixels.size : undefined;
  4259. model.width = horizontal ? undefined : ipixels.size;
  4260. },
  4261. /**
  4262. * Returns the stacks based on groups and bar visibility.
  4263. * @param {number} [last] - The dataset index
  4264. * @returns {string[]} The list of stack IDs
  4265. * @private
  4266. */
  4267. _getStacks: function(last) {
  4268. var me = this;
  4269. var scale = me._getIndexScale();
  4270. var metasets = scale._getMatchingVisibleMetas(me._type);
  4271. var stacked = scale.options.stacked;
  4272. var ilen = metasets.length;
  4273. var stacks = [];
  4274. var i, meta;
  4275. for (i = 0; i < ilen; ++i) {
  4276. meta = metasets[i];
  4277. // stacked | meta.stack
  4278. // | found | not found | undefined
  4279. // false | x | x | x
  4280. // true | | x |
  4281. // undefined | | x | x
  4282. if (stacked === false || stacks.indexOf(meta.stack) === -1 ||
  4283. (stacked === undefined && meta.stack === undefined)) {
  4284. stacks.push(meta.stack);
  4285. }
  4286. if (meta.index === last) {
  4287. break;
  4288. }
  4289. }
  4290. return stacks;
  4291. },
  4292. /**
  4293. * Returns the effective number of stacks based on groups and bar visibility.
  4294. * @private
  4295. */
  4296. getStackCount: function() {
  4297. return this._getStacks().length;
  4298. },
  4299. /**
  4300. * Returns the stack index for the given dataset based on groups and bar visibility.
  4301. * @param {number} [datasetIndex] - The dataset index
  4302. * @param {string} [name] - The stack name to find
  4303. * @returns {number} The stack index
  4304. * @private
  4305. */
  4306. getStackIndex: function(datasetIndex, name) {
  4307. var stacks = this._getStacks(datasetIndex);
  4308. var index = (name !== undefined)
  4309. ? stacks.indexOf(name)
  4310. : -1; // indexOf returns -1 if element is not present
  4311. return (index === -1)
  4312. ? stacks.length - 1
  4313. : index;
  4314. },
  4315. /**
  4316. * @private
  4317. */
  4318. getRuler: function() {
  4319. var me = this;
  4320. var scale = me._getIndexScale();
  4321. var pixels = [];
  4322. var i, ilen;
  4323. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  4324. pixels.push(scale.getPixelForValue(null, i, me.index));
  4325. }
  4326. return {
  4327. pixels: pixels,
  4328. start: scale._startPixel,
  4329. end: scale._endPixel,
  4330. stackCount: me.getStackCount(),
  4331. scale: scale
  4332. };
  4333. },
  4334. /**
  4335. * Note: pixel values are not clamped to the scale area.
  4336. * @private
  4337. */
  4338. calculateBarValuePixels: function(datasetIndex, index, options) {
  4339. var me = this;
  4340. var chart = me.chart;
  4341. var scale = me._getValueScale();
  4342. var isHorizontal = scale.isHorizontal();
  4343. var datasets = chart.data.datasets;
  4344. var metasets = scale._getMatchingVisibleMetas(me._type);
  4345. var value = scale._parseValue(datasets[datasetIndex].data[index]);
  4346. var minBarLength = options.minBarLength;
  4347. var stacked = scale.options.stacked;
  4348. var stack = me.getMeta().stack;
  4349. var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;
  4350. var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;
  4351. var ilen = metasets.length;
  4352. var i, imeta, ivalue, base, head, size, stackLength;
  4353. if (stacked || (stacked === undefined && stack !== undefined)) {
  4354. for (i = 0; i < ilen; ++i) {
  4355. imeta = metasets[i];
  4356. if (imeta.index === datasetIndex) {
  4357. break;
  4358. }
  4359. if (imeta.stack === stack) {
  4360. stackLength = scale._parseValue(datasets[imeta.index].data[index]);
  4361. ivalue = stackLength.start === undefined ? stackLength.end : stackLength.min >= 0 && stackLength.max >= 0 ? stackLength.max : stackLength.min;
  4362. if ((value.min < 0 && ivalue < 0) || (value.max >= 0 && ivalue > 0)) {
  4363. start += ivalue;
  4364. }
  4365. }
  4366. }
  4367. }
  4368. base = scale.getPixelForValue(start);
  4369. head = scale.getPixelForValue(start + length);
  4370. size = head - base;
  4371. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  4372. size = minBarLength;
  4373. if (length >= 0 && !isHorizontal || length < 0 && isHorizontal) {
  4374. head = base - minBarLength;
  4375. } else {
  4376. head = base + minBarLength;
  4377. }
  4378. }
  4379. return {
  4380. size: size,
  4381. base: base,
  4382. head: head,
  4383. center: head + size / 2
  4384. };
  4385. },
  4386. /**
  4387. * @private
  4388. */
  4389. calculateBarIndexPixels: function(datasetIndex, index, ruler, options) {
  4390. var me = this;
  4391. var range = options.barThickness === 'flex'
  4392. ? computeFlexCategoryTraits(index, ruler, options)
  4393. : computeFitCategoryTraits(index, ruler, options);
  4394. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  4395. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  4396. var size = Math.min(
  4397. valueOrDefault$3(options.maxBarThickness, Infinity),
  4398. range.chunk * range.ratio);
  4399. return {
  4400. base: center - size / 2,
  4401. head: center + size / 2,
  4402. center: center,
  4403. size: size
  4404. };
  4405. },
  4406. draw: function() {
  4407. var me = this;
  4408. var chart = me.chart;
  4409. var scale = me._getValueScale();
  4410. var rects = me.getMeta().data;
  4411. var dataset = me.getDataset();
  4412. var ilen = rects.length;
  4413. var i = 0;
  4414. helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
  4415. for (; i < ilen; ++i) {
  4416. var val = scale._parseValue(dataset.data[i]);
  4417. if (!isNaN(val.min) && !isNaN(val.max)) {
  4418. rects[i].draw();
  4419. }
  4420. }
  4421. helpers$1.canvas.unclipArea(chart.ctx);
  4422. },
  4423. /**
  4424. * @private
  4425. */
  4426. _resolveDataElementOptions: function() {
  4427. var me = this;
  4428. var values = helpers$1.extend({}, core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments));
  4429. var indexOpts = me._getIndexScale().options;
  4430. var valueOpts = me._getValueScale().options;
  4431. values.barPercentage = valueOrDefault$3(indexOpts.barPercentage, values.barPercentage);
  4432. values.barThickness = valueOrDefault$3(indexOpts.barThickness, values.barThickness);
  4433. values.categoryPercentage = valueOrDefault$3(indexOpts.categoryPercentage, values.categoryPercentage);
  4434. values.maxBarThickness = valueOrDefault$3(indexOpts.maxBarThickness, values.maxBarThickness);
  4435. values.minBarLength = valueOrDefault$3(valueOpts.minBarLength, values.minBarLength);
  4436. return values;
  4437. }
  4438. });
  4439. var valueOrDefault$4 = helpers$1.valueOrDefault;
  4440. var resolve$1 = helpers$1.options.resolve;
  4441. core_defaults._set('bubble', {
  4442. hover: {
  4443. mode: 'single'
  4444. },
  4445. scales: {
  4446. xAxes: [{
  4447. type: 'linear', // bubble should probably use a linear scale by default
  4448. position: 'bottom',
  4449. id: 'x-axis-0' // need an ID so datasets can reference the scale
  4450. }],
  4451. yAxes: [{
  4452. type: 'linear',
  4453. position: 'left',
  4454. id: 'y-axis-0'
  4455. }]
  4456. },
  4457. tooltips: {
  4458. callbacks: {
  4459. title: function() {
  4460. // Title doesn't make sense for scatter since we format the data as a point
  4461. return '';
  4462. },
  4463. label: function(item, data) {
  4464. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  4465. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  4466. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  4467. }
  4468. }
  4469. }
  4470. });
  4471. var controller_bubble = core_datasetController.extend({
  4472. /**
  4473. * @protected
  4474. */
  4475. dataElementType: elements.Point,
  4476. /**
  4477. * @private
  4478. */
  4479. _dataElementOptions: [
  4480. 'backgroundColor',
  4481. 'borderColor',
  4482. 'borderWidth',
  4483. 'hoverBackgroundColor',
  4484. 'hoverBorderColor',
  4485. 'hoverBorderWidth',
  4486. 'hoverRadius',
  4487. 'hitRadius',
  4488. 'pointStyle',
  4489. 'rotation'
  4490. ],
  4491. /**
  4492. * @protected
  4493. */
  4494. update: function(reset) {
  4495. var me = this;
  4496. var meta = me.getMeta();
  4497. var points = meta.data;
  4498. // Update Points
  4499. helpers$1.each(points, function(point, index) {
  4500. me.updateElement(point, index, reset);
  4501. });
  4502. },
  4503. /**
  4504. * @protected
  4505. */
  4506. updateElement: function(point, index, reset) {
  4507. var me = this;
  4508. var meta = me.getMeta();
  4509. var custom = point.custom || {};
  4510. var xScale = me.getScaleForId(meta.xAxisID);
  4511. var yScale = me.getScaleForId(meta.yAxisID);
  4512. var options = me._resolveDataElementOptions(point, index);
  4513. var data = me.getDataset().data[index];
  4514. var dsIndex = me.index;
  4515. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  4516. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  4517. point._xScale = xScale;
  4518. point._yScale = yScale;
  4519. point._options = options;
  4520. point._datasetIndex = dsIndex;
  4521. point._index = index;
  4522. point._model = {
  4523. backgroundColor: options.backgroundColor,
  4524. borderColor: options.borderColor,
  4525. borderWidth: options.borderWidth,
  4526. hitRadius: options.hitRadius,
  4527. pointStyle: options.pointStyle,
  4528. rotation: options.rotation,
  4529. radius: reset ? 0 : options.radius,
  4530. skip: custom.skip || isNaN(x) || isNaN(y),
  4531. x: x,
  4532. y: y,
  4533. };
  4534. point.pivot();
  4535. },
  4536. /**
  4537. * @protected
  4538. */
  4539. setHoverStyle: function(point) {
  4540. var model = point._model;
  4541. var options = point._options;
  4542. var getHoverColor = helpers$1.getHoverColor;
  4543. point.$previousStyle = {
  4544. backgroundColor: model.backgroundColor,
  4545. borderColor: model.borderColor,
  4546. borderWidth: model.borderWidth,
  4547. radius: model.radius
  4548. };
  4549. model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4550. model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
  4551. model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
  4552. model.radius = options.radius + options.hoverRadius;
  4553. },
  4554. /**
  4555. * @private
  4556. */
  4557. _resolveDataElementOptions: function(point, index) {
  4558. var me = this;
  4559. var chart = me.chart;
  4560. var dataset = me.getDataset();
  4561. var custom = point.custom || {};
  4562. var data = dataset.data[index] || {};
  4563. var values = core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments);
  4564. // Scriptable options
  4565. var context = {
  4566. chart: chart,
  4567. dataIndex: index,
  4568. dataset: dataset,
  4569. datasetIndex: me.index
  4570. };
  4571. // In case values were cached (and thus frozen), we need to clone the values
  4572. if (me._cachedDataOpts === values) {
  4573. values = helpers$1.extend({}, values);
  4574. }
  4575. // Custom radius resolution
  4576. values.radius = resolve$1([
  4577. custom.radius,
  4578. data.r,
  4579. me._config.radius,
  4580. chart.options.elements.point.radius
  4581. ], context, index);
  4582. return values;
  4583. }
  4584. });
  4585. var valueOrDefault$5 = helpers$1.valueOrDefault;
  4586. var PI$1 = Math.PI;
  4587. var DOUBLE_PI$1 = PI$1 * 2;
  4588. var HALF_PI$1 = PI$1 / 2;
  4589. core_defaults._set('doughnut', {
  4590. animation: {
  4591. // Boolean - Whether we animate the rotation of the Doughnut
  4592. animateRotate: true,
  4593. // Boolean - Whether we animate scaling the Doughnut from the centre
  4594. animateScale: false
  4595. },
  4596. hover: {
  4597. mode: 'single'
  4598. },
  4599. legendCallback: function(chart) {
  4600. var list = document.createElement('ul');
  4601. var data = chart.data;
  4602. var datasets = data.datasets;
  4603. var labels = data.labels;
  4604. var i, ilen, listItem, listItemSpan;
  4605. list.setAttribute('class', chart.id + '-legend');
  4606. if (datasets.length) {
  4607. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  4608. listItem = list.appendChild(document.createElement('li'));
  4609. listItemSpan = listItem.appendChild(document.createElement('span'));
  4610. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  4611. if (labels[i]) {
  4612. listItem.appendChild(document.createTextNode(labels[i]));
  4613. }
  4614. }
  4615. }
  4616. return list.outerHTML;
  4617. },
  4618. legend: {
  4619. labels: {
  4620. generateLabels: function(chart) {
  4621. var data = chart.data;
  4622. if (data.labels.length && data.datasets.length) {
  4623. return data.labels.map(function(label, i) {
  4624. var meta = chart.getDatasetMeta(0);
  4625. var style = meta.controller.getStyle(i);
  4626. return {
  4627. text: label,
  4628. fillStyle: style.backgroundColor,
  4629. strokeStyle: style.borderColor,
  4630. lineWidth: style.borderWidth,
  4631. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  4632. // Extra data used for toggling the correct item
  4633. index: i
  4634. };
  4635. });
  4636. }
  4637. return [];
  4638. }
  4639. },
  4640. onClick: function(e, legendItem) {
  4641. var index = legendItem.index;
  4642. var chart = this.chart;
  4643. var i, ilen, meta;
  4644. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  4645. meta = chart.getDatasetMeta(i);
  4646. // toggle visibility of index if exists
  4647. if (meta.data[index]) {
  4648. meta.data[index].hidden = !meta.data[index].hidden;
  4649. }
  4650. }
  4651. chart.update();
  4652. }
  4653. },
  4654. // The percentage of the chart that we cut out of the middle.
  4655. cutoutPercentage: 50,
  4656. // The rotation of the chart, where the first data arc begins.
  4657. rotation: -HALF_PI$1,
  4658. // The total circumference of the chart.
  4659. circumference: DOUBLE_PI$1,
  4660. // Need to override these to give a nice default
  4661. tooltips: {
  4662. callbacks: {
  4663. title: function() {
  4664. return '';
  4665. },
  4666. label: function(tooltipItem, data) {
  4667. var dataLabel = data.labels[tooltipItem.index];
  4668. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  4669. if (helpers$1.isArray(dataLabel)) {
  4670. // show value on first line of multiline label
  4671. // need to clone because we are changing the value
  4672. dataLabel = dataLabel.slice();
  4673. dataLabel[0] += value;
  4674. } else {
  4675. dataLabel += value;
  4676. }
  4677. return dataLabel;
  4678. }
  4679. }
  4680. }
  4681. });
  4682. var controller_doughnut = core_datasetController.extend({
  4683. dataElementType: elements.Arc,
  4684. linkScales: helpers$1.noop,
  4685. /**
  4686. * @private
  4687. */
  4688. _dataElementOptions: [
  4689. 'backgroundColor',
  4690. 'borderColor',
  4691. 'borderWidth',
  4692. 'borderAlign',
  4693. 'hoverBackgroundColor',
  4694. 'hoverBorderColor',
  4695. 'hoverBorderWidth',
  4696. ],
  4697. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  4698. getRingIndex: function(datasetIndex) {
  4699. var ringIndex = 0;
  4700. for (var j = 0; j < datasetIndex; ++j) {
  4701. if (this.chart.isDatasetVisible(j)) {
  4702. ++ringIndex;
  4703. }
  4704. }
  4705. return ringIndex;
  4706. },
  4707. update: function(reset) {
  4708. var me = this;
  4709. var chart = me.chart;
  4710. var chartArea = chart.chartArea;
  4711. var opts = chart.options;
  4712. var ratioX = 1;
  4713. var ratioY = 1;
  4714. var offsetX = 0;
  4715. var offsetY = 0;
  4716. var meta = me.getMeta();
  4717. var arcs = meta.data;
  4718. var cutout = opts.cutoutPercentage / 100 || 0;
  4719. var circumference = opts.circumference;
  4720. var chartWeight = me._getRingWeight(me.index);
  4721. var maxWidth, maxHeight, i, ilen;
  4722. // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc
  4723. if (circumference < DOUBLE_PI$1) {
  4724. var startAngle = opts.rotation % DOUBLE_PI$1;
  4725. startAngle += startAngle >= PI$1 ? -DOUBLE_PI$1 : startAngle < -PI$1 ? DOUBLE_PI$1 : 0;
  4726. var endAngle = startAngle + circumference;
  4727. var startX = Math.cos(startAngle);
  4728. var startY = Math.sin(startAngle);
  4729. var endX = Math.cos(endAngle);
  4730. var endY = Math.sin(endAngle);
  4731. var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI$1;
  4732. var contains90 = (startAngle <= HALF_PI$1 && endAngle >= HALF_PI$1) || endAngle >= DOUBLE_PI$1 + HALF_PI$1;
  4733. var contains180 = startAngle === -PI$1 || endAngle >= PI$1;
  4734. var contains270 = (startAngle <= -HALF_PI$1 && endAngle >= -HALF_PI$1) || endAngle >= PI$1 + HALF_PI$1;
  4735. var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);
  4736. var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);
  4737. var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);
  4738. var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);
  4739. ratioX = (maxX - minX) / 2;
  4740. ratioY = (maxY - minY) / 2;
  4741. offsetX = -(maxX + minX) / 2;
  4742. offsetY = -(maxY + minY) / 2;
  4743. }
  4744. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4745. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  4746. }
  4747. chart.borderWidth = me.getMaxBorderWidth();
  4748. maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;
  4749. maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;
  4750. chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  4751. chart.innerRadius = Math.max(chart.outerRadius * cutout, 0);
  4752. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
  4753. chart.offsetX = offsetX * chart.outerRadius;
  4754. chart.offsetY = offsetY * chart.outerRadius;
  4755. meta.total = me.calculateTotal();
  4756. me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
  4757. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
  4758. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4759. me.updateElement(arcs[i], i, reset);
  4760. }
  4761. },
  4762. updateElement: function(arc, index, reset) {
  4763. var me = this;
  4764. var chart = me.chart;
  4765. var chartArea = chart.chartArea;
  4766. var opts = chart.options;
  4767. var animationOpts = opts.animation;
  4768. var centerX = (chartArea.left + chartArea.right) / 2;
  4769. var centerY = (chartArea.top + chartArea.bottom) / 2;
  4770. var startAngle = opts.rotation; // non reset case handled later
  4771. var endAngle = opts.rotation; // non reset case handled later
  4772. var dataset = me.getDataset();
  4773. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / DOUBLE_PI$1);
  4774. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  4775. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  4776. var options = arc._options || {};
  4777. helpers$1.extend(arc, {
  4778. // Utility
  4779. _datasetIndex: me.index,
  4780. _index: index,
  4781. // Desired view properties
  4782. _model: {
  4783. backgroundColor: options.backgroundColor,
  4784. borderColor: options.borderColor,
  4785. borderWidth: options.borderWidth,
  4786. borderAlign: options.borderAlign,
  4787. x: centerX + chart.offsetX,
  4788. y: centerY + chart.offsetY,
  4789. startAngle: startAngle,
  4790. endAngle: endAngle,
  4791. circumference: circumference,
  4792. outerRadius: outerRadius,
  4793. innerRadius: innerRadius,
  4794. label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  4795. }
  4796. });
  4797. var model = arc._model;
  4798. // Set correct angles if not resetting
  4799. if (!reset || !animationOpts.animateRotate) {
  4800. if (index === 0) {
  4801. model.startAngle = opts.rotation;
  4802. } else {
  4803. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  4804. }
  4805. model.endAngle = model.startAngle + model.circumference;
  4806. }
  4807. arc.pivot();
  4808. },
  4809. calculateTotal: function() {
  4810. var dataset = this.getDataset();
  4811. var meta = this.getMeta();
  4812. var total = 0;
  4813. var value;
  4814. helpers$1.each(meta.data, function(element, index) {
  4815. value = dataset.data[index];
  4816. if (!isNaN(value) && !element.hidden) {
  4817. total += Math.abs(value);
  4818. }
  4819. });
  4820. /* if (total === 0) {
  4821. total = NaN;
  4822. }*/
  4823. return total;
  4824. },
  4825. calculateCircumference: function(value) {
  4826. var total = this.getMeta().total;
  4827. if (total > 0 && !isNaN(value)) {
  4828. return DOUBLE_PI$1 * (Math.abs(value) / total);
  4829. }
  4830. return 0;
  4831. },
  4832. // gets the max border or hover width to properly scale pie charts
  4833. getMaxBorderWidth: function(arcs) {
  4834. var me = this;
  4835. var max = 0;
  4836. var chart = me.chart;
  4837. var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
  4838. if (!arcs) {
  4839. // Find the outmost visible dataset
  4840. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  4841. if (chart.isDatasetVisible(i)) {
  4842. meta = chart.getDatasetMeta(i);
  4843. arcs = meta.data;
  4844. if (i !== me.index) {
  4845. controller = meta.controller;
  4846. }
  4847. break;
  4848. }
  4849. }
  4850. }
  4851. if (!arcs) {
  4852. return 0;
  4853. }
  4854. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4855. arc = arcs[i];
  4856. if (controller) {
  4857. controller._configure();
  4858. options = controller._resolveDataElementOptions(arc, i);
  4859. } else {
  4860. options = arc._options;
  4861. }
  4862. if (options.borderAlign !== 'inner') {
  4863. borderWidth = options.borderWidth;
  4864. hoverWidth = options.hoverBorderWidth;
  4865. max = borderWidth > max ? borderWidth : max;
  4866. max = hoverWidth > max ? hoverWidth : max;
  4867. }
  4868. }
  4869. return max;
  4870. },
  4871. /**
  4872. * @protected
  4873. */
  4874. setHoverStyle: function(arc) {
  4875. var model = arc._model;
  4876. var options = arc._options;
  4877. var getHoverColor = helpers$1.getHoverColor;
  4878. arc.$previousStyle = {
  4879. backgroundColor: model.backgroundColor,
  4880. borderColor: model.borderColor,
  4881. borderWidth: model.borderWidth,
  4882. };
  4883. model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4884. model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
  4885. model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
  4886. },
  4887. /**
  4888. * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
  4889. * @private
  4890. */
  4891. _getRingWeightOffset: function(datasetIndex) {
  4892. var ringWeightOffset = 0;
  4893. for (var i = 0; i < datasetIndex; ++i) {
  4894. if (this.chart.isDatasetVisible(i)) {
  4895. ringWeightOffset += this._getRingWeight(i);
  4896. }
  4897. }
  4898. return ringWeightOffset;
  4899. },
  4900. /**
  4901. * @private
  4902. */
  4903. _getRingWeight: function(dataSetIndex) {
  4904. return Math.max(valueOrDefault$5(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
  4905. },
  4906. /**
  4907. * Returns the sum of all visibile data set weights. This value can be 0.
  4908. * @private
  4909. */
  4910. _getVisibleDatasetWeightTotal: function() {
  4911. return this._getRingWeightOffset(this.chart.data.datasets.length);
  4912. }
  4913. });
  4914. core_defaults._set('horizontalBar', {
  4915. hover: {
  4916. mode: 'index',
  4917. axis: 'y'
  4918. },
  4919. scales: {
  4920. xAxes: [{
  4921. type: 'linear',
  4922. position: 'bottom'
  4923. }],
  4924. yAxes: [{
  4925. type: 'category',
  4926. position: 'left',
  4927. offset: true,
  4928. gridLines: {
  4929. offsetGridLines: true
  4930. }
  4931. }]
  4932. },
  4933. elements: {
  4934. rectangle: {
  4935. borderSkipped: 'left'
  4936. }
  4937. },
  4938. tooltips: {
  4939. mode: 'index',
  4940. axis: 'y'
  4941. }
  4942. });
  4943. core_defaults._set('global', {
  4944. datasets: {
  4945. horizontalBar: {
  4946. categoryPercentage: 0.8,
  4947. barPercentage: 0.9
  4948. }
  4949. }
  4950. });
  4951. var controller_horizontalBar = controller_bar.extend({
  4952. /**
  4953. * @private
  4954. */
  4955. _getValueScaleId: function() {
  4956. return this.getMeta().xAxisID;
  4957. },
  4958. /**
  4959. * @private
  4960. */
  4961. _getIndexScaleId: function() {
  4962. return this.getMeta().yAxisID;
  4963. }
  4964. });
  4965. var valueOrDefault$6 = helpers$1.valueOrDefault;
  4966. var resolve$2 = helpers$1.options.resolve;
  4967. var isPointInArea = helpers$1.canvas._isPointInArea;
  4968. core_defaults._set('line', {
  4969. showLines: true,
  4970. spanGaps: false,
  4971. hover: {
  4972. mode: 'label'
  4973. },
  4974. scales: {
  4975. xAxes: [{
  4976. type: 'category',
  4977. id: 'x-axis-0'
  4978. }],
  4979. yAxes: [{
  4980. type: 'linear',
  4981. id: 'y-axis-0'
  4982. }]
  4983. }
  4984. });
  4985. function scaleClip(scale, halfBorderWidth) {
  4986. var tickOpts = scale && scale.options.ticks || {};
  4987. var reverse = tickOpts.reverse;
  4988. var min = tickOpts.min === undefined ? halfBorderWidth : 0;
  4989. var max = tickOpts.max === undefined ? halfBorderWidth : 0;
  4990. return {
  4991. start: reverse ? max : min,
  4992. end: reverse ? min : max
  4993. };
  4994. }
  4995. function defaultClip(xScale, yScale, borderWidth) {
  4996. var halfBorderWidth = borderWidth / 2;
  4997. var x = scaleClip(xScale, halfBorderWidth);
  4998. var y = scaleClip(yScale, halfBorderWidth);
  4999. return {
  5000. top: y.end,
  5001. right: x.end,
  5002. bottom: y.start,
  5003. left: x.start
  5004. };
  5005. }
  5006. function toClip(value) {
  5007. var t, r, b, l;
  5008. if (helpers$1.isObject(value)) {
  5009. t = value.top;
  5010. r = value.right;
  5011. b = value.bottom;
  5012. l = value.left;
  5013. } else {
  5014. t = r = b = l = value;
  5015. }
  5016. return {
  5017. top: t,
  5018. right: r,
  5019. bottom: b,
  5020. left: l
  5021. };
  5022. }
  5023. var controller_line = core_datasetController.extend({
  5024. datasetElementType: elements.Line,
  5025. dataElementType: elements.Point,
  5026. /**
  5027. * @private
  5028. */
  5029. _datasetElementOptions: [
  5030. 'backgroundColor',
  5031. 'borderCapStyle',
  5032. 'borderColor',
  5033. 'borderDash',
  5034. 'borderDashOffset',
  5035. 'borderJoinStyle',
  5036. 'borderWidth',
  5037. 'cubicInterpolationMode',
  5038. 'fill'
  5039. ],
  5040. /**
  5041. * @private
  5042. */
  5043. _dataElementOptions: {
  5044. backgroundColor: 'pointBackgroundColor',
  5045. borderColor: 'pointBorderColor',
  5046. borderWidth: 'pointBorderWidth',
  5047. hitRadius: 'pointHitRadius',
  5048. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5049. hoverBorderColor: 'pointHoverBorderColor',
  5050. hoverBorderWidth: 'pointHoverBorderWidth',
  5051. hoverRadius: 'pointHoverRadius',
  5052. pointStyle: 'pointStyle',
  5053. radius: 'pointRadius',
  5054. rotation: 'pointRotation'
  5055. },
  5056. update: function(reset) {
  5057. var me = this;
  5058. var meta = me.getMeta();
  5059. var line = meta.dataset;
  5060. var points = meta.data || [];
  5061. var options = me.chart.options;
  5062. var config = me._config;
  5063. var showLine = me._showLine = valueOrDefault$6(config.showLine, options.showLines);
  5064. var i, ilen;
  5065. me._xScale = me.getScaleForId(meta.xAxisID);
  5066. me._yScale = me.getScaleForId(meta.yAxisID);
  5067. // Update Line
  5068. if (showLine) {
  5069. // Compatibility: If the properties are defined with only the old name, use those values
  5070. if (config.tension !== undefined && config.lineTension === undefined) {
  5071. config.lineTension = config.tension;
  5072. }
  5073. // Utility
  5074. line._scale = me._yScale;
  5075. line._datasetIndex = me.index;
  5076. // Data
  5077. line._children = points;
  5078. // Model
  5079. line._model = me._resolveDatasetElementOptions(line);
  5080. line.pivot();
  5081. }
  5082. // Update Points
  5083. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5084. me.updateElement(points[i], i, reset);
  5085. }
  5086. if (showLine && line._model.tension !== 0) {
  5087. me.updateBezierControlPoints();
  5088. }
  5089. // Now pivot the point for animation
  5090. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5091. points[i].pivot();
  5092. }
  5093. },
  5094. updateElement: function(point, index, reset) {
  5095. var me = this;
  5096. var meta = me.getMeta();
  5097. var custom = point.custom || {};
  5098. var dataset = me.getDataset();
  5099. var datasetIndex = me.index;
  5100. var value = dataset.data[index];
  5101. var xScale = me._xScale;
  5102. var yScale = me._yScale;
  5103. var lineModel = meta.dataset._model;
  5104. var x, y;
  5105. var options = me._resolveDataElementOptions(point, index);
  5106. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  5107. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  5108. // Utility
  5109. point._xScale = xScale;
  5110. point._yScale = yScale;
  5111. point._options = options;
  5112. point._datasetIndex = datasetIndex;
  5113. point._index = index;
  5114. // Desired view properties
  5115. point._model = {
  5116. x: x,
  5117. y: y,
  5118. skip: custom.skip || isNaN(x) || isNaN(y),
  5119. // Appearance
  5120. radius: options.radius,
  5121. pointStyle: options.pointStyle,
  5122. rotation: options.rotation,
  5123. backgroundColor: options.backgroundColor,
  5124. borderColor: options.borderColor,
  5125. borderWidth: options.borderWidth,
  5126. tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0),
  5127. steppedLine: lineModel ? lineModel.steppedLine : false,
  5128. // Tooltip
  5129. hitRadius: options.hitRadius
  5130. };
  5131. },
  5132. /**
  5133. * @private
  5134. */
  5135. _resolveDatasetElementOptions: function(element) {
  5136. var me = this;
  5137. var config = me._config;
  5138. var custom = element.custom || {};
  5139. var options = me.chart.options;
  5140. var lineOptions = options.elements.line;
  5141. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5142. // The default behavior of lines is to break at null values, according
  5143. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  5144. // This option gives lines the ability to span gaps
  5145. values.spanGaps = valueOrDefault$6(config.spanGaps, options.spanGaps);
  5146. values.tension = valueOrDefault$6(config.lineTension, lineOptions.tension);
  5147. values.steppedLine = resolve$2([custom.steppedLine, config.steppedLine, lineOptions.stepped]);
  5148. values.clip = toClip(valueOrDefault$6(config.clip, defaultClip(me._xScale, me._yScale, values.borderWidth)));
  5149. return values;
  5150. },
  5151. calculatePointY: function(value, index, datasetIndex) {
  5152. var me = this;
  5153. var chart = me.chart;
  5154. var yScale = me._yScale;
  5155. var sumPos = 0;
  5156. var sumNeg = 0;
  5157. var i, ds, dsMeta, stackedRightValue, rightValue, metasets, ilen;
  5158. if (yScale.options.stacked) {
  5159. rightValue = +yScale.getRightValue(value);
  5160. metasets = chart._getSortedVisibleDatasetMetas();
  5161. ilen = metasets.length;
  5162. for (i = 0; i < ilen; ++i) {
  5163. dsMeta = metasets[i];
  5164. if (dsMeta.index === datasetIndex) {
  5165. break;
  5166. }
  5167. ds = chart.data.datasets[dsMeta.index];
  5168. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id) {
  5169. stackedRightValue = +yScale.getRightValue(ds.data[index]);
  5170. if (stackedRightValue < 0) {
  5171. sumNeg += stackedRightValue || 0;
  5172. } else {
  5173. sumPos += stackedRightValue || 0;
  5174. }
  5175. }
  5176. }
  5177. if (rightValue < 0) {
  5178. return yScale.getPixelForValue(sumNeg + rightValue);
  5179. }
  5180. return yScale.getPixelForValue(sumPos + rightValue);
  5181. }
  5182. return yScale.getPixelForValue(value);
  5183. },
  5184. updateBezierControlPoints: function() {
  5185. var me = this;
  5186. var chart = me.chart;
  5187. var meta = me.getMeta();
  5188. var lineModel = meta.dataset._model;
  5189. var area = chart.chartArea;
  5190. var points = meta.data || [];
  5191. var i, ilen, model, controlPoints;
  5192. // Only consider points that are drawn in case the spanGaps option is used
  5193. if (lineModel.spanGaps) {
  5194. points = points.filter(function(pt) {
  5195. return !pt._model.skip;
  5196. });
  5197. }
  5198. function capControlPoint(pt, min, max) {
  5199. return Math.max(Math.min(pt, max), min);
  5200. }
  5201. if (lineModel.cubicInterpolationMode === 'monotone') {
  5202. helpers$1.splineCurveMonotone(points);
  5203. } else {
  5204. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5205. model = points[i]._model;
  5206. controlPoints = helpers$1.splineCurve(
  5207. helpers$1.previousItem(points, i)._model,
  5208. model,
  5209. helpers$1.nextItem(points, i)._model,
  5210. lineModel.tension
  5211. );
  5212. model.controlPointPreviousX = controlPoints.previous.x;
  5213. model.controlPointPreviousY = controlPoints.previous.y;
  5214. model.controlPointNextX = controlPoints.next.x;
  5215. model.controlPointNextY = controlPoints.next.y;
  5216. }
  5217. }
  5218. if (chart.options.elements.line.capBezierPoints) {
  5219. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5220. model = points[i]._model;
  5221. if (isPointInArea(model, area)) {
  5222. if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
  5223. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  5224. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  5225. }
  5226. if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
  5227. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  5228. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  5229. }
  5230. }
  5231. }
  5232. }
  5233. },
  5234. draw: function() {
  5235. var me = this;
  5236. var chart = me.chart;
  5237. var meta = me.getMeta();
  5238. var points = meta.data || [];
  5239. var area = chart.chartArea;
  5240. var canvas = chart.canvas;
  5241. var i = 0;
  5242. var ilen = points.length;
  5243. var clip;
  5244. if (me._showLine) {
  5245. clip = meta.dataset._model.clip;
  5246. helpers$1.canvas.clipArea(chart.ctx, {
  5247. left: clip.left === false ? 0 : area.left - clip.left,
  5248. right: clip.right === false ? canvas.width : area.right + clip.right,
  5249. top: clip.top === false ? 0 : area.top - clip.top,
  5250. bottom: clip.bottom === false ? canvas.height : area.bottom + clip.bottom
  5251. });
  5252. meta.dataset.draw();
  5253. helpers$1.canvas.unclipArea(chart.ctx);
  5254. }
  5255. // Draw the points
  5256. for (; i < ilen; ++i) {
  5257. points[i].draw(area);
  5258. }
  5259. },
  5260. /**
  5261. * @protected
  5262. */
  5263. setHoverStyle: function(point) {
  5264. var model = point._model;
  5265. var options = point._options;
  5266. var getHoverColor = helpers$1.getHoverColor;
  5267. point.$previousStyle = {
  5268. backgroundColor: model.backgroundColor,
  5269. borderColor: model.borderColor,
  5270. borderWidth: model.borderWidth,
  5271. radius: model.radius
  5272. };
  5273. model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5274. model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));
  5275. model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);
  5276. model.radius = valueOrDefault$6(options.hoverRadius, options.radius);
  5277. },
  5278. });
  5279. var resolve$3 = helpers$1.options.resolve;
  5280. core_defaults._set('polarArea', {
  5281. scale: {
  5282. type: 'radialLinear',
  5283. angleLines: {
  5284. display: false
  5285. },
  5286. gridLines: {
  5287. circular: true
  5288. },
  5289. pointLabels: {
  5290. display: false
  5291. },
  5292. ticks: {
  5293. beginAtZero: true
  5294. }
  5295. },
  5296. // Boolean - Whether to animate the rotation of the chart
  5297. animation: {
  5298. animateRotate: true,
  5299. animateScale: true
  5300. },
  5301. startAngle: -0.5 * Math.PI,
  5302. legendCallback: function(chart) {
  5303. var list = document.createElement('ul');
  5304. var data = chart.data;
  5305. var datasets = data.datasets;
  5306. var labels = data.labels;
  5307. var i, ilen, listItem, listItemSpan;
  5308. list.setAttribute('class', chart.id + '-legend');
  5309. if (datasets.length) {
  5310. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  5311. listItem = list.appendChild(document.createElement('li'));
  5312. listItemSpan = listItem.appendChild(document.createElement('span'));
  5313. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  5314. if (labels[i]) {
  5315. listItem.appendChild(document.createTextNode(labels[i]));
  5316. }
  5317. }
  5318. }
  5319. return list.outerHTML;
  5320. },
  5321. legend: {
  5322. labels: {
  5323. generateLabels: function(chart) {
  5324. var data = chart.data;
  5325. if (data.labels.length && data.datasets.length) {
  5326. return data.labels.map(function(label, i) {
  5327. var meta = chart.getDatasetMeta(0);
  5328. var style = meta.controller.getStyle(i);
  5329. return {
  5330. text: label,
  5331. fillStyle: style.backgroundColor,
  5332. strokeStyle: style.borderColor,
  5333. lineWidth: style.borderWidth,
  5334. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  5335. // Extra data used for toggling the correct item
  5336. index: i
  5337. };
  5338. });
  5339. }
  5340. return [];
  5341. }
  5342. },
  5343. onClick: function(e, legendItem) {
  5344. var index = legendItem.index;
  5345. var chart = this.chart;
  5346. var i, ilen, meta;
  5347. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  5348. meta = chart.getDatasetMeta(i);
  5349. meta.data[index].hidden = !meta.data[index].hidden;
  5350. }
  5351. chart.update();
  5352. }
  5353. },
  5354. // Need to override these to give a nice default
  5355. tooltips: {
  5356. callbacks: {
  5357. title: function() {
  5358. return '';
  5359. },
  5360. label: function(item, data) {
  5361. return data.labels[item.index] + ': ' + item.yLabel;
  5362. }
  5363. }
  5364. }
  5365. });
  5366. var controller_polarArea = core_datasetController.extend({
  5367. dataElementType: elements.Arc,
  5368. linkScales: helpers$1.noop,
  5369. /**
  5370. * @private
  5371. */
  5372. _dataElementOptions: [
  5373. 'backgroundColor',
  5374. 'borderColor',
  5375. 'borderWidth',
  5376. 'borderAlign',
  5377. 'hoverBackgroundColor',
  5378. 'hoverBorderColor',
  5379. 'hoverBorderWidth',
  5380. ],
  5381. /**
  5382. * @private
  5383. */
  5384. _getIndexScaleId: function() {
  5385. return this.chart.scale.id;
  5386. },
  5387. /**
  5388. * @private
  5389. */
  5390. _getValueScaleId: function() {
  5391. return this.chart.scale.id;
  5392. },
  5393. update: function(reset) {
  5394. var me = this;
  5395. var dataset = me.getDataset();
  5396. var meta = me.getMeta();
  5397. var start = me.chart.options.startAngle || 0;
  5398. var starts = me._starts = [];
  5399. var angles = me._angles = [];
  5400. var arcs = meta.data;
  5401. var i, ilen, angle;
  5402. me._updateRadius();
  5403. meta.count = me.countVisibleElements();
  5404. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  5405. starts[i] = start;
  5406. angle = me._computeAngle(i);
  5407. angles[i] = angle;
  5408. start += angle;
  5409. }
  5410. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  5411. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  5412. me.updateElement(arcs[i], i, reset);
  5413. }
  5414. },
  5415. /**
  5416. * @private
  5417. */
  5418. _updateRadius: function() {
  5419. var me = this;
  5420. var chart = me.chart;
  5421. var chartArea = chart.chartArea;
  5422. var opts = chart.options;
  5423. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  5424. chart.outerRadius = Math.max(minSize / 2, 0);
  5425. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  5426. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  5427. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  5428. me.innerRadius = me.outerRadius - chart.radiusLength;
  5429. },
  5430. updateElement: function(arc, index, reset) {
  5431. var me = this;
  5432. var chart = me.chart;
  5433. var dataset = me.getDataset();
  5434. var opts = chart.options;
  5435. var animationOpts = opts.animation;
  5436. var scale = chart.scale;
  5437. var labels = chart.data.labels;
  5438. var centerX = scale.xCenter;
  5439. var centerY = scale.yCenter;
  5440. // var negHalfPI = -0.5 * Math.PI;
  5441. var datasetStartAngle = opts.startAngle;
  5442. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5443. var startAngle = me._starts[index];
  5444. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  5445. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5446. var options = arc._options || {};
  5447. helpers$1.extend(arc, {
  5448. // Utility
  5449. _datasetIndex: me.index,
  5450. _index: index,
  5451. _scale: scale,
  5452. // Desired view properties
  5453. _model: {
  5454. backgroundColor: options.backgroundColor,
  5455. borderColor: options.borderColor,
  5456. borderWidth: options.borderWidth,
  5457. borderAlign: options.borderAlign,
  5458. x: centerX,
  5459. y: centerY,
  5460. innerRadius: 0,
  5461. outerRadius: reset ? resetRadius : distance,
  5462. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  5463. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  5464. label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
  5465. }
  5466. });
  5467. arc.pivot();
  5468. },
  5469. countVisibleElements: function() {
  5470. var dataset = this.getDataset();
  5471. var meta = this.getMeta();
  5472. var count = 0;
  5473. helpers$1.each(meta.data, function(element, index) {
  5474. if (!isNaN(dataset.data[index]) && !element.hidden) {
  5475. count++;
  5476. }
  5477. });
  5478. return count;
  5479. },
  5480. /**
  5481. * @protected
  5482. */
  5483. setHoverStyle: function(arc) {
  5484. var model = arc._model;
  5485. var options = arc._options;
  5486. var getHoverColor = helpers$1.getHoverColor;
  5487. var valueOrDefault = helpers$1.valueOrDefault;
  5488. arc.$previousStyle = {
  5489. backgroundColor: model.backgroundColor,
  5490. borderColor: model.borderColor,
  5491. borderWidth: model.borderWidth,
  5492. };
  5493. model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5494. model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
  5495. model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  5496. },
  5497. /**
  5498. * @private
  5499. */
  5500. _computeAngle: function(index) {
  5501. var me = this;
  5502. var count = this.getMeta().count;
  5503. var dataset = me.getDataset();
  5504. var meta = me.getMeta();
  5505. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  5506. return 0;
  5507. }
  5508. // Scriptable options
  5509. var context = {
  5510. chart: me.chart,
  5511. dataIndex: index,
  5512. dataset: dataset,
  5513. datasetIndex: me.index
  5514. };
  5515. return resolve$3([
  5516. me.chart.options.elements.arc.angle,
  5517. (2 * Math.PI) / count
  5518. ], context, index);
  5519. }
  5520. });
  5521. core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
  5522. core_defaults._set('pie', {
  5523. cutoutPercentage: 0
  5524. });
  5525. // Pie charts are Doughnut chart with different defaults
  5526. var controller_pie = controller_doughnut;
  5527. var valueOrDefault$7 = helpers$1.valueOrDefault;
  5528. core_defaults._set('radar', {
  5529. spanGaps: false,
  5530. scale: {
  5531. type: 'radialLinear'
  5532. },
  5533. elements: {
  5534. line: {
  5535. fill: 'start',
  5536. tension: 0 // no bezier in radar
  5537. }
  5538. }
  5539. });
  5540. var controller_radar = core_datasetController.extend({
  5541. datasetElementType: elements.Line,
  5542. dataElementType: elements.Point,
  5543. linkScales: helpers$1.noop,
  5544. /**
  5545. * @private
  5546. */
  5547. _datasetElementOptions: [
  5548. 'backgroundColor',
  5549. 'borderWidth',
  5550. 'borderColor',
  5551. 'borderCapStyle',
  5552. 'borderDash',
  5553. 'borderDashOffset',
  5554. 'borderJoinStyle',
  5555. 'fill'
  5556. ],
  5557. /**
  5558. * @private
  5559. */
  5560. _dataElementOptions: {
  5561. backgroundColor: 'pointBackgroundColor',
  5562. borderColor: 'pointBorderColor',
  5563. borderWidth: 'pointBorderWidth',
  5564. hitRadius: 'pointHitRadius',
  5565. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5566. hoverBorderColor: 'pointHoverBorderColor',
  5567. hoverBorderWidth: 'pointHoverBorderWidth',
  5568. hoverRadius: 'pointHoverRadius',
  5569. pointStyle: 'pointStyle',
  5570. radius: 'pointRadius',
  5571. rotation: 'pointRotation'
  5572. },
  5573. /**
  5574. * @private
  5575. */
  5576. _getIndexScaleId: function() {
  5577. return this.chart.scale.id;
  5578. },
  5579. /**
  5580. * @private
  5581. */
  5582. _getValueScaleId: function() {
  5583. return this.chart.scale.id;
  5584. },
  5585. update: function(reset) {
  5586. var me = this;
  5587. var meta = me.getMeta();
  5588. var line = meta.dataset;
  5589. var points = meta.data || [];
  5590. var scale = me.chart.scale;
  5591. var config = me._config;
  5592. var i, ilen;
  5593. // Compatibility: If the properties are defined with only the old name, use those values
  5594. if (config.tension !== undefined && config.lineTension === undefined) {
  5595. config.lineTension = config.tension;
  5596. }
  5597. // Utility
  5598. line._scale = scale;
  5599. line._datasetIndex = me.index;
  5600. // Data
  5601. line._children = points;
  5602. line._loop = true;
  5603. // Model
  5604. line._model = me._resolveDatasetElementOptions(line);
  5605. line.pivot();
  5606. // Update Points
  5607. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5608. me.updateElement(points[i], i, reset);
  5609. }
  5610. // Update bezier control points
  5611. me.updateBezierControlPoints();
  5612. // Now pivot the point for animation
  5613. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5614. points[i].pivot();
  5615. }
  5616. },
  5617. updateElement: function(point, index, reset) {
  5618. var me = this;
  5619. var custom = point.custom || {};
  5620. var dataset = me.getDataset();
  5621. var scale = me.chart.scale;
  5622. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  5623. var options = me._resolveDataElementOptions(point, index);
  5624. var lineModel = me.getMeta().dataset._model;
  5625. var x = reset ? scale.xCenter : pointPosition.x;
  5626. var y = reset ? scale.yCenter : pointPosition.y;
  5627. // Utility
  5628. point._scale = scale;
  5629. point._options = options;
  5630. point._datasetIndex = me.index;
  5631. point._index = index;
  5632. // Desired view properties
  5633. point._model = {
  5634. x: x, // value not used in dataset scale, but we want a consistent API between scales
  5635. y: y,
  5636. skip: custom.skip || isNaN(x) || isNaN(y),
  5637. // Appearance
  5638. radius: options.radius,
  5639. pointStyle: options.pointStyle,
  5640. rotation: options.rotation,
  5641. backgroundColor: options.backgroundColor,
  5642. borderColor: options.borderColor,
  5643. borderWidth: options.borderWidth,
  5644. tension: valueOrDefault$7(custom.tension, lineModel ? lineModel.tension : 0),
  5645. // Tooltip
  5646. hitRadius: options.hitRadius
  5647. };
  5648. },
  5649. /**
  5650. * @private
  5651. */
  5652. _resolveDatasetElementOptions: function() {
  5653. var me = this;
  5654. var config = me._config;
  5655. var options = me.chart.options;
  5656. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5657. values.spanGaps = valueOrDefault$7(config.spanGaps, options.spanGaps);
  5658. values.tension = valueOrDefault$7(config.lineTension, options.elements.line.tension);
  5659. return values;
  5660. },
  5661. updateBezierControlPoints: function() {
  5662. var me = this;
  5663. var meta = me.getMeta();
  5664. var area = me.chart.chartArea;
  5665. var points = meta.data || [];
  5666. var i, ilen, model, controlPoints;
  5667. // Only consider points that are drawn in case the spanGaps option is used
  5668. if (meta.dataset._model.spanGaps) {
  5669. points = points.filter(function(pt) {
  5670. return !pt._model.skip;
  5671. });
  5672. }
  5673. function capControlPoint(pt, min, max) {
  5674. return Math.max(Math.min(pt, max), min);
  5675. }
  5676. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5677. model = points[i]._model;
  5678. controlPoints = helpers$1.splineCurve(
  5679. helpers$1.previousItem(points, i, true)._model,
  5680. model,
  5681. helpers$1.nextItem(points, i, true)._model,
  5682. model.tension
  5683. );
  5684. // Prevent the bezier going outside of the bounds of the graph
  5685. model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
  5686. model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
  5687. model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
  5688. model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
  5689. }
  5690. },
  5691. setHoverStyle: function(point) {
  5692. var model = point._model;
  5693. var options = point._options;
  5694. var getHoverColor = helpers$1.getHoverColor;
  5695. point.$previousStyle = {
  5696. backgroundColor: model.backgroundColor,
  5697. borderColor: model.borderColor,
  5698. borderWidth: model.borderWidth,
  5699. radius: model.radius
  5700. };
  5701. model.backgroundColor = valueOrDefault$7(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5702. model.borderColor = valueOrDefault$7(options.hoverBorderColor, getHoverColor(options.borderColor));
  5703. model.borderWidth = valueOrDefault$7(options.hoverBorderWidth, options.borderWidth);
  5704. model.radius = valueOrDefault$7(options.hoverRadius, options.radius);
  5705. }
  5706. });
  5707. core_defaults._set('scatter', {
  5708. hover: {
  5709. mode: 'single'
  5710. },
  5711. scales: {
  5712. xAxes: [{
  5713. id: 'x-axis-1', // need an ID so datasets can reference the scale
  5714. type: 'linear', // scatter should not use a category axis
  5715. position: 'bottom'
  5716. }],
  5717. yAxes: [{
  5718. id: 'y-axis-1',
  5719. type: 'linear',
  5720. position: 'left'
  5721. }]
  5722. },
  5723. tooltips: {
  5724. callbacks: {
  5725. title: function() {
  5726. return ''; // doesn't make sense for scatter since data are formatted as a point
  5727. },
  5728. label: function(item) {
  5729. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  5730. }
  5731. }
  5732. }
  5733. });
  5734. core_defaults._set('global', {
  5735. datasets: {
  5736. scatter: {
  5737. showLine: false
  5738. }
  5739. }
  5740. });
  5741. // Scatter charts use line controllers
  5742. var controller_scatter = controller_line;
  5743. // NOTE export a map in which the key represents the controller type, not
  5744. // the class, and so must be CamelCase in order to be correctly retrieved
  5745. // by the controller in core.controller.js (`controllers[meta.type]`).
  5746. var controllers = {
  5747. bar: controller_bar,
  5748. bubble: controller_bubble,
  5749. doughnut: controller_doughnut,
  5750. horizontalBar: controller_horizontalBar,
  5751. line: controller_line,
  5752. polarArea: controller_polarArea,
  5753. pie: controller_pie,
  5754. radar: controller_radar,
  5755. scatter: controller_scatter
  5756. };
  5757. /**
  5758. * Helper function to get relative position for an event
  5759. * @param {Event|IEvent} event - The event to get the position for
  5760. * @param {Chart} chart - The chart
  5761. * @returns {object} the event position
  5762. */
  5763. function getRelativePosition(e, chart) {
  5764. if (e.native) {
  5765. return {
  5766. x: e.x,
  5767. y: e.y
  5768. };
  5769. }
  5770. return helpers$1.getRelativePosition(e, chart);
  5771. }
  5772. /**
  5773. * Helper function to traverse all of the visible elements in the chart
  5774. * @param {Chart} chart - the chart
  5775. * @param {function} handler - the callback to execute for each visible item
  5776. */
  5777. function parseVisibleItems(chart, handler) {
  5778. var metasets = chart._getSortedVisibleDatasetMetas();
  5779. var metadata, i, j, ilen, jlen, element;
  5780. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  5781. metadata = metasets[i].data;
  5782. for (j = 0, jlen = metadata.length; j < jlen; ++j) {
  5783. element = metadata[j];
  5784. if (!element._view.skip) {
  5785. handler(element);
  5786. }
  5787. }
  5788. }
  5789. }
  5790. /**
  5791. * Helper function to get the items that intersect the event position
  5792. * @param {ChartElement[]} items - elements to filter
  5793. * @param {object} position - the point to be nearest to
  5794. * @return {ChartElement[]} the nearest items
  5795. */
  5796. function getIntersectItems(chart, position) {
  5797. var elements = [];
  5798. parseVisibleItems(chart, function(element) {
  5799. if (element.inRange(position.x, position.y)) {
  5800. elements.push(element);
  5801. }
  5802. });
  5803. return elements;
  5804. }
  5805. /**
  5806. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  5807. * @param {Chart} chart - the chart to look at elements from
  5808. * @param {object} position - the point to be nearest to
  5809. * @param {boolean} intersect - if true, only consider items that intersect the position
  5810. * @param {function} distanceMetric - function to provide the distance between points
  5811. * @return {ChartElement[]} the nearest items
  5812. */
  5813. function getNearestItems(chart, position, intersect, distanceMetric) {
  5814. var minDistance = Number.POSITIVE_INFINITY;
  5815. var nearestItems = [];
  5816. parseVisibleItems(chart, function(element) {
  5817. if (intersect && !element.inRange(position.x, position.y)) {
  5818. return;
  5819. }
  5820. var center = element.getCenterPoint();
  5821. var distance = distanceMetric(position, center);
  5822. if (distance < minDistance) {
  5823. nearestItems = [element];
  5824. minDistance = distance;
  5825. } else if (distance === minDistance) {
  5826. // Can have multiple items at the same distance in which case we sort by size
  5827. nearestItems.push(element);
  5828. }
  5829. });
  5830. return nearestItems;
  5831. }
  5832. /**
  5833. * Get a distance metric function for two points based on the
  5834. * axis mode setting
  5835. * @param {string} axis - the axis mode. x|y|xy
  5836. */
  5837. function getDistanceMetricForAxis(axis) {
  5838. var useX = axis.indexOf('x') !== -1;
  5839. var useY = axis.indexOf('y') !== -1;
  5840. return function(pt1, pt2) {
  5841. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  5842. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  5843. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  5844. };
  5845. }
  5846. function indexMode(chart, e, options) {
  5847. var position = getRelativePosition(e, chart);
  5848. // Default axis for index mode is 'x' to match old behaviour
  5849. options.axis = options.axis || 'x';
  5850. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5851. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5852. var elements = [];
  5853. if (!items.length) {
  5854. return [];
  5855. }
  5856. chart._getSortedVisibleDatasetMetas().forEach(function(meta) {
  5857. var element = meta.data[items[0]._index];
  5858. // don't count items that are skipped (null data)
  5859. if (element && !element._view.skip) {
  5860. elements.push(element);
  5861. }
  5862. });
  5863. return elements;
  5864. }
  5865. /**
  5866. * @interface IInteractionOptions
  5867. */
  5868. /**
  5869. * If true, only consider items that intersect the point
  5870. * @name IInterfaceOptions#boolean
  5871. * @type Boolean
  5872. */
  5873. /**
  5874. * Contains interaction related functions
  5875. * @namespace Chart.Interaction
  5876. */
  5877. var core_interaction = {
  5878. // Helper function for different modes
  5879. modes: {
  5880. single: function(chart, e) {
  5881. var position = getRelativePosition(e, chart);
  5882. var elements = [];
  5883. parseVisibleItems(chart, function(element) {
  5884. if (element.inRange(position.x, position.y)) {
  5885. elements.push(element);
  5886. return elements;
  5887. }
  5888. });
  5889. return elements.slice(0, 1);
  5890. },
  5891. /**
  5892. * @function Chart.Interaction.modes.label
  5893. * @deprecated since version 2.4.0
  5894. * @todo remove at version 3
  5895. * @private
  5896. */
  5897. label: indexMode,
  5898. /**
  5899. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  5900. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  5901. * @function Chart.Interaction.modes.index
  5902. * @since v2.4.0
  5903. * @param {Chart} chart - the chart we are returning items from
  5904. * @param {Event} e - the event we are find things at
  5905. * @param {IInteractionOptions} options - options to use during interaction
  5906. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5907. */
  5908. index: indexMode,
  5909. /**
  5910. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  5911. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  5912. * @function Chart.Interaction.modes.dataset
  5913. * @param {Chart} chart - the chart we are returning items from
  5914. * @param {Event} e - the event we are find things at
  5915. * @param {IInteractionOptions} options - options to use during interaction
  5916. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5917. */
  5918. dataset: function(chart, e, options) {
  5919. var position = getRelativePosition(e, chart);
  5920. options.axis = options.axis || 'xy';
  5921. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5922. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5923. if (items.length > 0) {
  5924. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  5925. }
  5926. return items;
  5927. },
  5928. /**
  5929. * @function Chart.Interaction.modes.x-axis
  5930. * @deprecated since version 2.4.0. Use index mode and intersect == true
  5931. * @todo remove at version 3
  5932. * @private
  5933. */
  5934. 'x-axis': function(chart, e) {
  5935. return indexMode(chart, e, {intersect: false});
  5936. },
  5937. /**
  5938. * Point mode returns all elements that hit test based on the event position
  5939. * of the event
  5940. * @function Chart.Interaction.modes.intersect
  5941. * @param {Chart} chart - the chart we are returning items from
  5942. * @param {Event} e - the event we are find things at
  5943. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5944. */
  5945. point: function(chart, e) {
  5946. var position = getRelativePosition(e, chart);
  5947. return getIntersectItems(chart, position);
  5948. },
  5949. /**
  5950. * nearest mode returns the element closest to the point
  5951. * @function Chart.Interaction.modes.intersect
  5952. * @param {Chart} chart - the chart we are returning items from
  5953. * @param {Event} e - the event we are find things at
  5954. * @param {IInteractionOptions} options - options to use
  5955. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5956. */
  5957. nearest: function(chart, e, options) {
  5958. var position = getRelativePosition(e, chart);
  5959. options.axis = options.axis || 'xy';
  5960. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5961. return getNearestItems(chart, position, options.intersect, distanceMetric);
  5962. },
  5963. /**
  5964. * x mode returns the elements that hit-test at the current x coordinate
  5965. * @function Chart.Interaction.modes.x
  5966. * @param {Chart} chart - the chart we are returning items from
  5967. * @param {Event} e - the event we are find things at
  5968. * @param {IInteractionOptions} options - options to use
  5969. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5970. */
  5971. x: function(chart, e, options) {
  5972. var position = getRelativePosition(e, chart);
  5973. var items = [];
  5974. var intersectsItem = false;
  5975. parseVisibleItems(chart, function(element) {
  5976. if (element.inXRange(position.x)) {
  5977. items.push(element);
  5978. }
  5979. if (element.inRange(position.x, position.y)) {
  5980. intersectsItem = true;
  5981. }
  5982. });
  5983. // If we want to trigger on an intersect and we don't have any items
  5984. // that intersect the position, return nothing
  5985. if (options.intersect && !intersectsItem) {
  5986. items = [];
  5987. }
  5988. return items;
  5989. },
  5990. /**
  5991. * y mode returns the elements that hit-test at the current y coordinate
  5992. * @function Chart.Interaction.modes.y
  5993. * @param {Chart} chart - the chart we are returning items from
  5994. * @param {Event} e - the event we are find things at
  5995. * @param {IInteractionOptions} options - options to use
  5996. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5997. */
  5998. y: function(chart, e, options) {
  5999. var position = getRelativePosition(e, chart);
  6000. var items = [];
  6001. var intersectsItem = false;
  6002. parseVisibleItems(chart, function(element) {
  6003. if (element.inYRange(position.y)) {
  6004. items.push(element);
  6005. }
  6006. if (element.inRange(position.x, position.y)) {
  6007. intersectsItem = true;
  6008. }
  6009. });
  6010. // If we want to trigger on an intersect and we don't have any items
  6011. // that intersect the position, return nothing
  6012. if (options.intersect && !intersectsItem) {
  6013. items = [];
  6014. }
  6015. return items;
  6016. }
  6017. }
  6018. };
  6019. var extend = helpers$1.extend;
  6020. function filterByPosition(array, position) {
  6021. return helpers$1.where(array, function(v) {
  6022. return v.pos === position;
  6023. });
  6024. }
  6025. function sortByWeight(array, reverse) {
  6026. return array.sort(function(a, b) {
  6027. var v0 = reverse ? b : a;
  6028. var v1 = reverse ? a : b;
  6029. return v0.weight === v1.weight ?
  6030. v0.index - v1.index :
  6031. v0.weight - v1.weight;
  6032. });
  6033. }
  6034. function wrapBoxes(boxes) {
  6035. var layoutBoxes = [];
  6036. var i, ilen, box;
  6037. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  6038. box = boxes[i];
  6039. layoutBoxes.push({
  6040. index: i,
  6041. box: box,
  6042. pos: box.position,
  6043. horizontal: box.isHorizontal(),
  6044. weight: box.weight
  6045. });
  6046. }
  6047. return layoutBoxes;
  6048. }
  6049. function setLayoutDims(layouts, params) {
  6050. var i, ilen, layout;
  6051. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  6052. layout = layouts[i];
  6053. // store width used instead of chartArea.w in fitBoxes
  6054. layout.width = layout.horizontal
  6055. ? layout.box.fullWidth && params.availableWidth
  6056. : params.vBoxMaxWidth;
  6057. // store height used instead of chartArea.h in fitBoxes
  6058. layout.height = layout.horizontal && params.hBoxMaxHeight;
  6059. }
  6060. }
  6061. function buildLayoutBoxes(boxes) {
  6062. var layoutBoxes = wrapBoxes(boxes);
  6063. var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  6064. var right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  6065. var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  6066. var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  6067. return {
  6068. leftAndTop: left.concat(top),
  6069. rightAndBottom: right.concat(bottom),
  6070. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  6071. vertical: left.concat(right),
  6072. horizontal: top.concat(bottom)
  6073. };
  6074. }
  6075. function getCombinedMax(maxPadding, chartArea, a, b) {
  6076. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  6077. }
  6078. function updateDims(chartArea, params, layout) {
  6079. var box = layout.box;
  6080. var maxPadding = chartArea.maxPadding;
  6081. var newWidth, newHeight;
  6082. if (layout.size) {
  6083. // this layout was already counted for, lets first reduce old size
  6084. chartArea[layout.pos] -= layout.size;
  6085. }
  6086. layout.size = layout.horizontal ? box.height : box.width;
  6087. chartArea[layout.pos] += layout.size;
  6088. if (box.getPadding) {
  6089. var boxPadding = box.getPadding();
  6090. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  6091. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  6092. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  6093. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  6094. }
  6095. newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right');
  6096. newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom');
  6097. if (newWidth !== chartArea.w || newHeight !== chartArea.h) {
  6098. chartArea.w = newWidth;
  6099. chartArea.h = newHeight;
  6100. // return true if chart area changed in layout's direction
  6101. var sizes = layout.horizontal ? [newWidth, chartArea.w] : [newHeight, chartArea.h];
  6102. return sizes[0] !== sizes[1] && (!isNaN(sizes[0]) || !isNaN(sizes[1]));
  6103. }
  6104. }
  6105. function handleMaxPadding(chartArea) {
  6106. var maxPadding = chartArea.maxPadding;
  6107. function updatePos(pos) {
  6108. var change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  6109. chartArea[pos] += change;
  6110. return change;
  6111. }
  6112. chartArea.y += updatePos('top');
  6113. chartArea.x += updatePos('left');
  6114. updatePos('right');
  6115. updatePos('bottom');
  6116. }
  6117. function getMargins(horizontal, chartArea) {
  6118. var maxPadding = chartArea.maxPadding;
  6119. function marginForPositions(positions) {
  6120. var margin = {left: 0, top: 0, right: 0, bottom: 0};
  6121. positions.forEach(function(pos) {
  6122. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  6123. });
  6124. return margin;
  6125. }
  6126. return horizontal
  6127. ? marginForPositions(['left', 'right'])
  6128. : marginForPositions(['top', 'bottom']);
  6129. }
  6130. function fitBoxes(boxes, chartArea, params) {
  6131. var refitBoxes = [];
  6132. var i, ilen, layout, box, refit, changed;
  6133. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6134. layout = boxes[i];
  6135. box = layout.box;
  6136. box.update(
  6137. layout.width || chartArea.w,
  6138. layout.height || chartArea.h,
  6139. getMargins(layout.horizontal, chartArea)
  6140. );
  6141. if (updateDims(chartArea, params, layout)) {
  6142. changed = true;
  6143. if (refitBoxes.length) {
  6144. // Dimensions changed and there were non full width boxes before this
  6145. // -> we have to refit those
  6146. refit = true;
  6147. }
  6148. }
  6149. if (!box.fullWidth) { // fullWidth boxes don't need to be re-fitted in any case
  6150. refitBoxes.push(layout);
  6151. }
  6152. }
  6153. return refit ? fitBoxes(refitBoxes, chartArea, params) || changed : changed;
  6154. }
  6155. function placeBoxes(boxes, chartArea, params) {
  6156. var userPadding = params.padding;
  6157. var x = chartArea.x;
  6158. var y = chartArea.y;
  6159. var i, ilen, layout, box;
  6160. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6161. layout = boxes[i];
  6162. box = layout.box;
  6163. if (layout.horizontal) {
  6164. box.left = box.fullWidth ? userPadding.left : chartArea.left;
  6165. box.right = box.fullWidth ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;
  6166. box.top = y;
  6167. box.bottom = y + box.height;
  6168. box.width = box.right - box.left;
  6169. y = box.bottom;
  6170. } else {
  6171. box.left = x;
  6172. box.right = x + box.width;
  6173. box.top = chartArea.top;
  6174. box.bottom = chartArea.top + chartArea.h;
  6175. box.height = box.bottom - box.top;
  6176. x = box.right;
  6177. }
  6178. }
  6179. chartArea.x = x;
  6180. chartArea.y = y;
  6181. }
  6182. core_defaults._set('global', {
  6183. layout: {
  6184. padding: {
  6185. top: 0,
  6186. right: 0,
  6187. bottom: 0,
  6188. left: 0
  6189. }
  6190. }
  6191. });
  6192. /**
  6193. * @interface ILayoutItem
  6194. * @prop {string} position - The position of the item in the chart layout. Possible values are
  6195. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  6196. * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  6197. * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  6198. * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  6199. * @prop {function} update - Takes two parameters: width and height. Returns size of item
  6200. * @prop {function} getPadding - Returns an object with padding on the edges
  6201. * @prop {number} width - Width of item. Must be valid after update()
  6202. * @prop {number} height - Height of item. Must be valid after update()
  6203. * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
  6204. * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
  6205. * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
  6206. * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  6207. */
  6208. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  6209. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  6210. // It is this service's responsibility of carrying out that layout.
  6211. var core_layouts = {
  6212. defaults: {},
  6213. /**
  6214. * Register a box to a chart.
  6215. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  6216. * @param {Chart} chart - the chart to use
  6217. * @param {ILayoutItem} item - the item to add to be layed out
  6218. */
  6219. addBox: function(chart, item) {
  6220. if (!chart.boxes) {
  6221. chart.boxes = [];
  6222. }
  6223. // initialize item with default values
  6224. item.fullWidth = item.fullWidth || false;
  6225. item.position = item.position || 'top';
  6226. item.weight = item.weight || 0;
  6227. item._layers = item._layers || function() {
  6228. return [{
  6229. z: 0,
  6230. draw: function() {
  6231. item.draw.apply(item, arguments);
  6232. }
  6233. }];
  6234. };
  6235. chart.boxes.push(item);
  6236. },
  6237. /**
  6238. * Remove a layoutItem from a chart
  6239. * @param {Chart} chart - the chart to remove the box from
  6240. * @param {ILayoutItem} layoutItem - the item to remove from the layout
  6241. */
  6242. removeBox: function(chart, layoutItem) {
  6243. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  6244. if (index !== -1) {
  6245. chart.boxes.splice(index, 1);
  6246. }
  6247. },
  6248. /**
  6249. * Sets (or updates) options on the given `item`.
  6250. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  6251. * @param {ILayoutItem} item - the item to configure with the given options
  6252. * @param {object} options - the new item options.
  6253. */
  6254. configure: function(chart, item, options) {
  6255. var props = ['fullWidth', 'position', 'weight'];
  6256. var ilen = props.length;
  6257. var i = 0;
  6258. var prop;
  6259. for (; i < ilen; ++i) {
  6260. prop = props[i];
  6261. if (options.hasOwnProperty(prop)) {
  6262. item[prop] = options[prop];
  6263. }
  6264. }
  6265. },
  6266. /**
  6267. * Fits boxes of the given chart into the given size by having each box measure itself
  6268. * then running a fitting algorithm
  6269. * @param {Chart} chart - the chart
  6270. * @param {number} width - the width to fit into
  6271. * @param {number} height - the height to fit into
  6272. */
  6273. update: function(chart, width, height) {
  6274. if (!chart) {
  6275. return;
  6276. }
  6277. var layoutOptions = chart.options.layout || {};
  6278. var padding = helpers$1.options.toPadding(layoutOptions.padding);
  6279. var availableWidth = width - padding.width;
  6280. var availableHeight = height - padding.height;
  6281. var boxes = buildLayoutBoxes(chart.boxes);
  6282. var verticalBoxes = boxes.vertical;
  6283. var horizontalBoxes = boxes.horizontal;
  6284. // Essentially we now have any number of boxes on each of the 4 sides.
  6285. // Our canvas looks like the following.
  6286. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  6287. // B1 is the bottom axis
  6288. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  6289. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  6290. // an error will be thrown.
  6291. //
  6292. // |----------------------------------------------------|
  6293. // | T1 (Full Width) |
  6294. // |----------------------------------------------------|
  6295. // | | | T2 | |
  6296. // | |----|-------------------------------------|----|
  6297. // | | | C1 | | C2 | |
  6298. // | | |----| |----| |
  6299. // | | | | |
  6300. // | L1 | L2 | ChartArea (C0) | R1 |
  6301. // | | | | |
  6302. // | | |----| |----| |
  6303. // | | | C3 | | C4 | |
  6304. // | |----|-------------------------------------|----|
  6305. // | | | B1 | |
  6306. // |----------------------------------------------------|
  6307. // | B2 (Full Width) |
  6308. // |----------------------------------------------------|
  6309. //
  6310. var params = Object.freeze({
  6311. outerWidth: width,
  6312. outerHeight: height,
  6313. padding: padding,
  6314. availableWidth: availableWidth,
  6315. vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length,
  6316. hBoxMaxHeight: availableHeight / 2
  6317. });
  6318. var chartArea = extend({
  6319. maxPadding: extend({}, padding),
  6320. w: availableWidth,
  6321. h: availableHeight,
  6322. x: padding.left,
  6323. y: padding.top
  6324. }, padding);
  6325. setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  6326. // First fit vertical boxes
  6327. fitBoxes(verticalBoxes, chartArea, params);
  6328. // Then fit horizontal boxes
  6329. if (fitBoxes(horizontalBoxes, chartArea, params)) {
  6330. // if the area changed, re-fit vertical boxes
  6331. fitBoxes(verticalBoxes, chartArea, params);
  6332. }
  6333. handleMaxPadding(chartArea);
  6334. // Finally place the boxes to correct coordinates
  6335. placeBoxes(boxes.leftAndTop, chartArea, params);
  6336. // Move to opposite side of chart
  6337. chartArea.x += chartArea.w;
  6338. chartArea.y += chartArea.h;
  6339. placeBoxes(boxes.rightAndBottom, chartArea, params);
  6340. chart.chartArea = {
  6341. left: chartArea.left,
  6342. top: chartArea.top,
  6343. right: chartArea.left + chartArea.w,
  6344. bottom: chartArea.top + chartArea.h
  6345. };
  6346. // Finally update boxes in chartArea (radial scale for example)
  6347. helpers$1.each(boxes.chartArea, function(layout) {
  6348. var box = layout.box;
  6349. extend(box, chart.chartArea);
  6350. box.update(chartArea.w, chartArea.h);
  6351. });
  6352. }
  6353. };
  6354. /**
  6355. * Platform fallback implementation (minimal).
  6356. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  6357. */
  6358. var platform_basic = {
  6359. acquireContext: function(item) {
  6360. if (item && item.canvas) {
  6361. // Support for any object associated to a canvas (including a context2d)
  6362. item = item.canvas;
  6363. }
  6364. return item && item.getContext('2d') || null;
  6365. }
  6366. };
  6367. 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";
  6368. var platform_dom$1 = /*#__PURE__*/Object.freeze({
  6369. __proto__: null,
  6370. 'default': platform_dom
  6371. });
  6372. var stylesheet = getCjsExportFromNamespace(platform_dom$1);
  6373. var EXPANDO_KEY = '$chartjs';
  6374. var CSS_PREFIX = 'chartjs-';
  6375. var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';
  6376. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  6377. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  6378. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  6379. /**
  6380. * DOM event types -> Chart.js event types.
  6381. * Note: only events with different types are mapped.
  6382. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  6383. */
  6384. var EVENT_TYPES = {
  6385. touchstart: 'mousedown',
  6386. touchmove: 'mousemove',
  6387. touchend: 'mouseup',
  6388. pointerenter: 'mouseenter',
  6389. pointerdown: 'mousedown',
  6390. pointermove: 'mousemove',
  6391. pointerup: 'mouseup',
  6392. pointerleave: 'mouseout',
  6393. pointerout: 'mouseout'
  6394. };
  6395. /**
  6396. * The "used" size is the final value of a dimension property after all calculations have
  6397. * been performed. This method uses the computed style of `element` but returns undefined
  6398. * if the computed style is not expressed in pixels. That can happen in some cases where
  6399. * `element` has a size relative to its parent and this last one is not yet displayed,
  6400. * for example because of `display: none` on a parent node.
  6401. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  6402. * @returns {number} Size in pixels or undefined if unknown.
  6403. */
  6404. function readUsedSize(element, property) {
  6405. var value = helpers$1.getStyle(element, property);
  6406. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  6407. return matches ? Number(matches[1]) : undefined;
  6408. }
  6409. /**
  6410. * Initializes the canvas style and render size without modifying the canvas display size,
  6411. * since responsiveness is handled by the controller.resize() method. The config is used
  6412. * to determine the aspect ratio to apply in case no explicit height has been specified.
  6413. */
  6414. function initCanvas(canvas, config) {
  6415. var style = canvas.style;
  6416. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  6417. // returns null or '' if no explicit value has been set to the canvas attribute.
  6418. var renderHeight = canvas.getAttribute('height');
  6419. var renderWidth = canvas.getAttribute('width');
  6420. // Chart.js modifies some canvas values that we want to restore on destroy
  6421. canvas[EXPANDO_KEY] = {
  6422. initial: {
  6423. height: renderHeight,
  6424. width: renderWidth,
  6425. style: {
  6426. display: style.display,
  6427. height: style.height,
  6428. width: style.width
  6429. }
  6430. }
  6431. };
  6432. // Force canvas to display as block to avoid extra space caused by inline
  6433. // elements, which would interfere with the responsive resize process.
  6434. // https://github.com/chartjs/Chart.js/issues/2538
  6435. style.display = style.display || 'block';
  6436. if (renderWidth === null || renderWidth === '') {
  6437. var displayWidth = readUsedSize(canvas, 'width');
  6438. if (displayWidth !== undefined) {
  6439. canvas.width = displayWidth;
  6440. }
  6441. }
  6442. if (renderHeight === null || renderHeight === '') {
  6443. if (canvas.style.height === '') {
  6444. // If no explicit render height and style height, let's apply the aspect ratio,
  6445. // which one can be specified by the user but also by charts as default option
  6446. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  6447. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  6448. } else {
  6449. var displayHeight = readUsedSize(canvas, 'height');
  6450. if (displayWidth !== undefined) {
  6451. canvas.height = displayHeight;
  6452. }
  6453. }
  6454. }
  6455. return canvas;
  6456. }
  6457. /**
  6458. * Detects support for options object argument in addEventListener.
  6459. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  6460. * @private
  6461. */
  6462. var supportsEventListenerOptions = (function() {
  6463. var supports = false;
  6464. try {
  6465. var options = Object.defineProperty({}, 'passive', {
  6466. // eslint-disable-next-line getter-return
  6467. get: function() {
  6468. supports = true;
  6469. }
  6470. });
  6471. window.addEventListener('e', null, options);
  6472. } catch (e) {
  6473. // continue regardless of error
  6474. }
  6475. return supports;
  6476. }());
  6477. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  6478. // https://github.com/chartjs/Chart.js/issues/4287
  6479. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  6480. function addListener(node, type, listener) {
  6481. node.addEventListener(type, listener, eventListenerOptions);
  6482. }
  6483. function removeListener(node, type, listener) {
  6484. node.removeEventListener(type, listener, eventListenerOptions);
  6485. }
  6486. function createEvent(type, chart, x, y, nativeEvent) {
  6487. return {
  6488. type: type,
  6489. chart: chart,
  6490. native: nativeEvent || null,
  6491. x: x !== undefined ? x : null,
  6492. y: y !== undefined ? y : null,
  6493. };
  6494. }
  6495. function fromNativeEvent(event, chart) {
  6496. var type = EVENT_TYPES[event.type] || event.type;
  6497. var pos = helpers$1.getRelativePosition(event, chart);
  6498. return createEvent(type, chart, pos.x, pos.y, event);
  6499. }
  6500. function throttled(fn, thisArg) {
  6501. var ticking = false;
  6502. var args = [];
  6503. return function() {
  6504. args = Array.prototype.slice.call(arguments);
  6505. thisArg = thisArg || this;
  6506. if (!ticking) {
  6507. ticking = true;
  6508. helpers$1.requestAnimFrame.call(window, function() {
  6509. ticking = false;
  6510. fn.apply(thisArg, args);
  6511. });
  6512. }
  6513. };
  6514. }
  6515. function createDiv(cls) {
  6516. var el = document.createElement('div');
  6517. el.className = cls || '';
  6518. return el;
  6519. }
  6520. // Implementation based on https://github.com/marcj/css-element-queries
  6521. function createResizer(handler) {
  6522. var maxSize = 1000000;
  6523. // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
  6524. // https://github.com/chartjs/Chart.js/issues/5902
  6525. var resizer = createDiv(CSS_SIZE_MONITOR);
  6526. var expand = createDiv(CSS_SIZE_MONITOR + '-expand');
  6527. var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');
  6528. expand.appendChild(createDiv());
  6529. shrink.appendChild(createDiv());
  6530. resizer.appendChild(expand);
  6531. resizer.appendChild(shrink);
  6532. resizer._reset = function() {
  6533. expand.scrollLeft = maxSize;
  6534. expand.scrollTop = maxSize;
  6535. shrink.scrollLeft = maxSize;
  6536. shrink.scrollTop = maxSize;
  6537. };
  6538. var onScroll = function() {
  6539. resizer._reset();
  6540. handler();
  6541. };
  6542. addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  6543. addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  6544. return resizer;
  6545. }
  6546. // https://davidwalsh.name/detect-node-insertion
  6547. function watchForRender(node, handler) {
  6548. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6549. var proxy = expando.renderProxy = function(e) {
  6550. if (e.animationName === CSS_RENDER_ANIMATION) {
  6551. handler();
  6552. }
  6553. };
  6554. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  6555. addListener(node, type, proxy);
  6556. });
  6557. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  6558. // is removed then added back immediately (same animation frame?). Accessing the
  6559. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  6560. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  6561. // https://github.com/chartjs/Chart.js/issues/4737
  6562. expando.reflow = !!node.offsetParent;
  6563. node.classList.add(CSS_RENDER_MONITOR);
  6564. }
  6565. function unwatchForRender(node) {
  6566. var expando = node[EXPANDO_KEY] || {};
  6567. var proxy = expando.renderProxy;
  6568. if (proxy) {
  6569. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  6570. removeListener(node, type, proxy);
  6571. });
  6572. delete expando.renderProxy;
  6573. }
  6574. node.classList.remove(CSS_RENDER_MONITOR);
  6575. }
  6576. function addResizeListener(node, listener, chart) {
  6577. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6578. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  6579. var resizer = expando.resizer = createResizer(throttled(function() {
  6580. if (expando.resizer) {
  6581. var container = chart.options.maintainAspectRatio && node.parentNode;
  6582. var w = container ? container.clientWidth : 0;
  6583. listener(createEvent('resize', chart));
  6584. if (container && container.clientWidth < w && chart.canvas) {
  6585. // If the container size shrank during chart resize, let's assume
  6586. // scrollbar appeared. So we resize again with the scrollbar visible -
  6587. // effectively making chart smaller and the scrollbar hidden again.
  6588. // Because we are inside `throttled`, and currently `ticking`, scroll
  6589. // events are ignored during this whole 2 resize process.
  6590. // If we assumed wrong and something else happened, we are resizing
  6591. // twice in a frame (potential performance issue)
  6592. listener(createEvent('resize', chart));
  6593. }
  6594. }
  6595. }));
  6596. // The resizer needs to be attached to the node parent, so we first need to be
  6597. // sure that `node` is attached to the DOM before injecting the resizer element.
  6598. watchForRender(node, function() {
  6599. if (expando.resizer) {
  6600. var container = node.parentNode;
  6601. if (container && container !== resizer.parentNode) {
  6602. container.insertBefore(resizer, container.firstChild);
  6603. }
  6604. // The container size might have changed, let's reset the resizer state.
  6605. resizer._reset();
  6606. }
  6607. });
  6608. }
  6609. function removeResizeListener(node) {
  6610. var expando = node[EXPANDO_KEY] || {};
  6611. var resizer = expando.resizer;
  6612. delete expando.resizer;
  6613. unwatchForRender(node);
  6614. if (resizer && resizer.parentNode) {
  6615. resizer.parentNode.removeChild(resizer);
  6616. }
  6617. }
  6618. /**
  6619. * Injects CSS styles inline if the styles are not already present.
  6620. * @param {HTMLDocument|ShadowRoot} rootNode - the node to contain the <style>.
  6621. * @param {string} css - the CSS to be injected.
  6622. */
  6623. function injectCSS(rootNode, css) {
  6624. // https://stackoverflow.com/q/3922139
  6625. var expando = rootNode[EXPANDO_KEY] || (rootNode[EXPANDO_KEY] = {});
  6626. if (!expando.containsStyles) {
  6627. expando.containsStyles = true;
  6628. css = '/* Chart.js */\n' + css;
  6629. var style = document.createElement('style');
  6630. style.setAttribute('type', 'text/css');
  6631. style.appendChild(document.createTextNode(css));
  6632. rootNode.appendChild(style);
  6633. }
  6634. }
  6635. var platform_dom$2 = {
  6636. /**
  6637. * When `true`, prevents the automatic injection of the stylesheet required to
  6638. * correctly detect when the chart is added to the DOM and then resized. This
  6639. * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)
  6640. * to be manually imported to make this library compatible with any CSP.
  6641. * See https://github.com/chartjs/Chart.js/issues/5208
  6642. */
  6643. disableCSSInjection: false,
  6644. /**
  6645. * This property holds whether this platform is enabled for the current environment.
  6646. * Currently used by platform.js to select the proper implementation.
  6647. * @private
  6648. */
  6649. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  6650. /**
  6651. * Initializes resources that depend on platform options.
  6652. * @param {HTMLCanvasElement} canvas - The Canvas element.
  6653. * @private
  6654. */
  6655. _ensureLoaded: function(canvas) {
  6656. if (!this.disableCSSInjection) {
  6657. // If the canvas is in a shadow DOM, then the styles must also be inserted
  6658. // into the same shadow DOM.
  6659. // https://github.com/chartjs/Chart.js/issues/5763
  6660. var root = canvas.getRootNode ? canvas.getRootNode() : document;
  6661. var targetNode = root.host ? root : document.head;
  6662. injectCSS(targetNode, stylesheet);
  6663. }
  6664. },
  6665. acquireContext: function(item, config) {
  6666. if (typeof item === 'string') {
  6667. item = document.getElementById(item);
  6668. } else if (item.length) {
  6669. // Support for array based queries (such as jQuery)
  6670. item = item[0];
  6671. }
  6672. if (item && item.canvas) {
  6673. // Support for any object associated to a canvas (including a context2d)
  6674. item = item.canvas;
  6675. }
  6676. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  6677. // method, for example: https://github.com/kkapsner/CanvasBlocker
  6678. // https://github.com/chartjs/Chart.js/issues/2807
  6679. var context = item && item.getContext && item.getContext('2d');
  6680. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  6681. // inside an iframe or when running in a protected environment. We could guess the
  6682. // types from their toString() value but let's keep things flexible and assume it's
  6683. // a sufficient condition if the item has a context2D which has item as `canvas`.
  6684. // https://github.com/chartjs/Chart.js/issues/3887
  6685. // https://github.com/chartjs/Chart.js/issues/4102
  6686. // https://github.com/chartjs/Chart.js/issues/4152
  6687. if (context && context.canvas === item) {
  6688. // Load platform resources on first chart creation, to make it possible to
  6689. // import the library before setting platform options.
  6690. this._ensureLoaded(item);
  6691. initCanvas(item, config);
  6692. return context;
  6693. }
  6694. return null;
  6695. },
  6696. releaseContext: function(context) {
  6697. var canvas = context.canvas;
  6698. if (!canvas[EXPANDO_KEY]) {
  6699. return;
  6700. }
  6701. var initial = canvas[EXPANDO_KEY].initial;
  6702. ['height', 'width'].forEach(function(prop) {
  6703. var value = initial[prop];
  6704. if (helpers$1.isNullOrUndef(value)) {
  6705. canvas.removeAttribute(prop);
  6706. } else {
  6707. canvas.setAttribute(prop, value);
  6708. }
  6709. });
  6710. helpers$1.each(initial.style || {}, function(value, key) {
  6711. canvas.style[key] = value;
  6712. });
  6713. // The canvas render size might have been changed (and thus the state stack discarded),
  6714. // we can't use save() and restore() to restore the initial state. So make sure that at
  6715. // least the canvas context is reset to the default state by setting the canvas width.
  6716. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  6717. // eslint-disable-next-line no-self-assign
  6718. canvas.width = canvas.width;
  6719. delete canvas[EXPANDO_KEY];
  6720. },
  6721. addEventListener: function(chart, type, listener) {
  6722. var canvas = chart.canvas;
  6723. if (type === 'resize') {
  6724. // Note: the resize event is not supported on all browsers.
  6725. addResizeListener(canvas, listener, chart);
  6726. return;
  6727. }
  6728. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  6729. var proxies = expando.proxies || (expando.proxies = {});
  6730. var proxy = proxies[chart.id + '_' + type] = function(event) {
  6731. listener(fromNativeEvent(event, chart));
  6732. };
  6733. addListener(canvas, type, proxy);
  6734. },
  6735. removeEventListener: function(chart, type, listener) {
  6736. var canvas = chart.canvas;
  6737. if (type === 'resize') {
  6738. // Note: the resize event is not supported on all browsers.
  6739. removeResizeListener(canvas);
  6740. return;
  6741. }
  6742. var expando = listener[EXPANDO_KEY] || {};
  6743. var proxies = expando.proxies || {};
  6744. var proxy = proxies[chart.id + '_' + type];
  6745. if (!proxy) {
  6746. return;
  6747. }
  6748. removeListener(canvas, type, proxy);
  6749. }
  6750. };
  6751. // DEPRECATIONS
  6752. /**
  6753. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  6754. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6755. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  6756. * @function Chart.helpers.addEvent
  6757. * @deprecated since version 2.7.0
  6758. * @todo remove at version 3
  6759. * @private
  6760. */
  6761. helpers$1.addEvent = addListener;
  6762. /**
  6763. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  6764. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6765. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  6766. * @function Chart.helpers.removeEvent
  6767. * @deprecated since version 2.7.0
  6768. * @todo remove at version 3
  6769. * @private
  6770. */
  6771. helpers$1.removeEvent = removeListener;
  6772. // @TODO Make possible to select another platform at build time.
  6773. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;
  6774. /**
  6775. * @namespace Chart.platform
  6776. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  6777. * @since 2.4.0
  6778. */
  6779. var platform = helpers$1.extend({
  6780. /**
  6781. * @since 2.7.0
  6782. */
  6783. initialize: function() {},
  6784. /**
  6785. * Called at chart construction time, returns a context2d instance implementing
  6786. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  6787. * @param {*} item - The native item from which to acquire context (platform specific)
  6788. * @param {object} options - The chart options
  6789. * @returns {CanvasRenderingContext2D} context2d instance
  6790. */
  6791. acquireContext: function() {},
  6792. /**
  6793. * Called at chart destruction time, releases any resources associated to the context
  6794. * previously returned by the acquireContext() method.
  6795. * @param {CanvasRenderingContext2D} context - The context2d instance
  6796. * @returns {boolean} true if the method succeeded, else false
  6797. */
  6798. releaseContext: function() {},
  6799. /**
  6800. * Registers the specified listener on the given chart.
  6801. * @param {Chart} chart - Chart from which to listen for event
  6802. * @param {string} type - The ({@link IEvent}) type to listen for
  6803. * @param {function} listener - Receives a notification (an object that implements
  6804. * the {@link IEvent} interface) when an event of the specified type occurs.
  6805. */
  6806. addEventListener: function() {},
  6807. /**
  6808. * Removes the specified listener previously registered with addEventListener.
  6809. * @param {Chart} chart - Chart from which to remove the listener
  6810. * @param {string} type - The ({@link IEvent}) type to remove
  6811. * @param {function} listener - The listener function to remove from the event target.
  6812. */
  6813. removeEventListener: function() {}
  6814. }, implementation);
  6815. core_defaults._set('global', {
  6816. plugins: {}
  6817. });
  6818. /**
  6819. * The plugin service singleton
  6820. * @namespace Chart.plugins
  6821. * @since 2.1.0
  6822. */
  6823. var core_plugins = {
  6824. /**
  6825. * Globally registered plugins.
  6826. * @private
  6827. */
  6828. _plugins: [],
  6829. /**
  6830. * This identifier is used to invalidate the descriptors cache attached to each chart
  6831. * when a global plugin is registered or unregistered. In this case, the cache ID is
  6832. * incremented and descriptors are regenerated during following API calls.
  6833. * @private
  6834. */
  6835. _cacheId: 0,
  6836. /**
  6837. * Registers the given plugin(s) if not already registered.
  6838. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6839. */
  6840. register: function(plugins) {
  6841. var p = this._plugins;
  6842. ([]).concat(plugins).forEach(function(plugin) {
  6843. if (p.indexOf(plugin) === -1) {
  6844. p.push(plugin);
  6845. }
  6846. });
  6847. this._cacheId++;
  6848. },
  6849. /**
  6850. * Unregisters the given plugin(s) only if registered.
  6851. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6852. */
  6853. unregister: function(plugins) {
  6854. var p = this._plugins;
  6855. ([]).concat(plugins).forEach(function(plugin) {
  6856. var idx = p.indexOf(plugin);
  6857. if (idx !== -1) {
  6858. p.splice(idx, 1);
  6859. }
  6860. });
  6861. this._cacheId++;
  6862. },
  6863. /**
  6864. * Remove all registered plugins.
  6865. * @since 2.1.5
  6866. */
  6867. clear: function() {
  6868. this._plugins = [];
  6869. this._cacheId++;
  6870. },
  6871. /**
  6872. * Returns the number of registered plugins?
  6873. * @returns {number}
  6874. * @since 2.1.5
  6875. */
  6876. count: function() {
  6877. return this._plugins.length;
  6878. },
  6879. /**
  6880. * Returns all registered plugin instances.
  6881. * @returns {IPlugin[]} array of plugin objects.
  6882. * @since 2.1.5
  6883. */
  6884. getAll: function() {
  6885. return this._plugins;
  6886. },
  6887. /**
  6888. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  6889. * This method immediately returns as soon as a plugin explicitly returns false. The
  6890. * returned value can be used, for instance, to interrupt the current action.
  6891. * @param {Chart} chart - The chart instance for which plugins should be called.
  6892. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  6893. * @param {Array} [args] - Extra arguments to apply to the hook call.
  6894. * @returns {boolean} false if any of the plugins return false, else returns true.
  6895. */
  6896. notify: function(chart, hook, args) {
  6897. var descriptors = this.descriptors(chart);
  6898. var ilen = descriptors.length;
  6899. var i, descriptor, plugin, params, method;
  6900. for (i = 0; i < ilen; ++i) {
  6901. descriptor = descriptors[i];
  6902. plugin = descriptor.plugin;
  6903. method = plugin[hook];
  6904. if (typeof method === 'function') {
  6905. params = [chart].concat(args || []);
  6906. params.push(descriptor.options);
  6907. if (method.apply(plugin, params) === false) {
  6908. return false;
  6909. }
  6910. }
  6911. }
  6912. return true;
  6913. },
  6914. /**
  6915. * Returns descriptors of enabled plugins for the given chart.
  6916. * @returns {object[]} [{ plugin, options }]
  6917. * @private
  6918. */
  6919. descriptors: function(chart) {
  6920. var cache = chart.$plugins || (chart.$plugins = {});
  6921. if (cache.id === this._cacheId) {
  6922. return cache.descriptors;
  6923. }
  6924. var plugins = [];
  6925. var descriptors = [];
  6926. var config = (chart && chart.config) || {};
  6927. var options = (config.options && config.options.plugins) || {};
  6928. this._plugins.concat(config.plugins || []).forEach(function(plugin) {
  6929. var idx = plugins.indexOf(plugin);
  6930. if (idx !== -1) {
  6931. return;
  6932. }
  6933. var id = plugin.id;
  6934. var opts = options[id];
  6935. if (opts === false) {
  6936. return;
  6937. }
  6938. if (opts === true) {
  6939. opts = helpers$1.clone(core_defaults.global.plugins[id]);
  6940. }
  6941. plugins.push(plugin);
  6942. descriptors.push({
  6943. plugin: plugin,
  6944. options: opts || {}
  6945. });
  6946. });
  6947. cache.descriptors = descriptors;
  6948. cache.id = this._cacheId;
  6949. return descriptors;
  6950. },
  6951. /**
  6952. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  6953. * but in some cases, this reference can be changed by the user when updating options.
  6954. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  6955. * @private
  6956. */
  6957. _invalidate: function(chart) {
  6958. delete chart.$plugins;
  6959. }
  6960. };
  6961. var core_scaleService = {
  6962. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  6963. // use the new chart options to grab the correct scale
  6964. constructors: {},
  6965. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  6966. // old browsers
  6967. // Scale config defaults
  6968. defaults: {},
  6969. registerScaleType: function(type, scaleConstructor, scaleDefaults) {
  6970. this.constructors[type] = scaleConstructor;
  6971. this.defaults[type] = helpers$1.clone(scaleDefaults);
  6972. },
  6973. getScaleConstructor: function(type) {
  6974. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  6975. },
  6976. getScaleDefaults: function(type) {
  6977. // Return the scale defaults merged with the global settings so that we always use the latest ones
  6978. return this.defaults.hasOwnProperty(type) ? helpers$1.merge(Object.create(null), [core_defaults.scale, this.defaults[type]]) : {};
  6979. },
  6980. updateScaleDefaults: function(type, additions) {
  6981. var me = this;
  6982. if (me.defaults.hasOwnProperty(type)) {
  6983. me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
  6984. }
  6985. },
  6986. addScalesToLayout: function(chart) {
  6987. // Adds each scale to the chart.boxes array to be sized accordingly
  6988. helpers$1.each(chart.scales, function(scale) {
  6989. // Set ILayoutItem parameters for backwards compatibility
  6990. scale.fullWidth = scale.options.fullWidth;
  6991. scale.position = scale.options.position;
  6992. scale.weight = scale.options.weight;
  6993. core_layouts.addBox(chart, scale);
  6994. });
  6995. }
  6996. };
  6997. var valueOrDefault$8 = helpers$1.valueOrDefault;
  6998. var getRtlHelper = helpers$1.rtl.getRtlAdapter;
  6999. core_defaults._set('global', {
  7000. tooltips: {
  7001. enabled: true,
  7002. custom: null,
  7003. mode: 'nearest',
  7004. position: 'average',
  7005. intersect: true,
  7006. backgroundColor: 'rgba(0,0,0,0.8)',
  7007. titleFontStyle: 'bold',
  7008. titleSpacing: 2,
  7009. titleMarginBottom: 6,
  7010. titleFontColor: '#fff',
  7011. titleAlign: 'left',
  7012. bodySpacing: 2,
  7013. bodyFontColor: '#fff',
  7014. bodyAlign: 'left',
  7015. footerFontStyle: 'bold',
  7016. footerSpacing: 2,
  7017. footerMarginTop: 6,
  7018. footerFontColor: '#fff',
  7019. footerAlign: 'left',
  7020. yPadding: 6,
  7021. xPadding: 6,
  7022. caretPadding: 2,
  7023. caretSize: 5,
  7024. cornerRadius: 6,
  7025. multiKeyBackground: '#fff',
  7026. displayColors: true,
  7027. borderColor: 'rgba(0,0,0,0)',
  7028. borderWidth: 0,
  7029. callbacks: {
  7030. // Args are: (tooltipItems, data)
  7031. beforeTitle: helpers$1.noop,
  7032. title: function(tooltipItems, data) {
  7033. var title = '';
  7034. var labels = data.labels;
  7035. var labelCount = labels ? labels.length : 0;
  7036. if (tooltipItems.length > 0) {
  7037. var item = tooltipItems[0];
  7038. if (item.label) {
  7039. title = item.label;
  7040. } else if (item.xLabel) {
  7041. title = item.xLabel;
  7042. } else if (labelCount > 0 && item.index < labelCount) {
  7043. title = labels[item.index];
  7044. }
  7045. }
  7046. return title;
  7047. },
  7048. afterTitle: helpers$1.noop,
  7049. // Args are: (tooltipItems, data)
  7050. beforeBody: helpers$1.noop,
  7051. // Args are: (tooltipItem, data)
  7052. beforeLabel: helpers$1.noop,
  7053. label: function(tooltipItem, data) {
  7054. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  7055. if (label) {
  7056. label += ': ';
  7057. }
  7058. if (!helpers$1.isNullOrUndef(tooltipItem.value)) {
  7059. label += tooltipItem.value;
  7060. } else {
  7061. label += tooltipItem.yLabel;
  7062. }
  7063. return label;
  7064. },
  7065. labelColor: function(tooltipItem, chart) {
  7066. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  7067. var activeElement = meta.data[tooltipItem.index];
  7068. var view = activeElement._view;
  7069. return {
  7070. borderColor: view.borderColor,
  7071. backgroundColor: view.backgroundColor
  7072. };
  7073. },
  7074. labelTextColor: function() {
  7075. return this._options.bodyFontColor;
  7076. },
  7077. afterLabel: helpers$1.noop,
  7078. // Args are: (tooltipItems, data)
  7079. afterBody: helpers$1.noop,
  7080. // Args are: (tooltipItems, data)
  7081. beforeFooter: helpers$1.noop,
  7082. footer: helpers$1.noop,
  7083. afterFooter: helpers$1.noop
  7084. }
  7085. }
  7086. });
  7087. var positioners = {
  7088. /**
  7089. * Average mode places the tooltip at the average position of the elements shown
  7090. * @function Chart.Tooltip.positioners.average
  7091. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  7092. * @returns {object} tooltip position
  7093. */
  7094. average: function(elements) {
  7095. if (!elements.length) {
  7096. return false;
  7097. }
  7098. var i, len;
  7099. var x = 0;
  7100. var y = 0;
  7101. var count = 0;
  7102. for (i = 0, len = elements.length; i < len; ++i) {
  7103. var el = elements[i];
  7104. if (el && el.hasValue()) {
  7105. var pos = el.tooltipPosition();
  7106. x += pos.x;
  7107. y += pos.y;
  7108. ++count;
  7109. }
  7110. }
  7111. return {
  7112. x: x / count,
  7113. y: y / count
  7114. };
  7115. },
  7116. /**
  7117. * Gets the tooltip position nearest of the item nearest to the event position
  7118. * @function Chart.Tooltip.positioners.nearest
  7119. * @param elements {Chart.Element[]} the tooltip elements
  7120. * @param eventPosition {object} the position of the event in canvas coordinates
  7121. * @returns {object} the tooltip position
  7122. */
  7123. nearest: function(elements, eventPosition) {
  7124. var x = eventPosition.x;
  7125. var y = eventPosition.y;
  7126. var minDistance = Number.POSITIVE_INFINITY;
  7127. var i, len, nearestElement;
  7128. for (i = 0, len = elements.length; i < len; ++i) {
  7129. var el = elements[i];
  7130. if (el && el.hasValue()) {
  7131. var center = el.getCenterPoint();
  7132. var d = helpers$1.distanceBetweenPoints(eventPosition, center);
  7133. if (d < minDistance) {
  7134. minDistance = d;
  7135. nearestElement = el;
  7136. }
  7137. }
  7138. }
  7139. if (nearestElement) {
  7140. var tp = nearestElement.tooltipPosition();
  7141. x = tp.x;
  7142. y = tp.y;
  7143. }
  7144. return {
  7145. x: x,
  7146. y: y
  7147. };
  7148. }
  7149. };
  7150. // Helper to push or concat based on if the 2nd parameter is an array or not
  7151. function pushOrConcat(base, toPush) {
  7152. if (toPush) {
  7153. if (helpers$1.isArray(toPush)) {
  7154. // base = base.concat(toPush);
  7155. Array.prototype.push.apply(base, toPush);
  7156. } else {
  7157. base.push(toPush);
  7158. }
  7159. }
  7160. return base;
  7161. }
  7162. /**
  7163. * Returns array of strings split by newline
  7164. * @param {string} value - The value to split by newline.
  7165. * @returns {string[]} value if newline present - Returned from String split() method
  7166. * @function
  7167. */
  7168. function splitNewlines(str) {
  7169. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  7170. return str.split('\n');
  7171. }
  7172. return str;
  7173. }
  7174. /**
  7175. * Private helper to create a tooltip item model
  7176. * @param element - the chart element (point, arc, bar) to create the tooltip item for
  7177. * @return new tooltip item
  7178. */
  7179. function createTooltipItem(element) {
  7180. var xScale = element._xScale;
  7181. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  7182. var index = element._index;
  7183. var datasetIndex = element._datasetIndex;
  7184. var controller = element._chart.getDatasetMeta(datasetIndex).controller;
  7185. var indexScale = controller._getIndexScale();
  7186. var valueScale = controller._getValueScale();
  7187. return {
  7188. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  7189. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  7190. label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',
  7191. value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',
  7192. index: index,
  7193. datasetIndex: datasetIndex,
  7194. x: element._model.x,
  7195. y: element._model.y
  7196. };
  7197. }
  7198. /**
  7199. * Helper to get the reset model for the tooltip
  7200. * @param tooltipOpts {object} the tooltip options
  7201. */
  7202. function getBaseModel(tooltipOpts) {
  7203. var globalDefaults = core_defaults.global;
  7204. return {
  7205. // Positioning
  7206. xPadding: tooltipOpts.xPadding,
  7207. yPadding: tooltipOpts.yPadding,
  7208. xAlign: tooltipOpts.xAlign,
  7209. yAlign: tooltipOpts.yAlign,
  7210. // Drawing direction and text direction
  7211. rtl: tooltipOpts.rtl,
  7212. textDirection: tooltipOpts.textDirection,
  7213. // Body
  7214. bodyFontColor: tooltipOpts.bodyFontColor,
  7215. _bodyFontFamily: valueOrDefault$8(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  7216. _bodyFontStyle: valueOrDefault$8(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  7217. _bodyAlign: tooltipOpts.bodyAlign,
  7218. bodyFontSize: valueOrDefault$8(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  7219. bodySpacing: tooltipOpts.bodySpacing,
  7220. // Title
  7221. titleFontColor: tooltipOpts.titleFontColor,
  7222. _titleFontFamily: valueOrDefault$8(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  7223. _titleFontStyle: valueOrDefault$8(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  7224. titleFontSize: valueOrDefault$8(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  7225. _titleAlign: tooltipOpts.titleAlign,
  7226. titleSpacing: tooltipOpts.titleSpacing,
  7227. titleMarginBottom: tooltipOpts.titleMarginBottom,
  7228. // Footer
  7229. footerFontColor: tooltipOpts.footerFontColor,
  7230. _footerFontFamily: valueOrDefault$8(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  7231. _footerFontStyle: valueOrDefault$8(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  7232. footerFontSize: valueOrDefault$8(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  7233. _footerAlign: tooltipOpts.footerAlign,
  7234. footerSpacing: tooltipOpts.footerSpacing,
  7235. footerMarginTop: tooltipOpts.footerMarginTop,
  7236. // Appearance
  7237. caretSize: tooltipOpts.caretSize,
  7238. cornerRadius: tooltipOpts.cornerRadius,
  7239. backgroundColor: tooltipOpts.backgroundColor,
  7240. opacity: 0,
  7241. legendColorBackground: tooltipOpts.multiKeyBackground,
  7242. displayColors: tooltipOpts.displayColors,
  7243. borderColor: tooltipOpts.borderColor,
  7244. borderWidth: tooltipOpts.borderWidth
  7245. };
  7246. }
  7247. /**
  7248. * Get the size of the tooltip
  7249. */
  7250. function getTooltipSize(tooltip, model) {
  7251. var ctx = tooltip._chart.ctx;
  7252. var height = model.yPadding * 2; // Tooltip Padding
  7253. var width = 0;
  7254. // Count of all lines in the body
  7255. var body = model.body;
  7256. var combinedBodyLength = body.reduce(function(count, bodyItem) {
  7257. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  7258. }, 0);
  7259. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  7260. var titleLineCount = model.title.length;
  7261. var footerLineCount = model.footer.length;
  7262. var titleFontSize = model.titleFontSize;
  7263. var bodyFontSize = model.bodyFontSize;
  7264. var footerFontSize = model.footerFontSize;
  7265. height += titleLineCount * titleFontSize; // Title Lines
  7266. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  7267. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  7268. height += combinedBodyLength * bodyFontSize; // Body Lines
  7269. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  7270. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  7271. height += footerLineCount * (footerFontSize); // Footer Lines
  7272. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  7273. // Title width
  7274. var widthPadding = 0;
  7275. var maxLineWidth = function(line) {
  7276. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  7277. };
  7278. ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  7279. helpers$1.each(model.title, maxLineWidth);
  7280. // Body width
  7281. ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  7282. helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  7283. // Body lines may include some extra width due to the color box
  7284. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  7285. helpers$1.each(body, function(bodyItem) {
  7286. helpers$1.each(bodyItem.before, maxLineWidth);
  7287. helpers$1.each(bodyItem.lines, maxLineWidth);
  7288. helpers$1.each(bodyItem.after, maxLineWidth);
  7289. });
  7290. // Reset back to 0
  7291. widthPadding = 0;
  7292. // Footer width
  7293. ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  7294. helpers$1.each(model.footer, maxLineWidth);
  7295. // Add padding
  7296. width += 2 * model.xPadding;
  7297. return {
  7298. width: width,
  7299. height: height
  7300. };
  7301. }
  7302. /**
  7303. * Helper to get the alignment of a tooltip given the size
  7304. */
  7305. function determineAlignment(tooltip, size) {
  7306. var model = tooltip._model;
  7307. var chart = tooltip._chart;
  7308. var chartArea = tooltip._chart.chartArea;
  7309. var xAlign = 'center';
  7310. var yAlign = 'center';
  7311. if (model.y < size.height) {
  7312. yAlign = 'top';
  7313. } else if (model.y > (chart.height - size.height)) {
  7314. yAlign = 'bottom';
  7315. }
  7316. var lf, rf; // functions to determine left, right alignment
  7317. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  7318. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  7319. var midX = (chartArea.left + chartArea.right) / 2;
  7320. var midY = (chartArea.top + chartArea.bottom) / 2;
  7321. if (yAlign === 'center') {
  7322. lf = function(x) {
  7323. return x <= midX;
  7324. };
  7325. rf = function(x) {
  7326. return x > midX;
  7327. };
  7328. } else {
  7329. lf = function(x) {
  7330. return x <= (size.width / 2);
  7331. };
  7332. rf = function(x) {
  7333. return x >= (chart.width - (size.width / 2));
  7334. };
  7335. }
  7336. olf = function(x) {
  7337. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  7338. };
  7339. orf = function(x) {
  7340. return x - size.width - model.caretSize - model.caretPadding < 0;
  7341. };
  7342. yf = function(y) {
  7343. return y <= midY ? 'top' : 'bottom';
  7344. };
  7345. if (lf(model.x)) {
  7346. xAlign = 'left';
  7347. // Is tooltip too wide and goes over the right side of the chart.?
  7348. if (olf(model.x)) {
  7349. xAlign = 'center';
  7350. yAlign = yf(model.y);
  7351. }
  7352. } else if (rf(model.x)) {
  7353. xAlign = 'right';
  7354. // Is tooltip too wide and goes outside left edge of canvas?
  7355. if (orf(model.x)) {
  7356. xAlign = 'center';
  7357. yAlign = yf(model.y);
  7358. }
  7359. }
  7360. var opts = tooltip._options;
  7361. return {
  7362. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  7363. yAlign: opts.yAlign ? opts.yAlign : yAlign
  7364. };
  7365. }
  7366. /**
  7367. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  7368. */
  7369. function getBackgroundPoint(vm, size, alignment, chart) {
  7370. // Background Position
  7371. var x = vm.x;
  7372. var y = vm.y;
  7373. var caretSize = vm.caretSize;
  7374. var caretPadding = vm.caretPadding;
  7375. var cornerRadius = vm.cornerRadius;
  7376. var xAlign = alignment.xAlign;
  7377. var yAlign = alignment.yAlign;
  7378. var paddingAndSize = caretSize + caretPadding;
  7379. var radiusAndPadding = cornerRadius + caretPadding;
  7380. if (xAlign === 'right') {
  7381. x -= size.width;
  7382. } else if (xAlign === 'center') {
  7383. x -= (size.width / 2);
  7384. if (x + size.width > chart.width) {
  7385. x = chart.width - size.width;
  7386. }
  7387. if (x < 0) {
  7388. x = 0;
  7389. }
  7390. }
  7391. if (yAlign === 'top') {
  7392. y += paddingAndSize;
  7393. } else if (yAlign === 'bottom') {
  7394. y -= size.height + paddingAndSize;
  7395. } else {
  7396. y -= (size.height / 2);
  7397. }
  7398. if (yAlign === 'center') {
  7399. if (xAlign === 'left') {
  7400. x += paddingAndSize;
  7401. } else if (xAlign === 'right') {
  7402. x -= paddingAndSize;
  7403. }
  7404. } else if (xAlign === 'left') {
  7405. x -= radiusAndPadding;
  7406. } else if (xAlign === 'right') {
  7407. x += radiusAndPadding;
  7408. }
  7409. return {
  7410. x: x,
  7411. y: y
  7412. };
  7413. }
  7414. function getAlignedX(vm, align) {
  7415. return align === 'center'
  7416. ? vm.x + vm.width / 2
  7417. : align === 'right'
  7418. ? vm.x + vm.width - vm.xPadding
  7419. : vm.x + vm.xPadding;
  7420. }
  7421. /**
  7422. * Helper to build before and after body lines
  7423. */
  7424. function getBeforeAfterBodyLines(callback) {
  7425. return pushOrConcat([], splitNewlines(callback));
  7426. }
  7427. var exports$4 = core_element.extend({
  7428. initialize: function() {
  7429. this._model = getBaseModel(this._options);
  7430. this._lastActive = [];
  7431. },
  7432. // Get the title
  7433. // Args are: (tooltipItem, data)
  7434. getTitle: function() {
  7435. var me = this;
  7436. var opts = me._options;
  7437. var callbacks = opts.callbacks;
  7438. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  7439. var title = callbacks.title.apply(me, arguments);
  7440. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  7441. var lines = [];
  7442. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  7443. lines = pushOrConcat(lines, splitNewlines(title));
  7444. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  7445. return lines;
  7446. },
  7447. // Args are: (tooltipItem, data)
  7448. getBeforeBody: function() {
  7449. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  7450. },
  7451. // Args are: (tooltipItem, data)
  7452. getBody: function(tooltipItems, data) {
  7453. var me = this;
  7454. var callbacks = me._options.callbacks;
  7455. var bodyItems = [];
  7456. helpers$1.each(tooltipItems, function(tooltipItem) {
  7457. var bodyItem = {
  7458. before: [],
  7459. lines: [],
  7460. after: []
  7461. };
  7462. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  7463. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  7464. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  7465. bodyItems.push(bodyItem);
  7466. });
  7467. return bodyItems;
  7468. },
  7469. // Args are: (tooltipItem, data)
  7470. getAfterBody: function() {
  7471. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  7472. },
  7473. // Get the footer and beforeFooter and afterFooter lines
  7474. // Args are: (tooltipItem, data)
  7475. getFooter: function() {
  7476. var me = this;
  7477. var callbacks = me._options.callbacks;
  7478. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  7479. var footer = callbacks.footer.apply(me, arguments);
  7480. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  7481. var lines = [];
  7482. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  7483. lines = pushOrConcat(lines, splitNewlines(footer));
  7484. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  7485. return lines;
  7486. },
  7487. update: function(changed) {
  7488. var me = this;
  7489. var opts = me._options;
  7490. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  7491. // 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
  7492. // which breaks any animations.
  7493. var existingModel = me._model;
  7494. var model = me._model = getBaseModel(opts);
  7495. var active = me._active;
  7496. var data = me._data;
  7497. // In the case where active.length === 0 we need to keep these at existing values for good animations
  7498. var alignment = {
  7499. xAlign: existingModel.xAlign,
  7500. yAlign: existingModel.yAlign
  7501. };
  7502. var backgroundPoint = {
  7503. x: existingModel.x,
  7504. y: existingModel.y
  7505. };
  7506. var tooltipSize = {
  7507. width: existingModel.width,
  7508. height: existingModel.height
  7509. };
  7510. var tooltipPosition = {
  7511. x: existingModel.caretX,
  7512. y: existingModel.caretY
  7513. };
  7514. var i, len;
  7515. if (active.length) {
  7516. model.opacity = 1;
  7517. var labelColors = [];
  7518. var labelTextColors = [];
  7519. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  7520. var tooltipItems = [];
  7521. for (i = 0, len = active.length; i < len; ++i) {
  7522. tooltipItems.push(createTooltipItem(active[i]));
  7523. }
  7524. // If the user provided a filter function, use it to modify the tooltip items
  7525. if (opts.filter) {
  7526. tooltipItems = tooltipItems.filter(function(a) {
  7527. return opts.filter(a, data);
  7528. });
  7529. }
  7530. // If the user provided a sorting function, use it to modify the tooltip items
  7531. if (opts.itemSort) {
  7532. tooltipItems = tooltipItems.sort(function(a, b) {
  7533. return opts.itemSort(a, b, data);
  7534. });
  7535. }
  7536. // Determine colors for boxes
  7537. helpers$1.each(tooltipItems, function(tooltipItem) {
  7538. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  7539. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  7540. });
  7541. // Build the Text Lines
  7542. model.title = me.getTitle(tooltipItems, data);
  7543. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  7544. model.body = me.getBody(tooltipItems, data);
  7545. model.afterBody = me.getAfterBody(tooltipItems, data);
  7546. model.footer = me.getFooter(tooltipItems, data);
  7547. // Initial positioning and colors
  7548. model.x = tooltipPosition.x;
  7549. model.y = tooltipPosition.y;
  7550. model.caretPadding = opts.caretPadding;
  7551. model.labelColors = labelColors;
  7552. model.labelTextColors = labelTextColors;
  7553. // data points
  7554. model.dataPoints = tooltipItems;
  7555. // We need to determine alignment of the tooltip
  7556. tooltipSize = getTooltipSize(this, model);
  7557. alignment = determineAlignment(this, tooltipSize);
  7558. // Final Size and Position
  7559. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  7560. } else {
  7561. model.opacity = 0;
  7562. }
  7563. model.xAlign = alignment.xAlign;
  7564. model.yAlign = alignment.yAlign;
  7565. model.x = backgroundPoint.x;
  7566. model.y = backgroundPoint.y;
  7567. model.width = tooltipSize.width;
  7568. model.height = tooltipSize.height;
  7569. // Point where the caret on the tooltip points to
  7570. model.caretX = tooltipPosition.x;
  7571. model.caretY = tooltipPosition.y;
  7572. me._model = model;
  7573. if (changed && opts.custom) {
  7574. opts.custom.call(me, model);
  7575. }
  7576. return me;
  7577. },
  7578. drawCaret: function(tooltipPoint, size) {
  7579. var ctx = this._chart.ctx;
  7580. var vm = this._view;
  7581. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  7582. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  7583. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  7584. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  7585. },
  7586. getCaretPosition: function(tooltipPoint, size, vm) {
  7587. var x1, x2, x3, y1, y2, y3;
  7588. var caretSize = vm.caretSize;
  7589. var cornerRadius = vm.cornerRadius;
  7590. var xAlign = vm.xAlign;
  7591. var yAlign = vm.yAlign;
  7592. var ptX = tooltipPoint.x;
  7593. var ptY = tooltipPoint.y;
  7594. var width = size.width;
  7595. var height = size.height;
  7596. if (yAlign === 'center') {
  7597. y2 = ptY + (height / 2);
  7598. if (xAlign === 'left') {
  7599. x1 = ptX;
  7600. x2 = x1 - caretSize;
  7601. x3 = x1;
  7602. y1 = y2 + caretSize;
  7603. y3 = y2 - caretSize;
  7604. } else {
  7605. x1 = ptX + width;
  7606. x2 = x1 + caretSize;
  7607. x3 = x1;
  7608. y1 = y2 - caretSize;
  7609. y3 = y2 + caretSize;
  7610. }
  7611. } else {
  7612. if (xAlign === 'left') {
  7613. x2 = ptX + cornerRadius + (caretSize);
  7614. x1 = x2 - caretSize;
  7615. x3 = x2 + caretSize;
  7616. } else if (xAlign === 'right') {
  7617. x2 = ptX + width - cornerRadius - caretSize;
  7618. x1 = x2 - caretSize;
  7619. x3 = x2 + caretSize;
  7620. } else {
  7621. x2 = vm.caretX;
  7622. x1 = x2 - caretSize;
  7623. x3 = x2 + caretSize;
  7624. }
  7625. if (yAlign === 'top') {
  7626. y1 = ptY;
  7627. y2 = y1 - caretSize;
  7628. y3 = y1;
  7629. } else {
  7630. y1 = ptY + height;
  7631. y2 = y1 + caretSize;
  7632. y3 = y1;
  7633. // invert drawing order
  7634. var tmp = x3;
  7635. x3 = x1;
  7636. x1 = tmp;
  7637. }
  7638. }
  7639. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  7640. },
  7641. drawTitle: function(pt, vm, ctx) {
  7642. var title = vm.title;
  7643. var length = title.length;
  7644. var titleFontSize, titleSpacing, i;
  7645. if (length) {
  7646. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7647. pt.x = getAlignedX(vm, vm._titleAlign);
  7648. ctx.textAlign = rtlHelper.textAlign(vm._titleAlign);
  7649. ctx.textBaseline = 'middle';
  7650. titleFontSize = vm.titleFontSize;
  7651. titleSpacing = vm.titleSpacing;
  7652. ctx.fillStyle = vm.titleFontColor;
  7653. ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  7654. for (i = 0; i < length; ++i) {
  7655. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFontSize / 2);
  7656. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  7657. if (i + 1 === length) {
  7658. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  7659. }
  7660. }
  7661. }
  7662. },
  7663. drawBody: function(pt, vm, ctx) {
  7664. var bodyFontSize = vm.bodyFontSize;
  7665. var bodySpacing = vm.bodySpacing;
  7666. var bodyAlign = vm._bodyAlign;
  7667. var body = vm.body;
  7668. var drawColorBoxes = vm.displayColors;
  7669. var xLinePadding = 0;
  7670. var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
  7671. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7672. var fillLineOfText = function(line) {
  7673. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyFontSize / 2);
  7674. pt.y += bodyFontSize + bodySpacing;
  7675. };
  7676. var bodyItem, textColor, labelColors, lines, i, j, ilen, jlen;
  7677. var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  7678. ctx.textAlign = bodyAlign;
  7679. ctx.textBaseline = 'middle';
  7680. ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  7681. pt.x = getAlignedX(vm, bodyAlignForCalculation);
  7682. // Before body lines
  7683. ctx.fillStyle = vm.bodyFontColor;
  7684. helpers$1.each(vm.beforeBody, fillLineOfText);
  7685. xLinePadding = drawColorBoxes && bodyAlignForCalculation !== 'right'
  7686. ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
  7687. : 0;
  7688. // Draw body lines now
  7689. for (i = 0, ilen = body.length; i < ilen; ++i) {
  7690. bodyItem = body[i];
  7691. textColor = vm.labelTextColors[i];
  7692. labelColors = vm.labelColors[i];
  7693. ctx.fillStyle = textColor;
  7694. helpers$1.each(bodyItem.before, fillLineOfText);
  7695. lines = bodyItem.lines;
  7696. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  7697. // Draw Legend-like boxes if needed
  7698. if (drawColorBoxes) {
  7699. var rtlColorX = rtlHelper.x(colorX);
  7700. // Fill a white rect so that colours merge nicely if the opacity is < 1
  7701. ctx.fillStyle = vm.legendColorBackground;
  7702. ctx.fillRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7703. // Border
  7704. ctx.lineWidth = 1;
  7705. ctx.strokeStyle = labelColors.borderColor;
  7706. ctx.strokeRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7707. // Inner square
  7708. ctx.fillStyle = labelColors.backgroundColor;
  7709. ctx.fillRect(rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), bodyFontSize - 2), pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  7710. ctx.fillStyle = textColor;
  7711. }
  7712. fillLineOfText(lines[j]);
  7713. }
  7714. helpers$1.each(bodyItem.after, fillLineOfText);
  7715. }
  7716. // Reset back to 0 for after body
  7717. xLinePadding = 0;
  7718. // After body lines
  7719. helpers$1.each(vm.afterBody, fillLineOfText);
  7720. pt.y -= bodySpacing; // Remove last body spacing
  7721. },
  7722. drawFooter: function(pt, vm, ctx) {
  7723. var footer = vm.footer;
  7724. var length = footer.length;
  7725. var footerFontSize, i;
  7726. if (length) {
  7727. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7728. pt.x = getAlignedX(vm, vm._footerAlign);
  7729. pt.y += vm.footerMarginTop;
  7730. ctx.textAlign = rtlHelper.textAlign(vm._footerAlign);
  7731. ctx.textBaseline = 'middle';
  7732. footerFontSize = vm.footerFontSize;
  7733. ctx.fillStyle = vm.footerFontColor;
  7734. ctx.font = helpers$1.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  7735. for (i = 0; i < length; ++i) {
  7736. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFontSize / 2);
  7737. pt.y += footerFontSize + vm.footerSpacing;
  7738. }
  7739. }
  7740. },
  7741. drawBackground: function(pt, vm, ctx, tooltipSize) {
  7742. ctx.fillStyle = vm.backgroundColor;
  7743. ctx.strokeStyle = vm.borderColor;
  7744. ctx.lineWidth = vm.borderWidth;
  7745. var xAlign = vm.xAlign;
  7746. var yAlign = vm.yAlign;
  7747. var x = pt.x;
  7748. var y = pt.y;
  7749. var width = tooltipSize.width;
  7750. var height = tooltipSize.height;
  7751. var radius = vm.cornerRadius;
  7752. ctx.beginPath();
  7753. ctx.moveTo(x + radius, y);
  7754. if (yAlign === 'top') {
  7755. this.drawCaret(pt, tooltipSize);
  7756. }
  7757. ctx.lineTo(x + width - radius, y);
  7758. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  7759. if (yAlign === 'center' && xAlign === 'right') {
  7760. this.drawCaret(pt, tooltipSize);
  7761. }
  7762. ctx.lineTo(x + width, y + height - radius);
  7763. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  7764. if (yAlign === 'bottom') {
  7765. this.drawCaret(pt, tooltipSize);
  7766. }
  7767. ctx.lineTo(x + radius, y + height);
  7768. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  7769. if (yAlign === 'center' && xAlign === 'left') {
  7770. this.drawCaret(pt, tooltipSize);
  7771. }
  7772. ctx.lineTo(x, y + radius);
  7773. ctx.quadraticCurveTo(x, y, x + radius, y);
  7774. ctx.closePath();
  7775. ctx.fill();
  7776. if (vm.borderWidth > 0) {
  7777. ctx.stroke();
  7778. }
  7779. },
  7780. draw: function() {
  7781. var ctx = this._chart.ctx;
  7782. var vm = this._view;
  7783. if (vm.opacity === 0) {
  7784. return;
  7785. }
  7786. var tooltipSize = {
  7787. width: vm.width,
  7788. height: vm.height
  7789. };
  7790. var pt = {
  7791. x: vm.x,
  7792. y: vm.y
  7793. };
  7794. // IE11/Edge does not like very small opacities, so snap to 0
  7795. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  7796. // Truthy/falsey value for empty tooltip
  7797. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  7798. if (this._options.enabled && hasTooltipContent) {
  7799. ctx.save();
  7800. ctx.globalAlpha = opacity;
  7801. // Draw Background
  7802. this.drawBackground(pt, vm, ctx, tooltipSize);
  7803. // Draw Title, Body, and Footer
  7804. pt.y += vm.yPadding;
  7805. helpers$1.rtl.overrideTextDirection(ctx, vm.textDirection);
  7806. // Titles
  7807. this.drawTitle(pt, vm, ctx);
  7808. // Body
  7809. this.drawBody(pt, vm, ctx);
  7810. // Footer
  7811. this.drawFooter(pt, vm, ctx);
  7812. helpers$1.rtl.restoreTextDirection(ctx, vm.textDirection);
  7813. ctx.restore();
  7814. }
  7815. },
  7816. /**
  7817. * Handle an event
  7818. * @private
  7819. * @param {IEvent} event - The event to handle
  7820. * @returns {boolean} true if the tooltip changed
  7821. */
  7822. handleEvent: function(e) {
  7823. var me = this;
  7824. var options = me._options;
  7825. var changed = false;
  7826. me._lastActive = me._lastActive || [];
  7827. // Find Active Elements for tooltips
  7828. if (e.type === 'mouseout') {
  7829. me._active = [];
  7830. } else {
  7831. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  7832. if (options.reverse) {
  7833. me._active.reverse();
  7834. }
  7835. }
  7836. // Remember Last Actives
  7837. changed = !helpers$1.arrayEquals(me._active, me._lastActive);
  7838. // Only handle target event on tooltip change
  7839. if (changed) {
  7840. me._lastActive = me._active;
  7841. if (options.enabled || options.custom) {
  7842. me._eventPosition = {
  7843. x: e.x,
  7844. y: e.y
  7845. };
  7846. me.update(true);
  7847. me.pivot();
  7848. }
  7849. }
  7850. return changed;
  7851. }
  7852. });
  7853. /**
  7854. * @namespace Chart.Tooltip.positioners
  7855. */
  7856. var positioners_1 = positioners;
  7857. var core_tooltip = exports$4;
  7858. core_tooltip.positioners = positioners_1;
  7859. var valueOrDefault$9 = helpers$1.valueOrDefault;
  7860. core_defaults._set('global', {
  7861. elements: {},
  7862. events: [
  7863. 'mousemove',
  7864. 'mouseout',
  7865. 'click',
  7866. 'touchstart',
  7867. 'touchmove'
  7868. ],
  7869. hover: {
  7870. onHover: null,
  7871. mode: 'nearest',
  7872. intersect: true,
  7873. animationDuration: 400
  7874. },
  7875. onClick: null,
  7876. maintainAspectRatio: true,
  7877. responsive: true,
  7878. responsiveAnimationDuration: 0
  7879. });
  7880. /**
  7881. * Recursively merge the given config objects representing the `scales` option
  7882. * by incorporating scale defaults in `xAxes` and `yAxes` array items, then
  7883. * returns a deep copy of the result, thus doesn't alter inputs.
  7884. */
  7885. function mergeScaleConfig(/* config objects ... */) {
  7886. return helpers$1.merge(Object.create(null), [].slice.call(arguments), {
  7887. merger: function(key, target, source, options) {
  7888. if (key === 'xAxes' || key === 'yAxes') {
  7889. var slen = source[key].length;
  7890. var i, type, scale;
  7891. if (!target[key]) {
  7892. target[key] = [];
  7893. }
  7894. for (i = 0; i < slen; ++i) {
  7895. scale = source[key][i];
  7896. type = valueOrDefault$9(scale.type, key === 'xAxes' ? 'category' : 'linear');
  7897. if (i >= target[key].length) {
  7898. target[key].push({});
  7899. }
  7900. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  7901. // new/untyped scale or type changed: let's apply the new defaults
  7902. // then merge source scale to correctly overwrite the defaults.
  7903. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
  7904. } else {
  7905. // scales type are the same
  7906. helpers$1.merge(target[key][i], scale);
  7907. }
  7908. }
  7909. } else {
  7910. helpers$1._merger(key, target, source, options);
  7911. }
  7912. }
  7913. });
  7914. }
  7915. /**
  7916. * Recursively merge the given config objects as the root options by handling
  7917. * default scale options for the `scales` and `scale` properties, then returns
  7918. * a deep copy of the result, thus doesn't alter inputs.
  7919. */
  7920. function mergeConfig(/* config objects ... */) {
  7921. return helpers$1.merge(Object.create(null), [].slice.call(arguments), {
  7922. merger: function(key, target, source, options) {
  7923. var tval = target[key] || Object.create(null);
  7924. var sval = source[key];
  7925. if (key === 'scales') {
  7926. // scale config merging is complex. Add our own function here for that
  7927. target[key] = mergeScaleConfig(tval, sval);
  7928. } else if (key === 'scale') {
  7929. // used in polar area & radar charts since there is only one scale
  7930. target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
  7931. } else {
  7932. helpers$1._merger(key, target, source, options);
  7933. }
  7934. }
  7935. });
  7936. }
  7937. function initConfig(config) {
  7938. config = config || Object.create(null);
  7939. // Do NOT use mergeConfig for the data object because this method merges arrays
  7940. // and so would change references to labels and datasets, preventing data updates.
  7941. var data = config.data = config.data || {};
  7942. data.datasets = data.datasets || [];
  7943. data.labels = data.labels || [];
  7944. config.options = mergeConfig(
  7945. core_defaults.global,
  7946. core_defaults[config.type],
  7947. config.options || {});
  7948. return config;
  7949. }
  7950. function updateConfig(chart) {
  7951. var newOptions = chart.options;
  7952. helpers$1.each(chart.scales, function(scale) {
  7953. core_layouts.removeBox(chart, scale);
  7954. });
  7955. newOptions = mergeConfig(
  7956. core_defaults.global,
  7957. core_defaults[chart.config.type],
  7958. newOptions);
  7959. chart.options = chart.config.options = newOptions;
  7960. chart.ensureScalesHaveIDs();
  7961. chart.buildOrUpdateScales();
  7962. // Tooltip
  7963. chart.tooltip._options = newOptions.tooltips;
  7964. chart.tooltip.initialize();
  7965. }
  7966. function nextAvailableScaleId(axesOpts, prefix, index) {
  7967. var id;
  7968. var hasId = function(obj) {
  7969. return obj.id === id;
  7970. };
  7971. do {
  7972. id = prefix + index++;
  7973. } while (helpers$1.findIndex(axesOpts, hasId) >= 0);
  7974. return id;
  7975. }
  7976. function positionIsHorizontal(position) {
  7977. return position === 'top' || position === 'bottom';
  7978. }
  7979. function compare2Level(l1, l2) {
  7980. return function(a, b) {
  7981. return a[l1] === b[l1]
  7982. ? a[l2] - b[l2]
  7983. : a[l1] - b[l1];
  7984. };
  7985. }
  7986. var Chart = function(item, config) {
  7987. this.construct(item, config);
  7988. return this;
  7989. };
  7990. helpers$1.extend(Chart.prototype, /** @lends Chart */ {
  7991. /**
  7992. * @private
  7993. */
  7994. construct: function(item, config) {
  7995. var me = this;
  7996. config = initConfig(config);
  7997. var context = platform.acquireContext(item, config);
  7998. var canvas = context && context.canvas;
  7999. var height = canvas && canvas.height;
  8000. var width = canvas && canvas.width;
  8001. me.id = helpers$1.uid();
  8002. me.ctx = context;
  8003. me.canvas = canvas;
  8004. me.config = config;
  8005. me.width = width;
  8006. me.height = height;
  8007. me.aspectRatio = height ? width / height : null;
  8008. me.options = config.options;
  8009. me._bufferedRender = false;
  8010. me._layers = [];
  8011. /**
  8012. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  8013. * the "instance" still need to be defined since it might be called from plugins.
  8014. * @prop Chart#chart
  8015. * @deprecated since version 2.6.0
  8016. * @todo remove at version 3
  8017. * @private
  8018. */
  8019. me.chart = me;
  8020. me.controller = me; // chart.chart.controller #inception
  8021. // Add the chart instance to the global namespace
  8022. Chart.instances[me.id] = me;
  8023. // Define alias to the config data: `chart.data === chart.config.data`
  8024. Object.defineProperty(me, 'data', {
  8025. get: function() {
  8026. return me.config.data;
  8027. },
  8028. set: function(value) {
  8029. me.config.data = value;
  8030. }
  8031. });
  8032. if (!context || !canvas) {
  8033. // The given item is not a compatible context2d element, let's return before finalizing
  8034. // the chart initialization but after setting basic chart / controller properties that
  8035. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  8036. // https://github.com/chartjs/Chart.js/issues/2807
  8037. console.error("Failed to create chart: can't acquire context from the given item");
  8038. return;
  8039. }
  8040. me.initialize();
  8041. me.update();
  8042. },
  8043. /**
  8044. * @private
  8045. */
  8046. initialize: function() {
  8047. var me = this;
  8048. // Before init plugin notification
  8049. core_plugins.notify(me, 'beforeInit');
  8050. helpers$1.retinaScale(me, me.options.devicePixelRatio);
  8051. me.bindEvents();
  8052. if (me.options.responsive) {
  8053. // Initial resize before chart draws (must be silent to preserve initial animations).
  8054. me.resize(true);
  8055. }
  8056. me.initToolTip();
  8057. // After init plugin notification
  8058. core_plugins.notify(me, 'afterInit');
  8059. return me;
  8060. },
  8061. clear: function() {
  8062. helpers$1.canvas.clear(this);
  8063. return this;
  8064. },
  8065. stop: function() {
  8066. // Stops any current animation loop occurring
  8067. core_animations.cancelAnimation(this);
  8068. return this;
  8069. },
  8070. resize: function(silent) {
  8071. var me = this;
  8072. var options = me.options;
  8073. var canvas = me.canvas;
  8074. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  8075. // the canvas render width and height will be casted to integers so make sure that
  8076. // the canvas display style uses the same integer values to avoid blurring effect.
  8077. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  8078. var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
  8079. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
  8080. if (me.width === newWidth && me.height === newHeight) {
  8081. return;
  8082. }
  8083. canvas.width = me.width = newWidth;
  8084. canvas.height = me.height = newHeight;
  8085. canvas.style.width = newWidth + 'px';
  8086. canvas.style.height = newHeight + 'px';
  8087. helpers$1.retinaScale(me, options.devicePixelRatio);
  8088. if (!silent) {
  8089. // Notify any plugins about the resize
  8090. var newSize = {width: newWidth, height: newHeight};
  8091. core_plugins.notify(me, 'resize', [newSize]);
  8092. // Notify of resize
  8093. if (options.onResize) {
  8094. options.onResize(me, newSize);
  8095. }
  8096. me.stop();
  8097. me.update({
  8098. duration: options.responsiveAnimationDuration
  8099. });
  8100. }
  8101. },
  8102. ensureScalesHaveIDs: function() {
  8103. var options = this.options;
  8104. var scalesOptions = options.scales || {};
  8105. var scaleOptions = options.scale;
  8106. helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {
  8107. if (!xAxisOptions.id) {
  8108. xAxisOptions.id = nextAvailableScaleId(scalesOptions.xAxes, 'x-axis-', index);
  8109. }
  8110. });
  8111. helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {
  8112. if (!yAxisOptions.id) {
  8113. yAxisOptions.id = nextAvailableScaleId(scalesOptions.yAxes, 'y-axis-', index);
  8114. }
  8115. });
  8116. if (scaleOptions) {
  8117. scaleOptions.id = scaleOptions.id || 'scale';
  8118. }
  8119. },
  8120. /**
  8121. * Builds a map of scale ID to scale object for future lookup.
  8122. */
  8123. buildOrUpdateScales: function() {
  8124. var me = this;
  8125. var options = me.options;
  8126. var scales = me.scales || {};
  8127. var items = [];
  8128. var updated = Object.keys(scales).reduce(function(obj, id) {
  8129. obj[id] = false;
  8130. return obj;
  8131. }, {});
  8132. if (options.scales) {
  8133. items = items.concat(
  8134. (options.scales.xAxes || []).map(function(xAxisOptions) {
  8135. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  8136. }),
  8137. (options.scales.yAxes || []).map(function(yAxisOptions) {
  8138. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  8139. })
  8140. );
  8141. }
  8142. if (options.scale) {
  8143. items.push({
  8144. options: options.scale,
  8145. dtype: 'radialLinear',
  8146. isDefault: true,
  8147. dposition: 'chartArea'
  8148. });
  8149. }
  8150. helpers$1.each(items, function(item) {
  8151. var scaleOptions = item.options;
  8152. var id = scaleOptions.id;
  8153. var scaleType = valueOrDefault$9(scaleOptions.type, item.dtype);
  8154. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  8155. scaleOptions.position = item.dposition;
  8156. }
  8157. updated[id] = true;
  8158. var scale = null;
  8159. if (id in scales && scales[id].type === scaleType) {
  8160. scale = scales[id];
  8161. scale.options = scaleOptions;
  8162. scale.ctx = me.ctx;
  8163. scale.chart = me;
  8164. } else {
  8165. var scaleClass = core_scaleService.getScaleConstructor(scaleType);
  8166. if (!scaleClass) {
  8167. return;
  8168. }
  8169. scale = new scaleClass({
  8170. id: id,
  8171. type: scaleType,
  8172. options: scaleOptions,
  8173. ctx: me.ctx,
  8174. chart: me
  8175. });
  8176. scales[scale.id] = scale;
  8177. }
  8178. scale.mergeTicksOptions();
  8179. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  8180. // and consider it as a regular scale part of the "scales"" map only! This would
  8181. // make the logic easier and remove some useless? custom code.
  8182. if (item.isDefault) {
  8183. me.scale = scale;
  8184. }
  8185. });
  8186. // clear up discarded scales
  8187. helpers$1.each(updated, function(hasUpdated, id) {
  8188. if (!hasUpdated) {
  8189. delete scales[id];
  8190. }
  8191. });
  8192. me.scales = scales;
  8193. core_scaleService.addScalesToLayout(this);
  8194. },
  8195. buildOrUpdateControllers: function() {
  8196. var me = this;
  8197. var newControllers = [];
  8198. var datasets = me.data.datasets;
  8199. var i, ilen;
  8200. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  8201. var dataset = datasets[i];
  8202. var meta = me.getDatasetMeta(i);
  8203. var type = dataset.type || me.config.type;
  8204. if (meta.type && meta.type !== type) {
  8205. me.destroyDatasetMeta(i);
  8206. meta = me.getDatasetMeta(i);
  8207. }
  8208. meta.type = type;
  8209. meta.order = dataset.order || 0;
  8210. meta.index = i;
  8211. if (meta.controller) {
  8212. meta.controller.updateIndex(i);
  8213. meta.controller.linkScales();
  8214. } else {
  8215. var ControllerClass = controllers[meta.type];
  8216. if (ControllerClass === undefined) {
  8217. throw new Error('"' + meta.type + '" is not a chart type.');
  8218. }
  8219. meta.controller = new ControllerClass(me, i);
  8220. newControllers.push(meta.controller);
  8221. }
  8222. }
  8223. return newControllers;
  8224. },
  8225. /**
  8226. * Reset the elements of all datasets
  8227. * @private
  8228. */
  8229. resetElements: function() {
  8230. var me = this;
  8231. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  8232. me.getDatasetMeta(datasetIndex).controller.reset();
  8233. }, me);
  8234. },
  8235. /**
  8236. * Resets the chart back to it's state before the initial animation
  8237. */
  8238. reset: function() {
  8239. this.resetElements();
  8240. this.tooltip.initialize();
  8241. },
  8242. update: function(config) {
  8243. var me = this;
  8244. var i, ilen;
  8245. if (!config || typeof config !== 'object') {
  8246. // backwards compatibility
  8247. config = {
  8248. duration: config,
  8249. lazy: arguments[1]
  8250. };
  8251. }
  8252. updateConfig(me);
  8253. // plugins options references might have change, let's invalidate the cache
  8254. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  8255. core_plugins._invalidate(me);
  8256. if (core_plugins.notify(me, 'beforeUpdate') === false) {
  8257. return;
  8258. }
  8259. // In case the entire data object changed
  8260. me.tooltip._data = me.data;
  8261. // Make sure dataset controllers are updated and new controllers are reset
  8262. var newControllers = me.buildOrUpdateControllers();
  8263. // Make sure all dataset controllers have correct meta data counts
  8264. for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
  8265. me.getDatasetMeta(i).controller.buildOrUpdateElements();
  8266. }
  8267. me.updateLayout();
  8268. // Can only reset the new controllers after the scales have been updated
  8269. if (me.options.animation && me.options.animation.duration) {
  8270. helpers$1.each(newControllers, function(controller) {
  8271. controller.reset();
  8272. });
  8273. }
  8274. me.updateDatasets();
  8275. // Need to reset tooltip in case it is displayed with elements that are removed
  8276. // after update.
  8277. me.tooltip.initialize();
  8278. // Last active contains items that were previously in the tooltip.
  8279. // When we reset the tooltip, we need to clear it
  8280. me.lastActive = [];
  8281. // Do this before render so that any plugins that need final scale updates can use it
  8282. core_plugins.notify(me, 'afterUpdate');
  8283. me._layers.sort(compare2Level('z', '_idx'));
  8284. if (me._bufferedRender) {
  8285. me._bufferedRequest = {
  8286. duration: config.duration,
  8287. easing: config.easing,
  8288. lazy: config.lazy
  8289. };
  8290. } else {
  8291. me.render(config);
  8292. }
  8293. },
  8294. /**
  8295. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  8296. * hook, in which case, plugins will not be called on `afterLayout`.
  8297. * @private
  8298. */
  8299. updateLayout: function() {
  8300. var me = this;
  8301. if (core_plugins.notify(me, 'beforeLayout') === false) {
  8302. return;
  8303. }
  8304. core_layouts.update(this, this.width, this.height);
  8305. me._layers = [];
  8306. helpers$1.each(me.boxes, function(box) {
  8307. // _configure is called twice, once in core.scale.update and once here.
  8308. // Here the boxes are fully updated and at their final positions.
  8309. if (box._configure) {
  8310. box._configure();
  8311. }
  8312. me._layers.push.apply(me._layers, box._layers());
  8313. }, me);
  8314. me._layers.forEach(function(item, index) {
  8315. item._idx = index;
  8316. });
  8317. /**
  8318. * Provided for backward compatibility, use `afterLayout` instead.
  8319. * @method IPlugin#afterScaleUpdate
  8320. * @deprecated since version 2.5.0
  8321. * @todo remove at version 3
  8322. * @private
  8323. */
  8324. core_plugins.notify(me, 'afterScaleUpdate');
  8325. core_plugins.notify(me, 'afterLayout');
  8326. },
  8327. /**
  8328. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  8329. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  8330. * @private
  8331. */
  8332. updateDatasets: function() {
  8333. var me = this;
  8334. if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  8335. return;
  8336. }
  8337. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8338. me.updateDataset(i);
  8339. }
  8340. core_plugins.notify(me, 'afterDatasetsUpdate');
  8341. },
  8342. /**
  8343. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  8344. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  8345. * @private
  8346. */
  8347. updateDataset: function(index) {
  8348. var me = this;
  8349. var meta = me.getDatasetMeta(index);
  8350. var args = {
  8351. meta: meta,
  8352. index: index
  8353. };
  8354. if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  8355. return;
  8356. }
  8357. meta.controller._update();
  8358. core_plugins.notify(me, 'afterDatasetUpdate', [args]);
  8359. },
  8360. render: function(config) {
  8361. var me = this;
  8362. if (!config || typeof config !== 'object') {
  8363. // backwards compatibility
  8364. config = {
  8365. duration: config,
  8366. lazy: arguments[1]
  8367. };
  8368. }
  8369. var animationOptions = me.options.animation;
  8370. var duration = valueOrDefault$9(config.duration, animationOptions && animationOptions.duration);
  8371. var lazy = config.lazy;
  8372. if (core_plugins.notify(me, 'beforeRender') === false) {
  8373. return;
  8374. }
  8375. var onComplete = function(animation) {
  8376. core_plugins.notify(me, 'afterRender');
  8377. helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
  8378. };
  8379. if (animationOptions && duration) {
  8380. var animation = new core_animation({
  8381. numSteps: duration / 16.66, // 60 fps
  8382. easing: config.easing || animationOptions.easing,
  8383. render: function(chart, animationObject) {
  8384. var easingFunction = helpers$1.easing.effects[animationObject.easing];
  8385. var currentStep = animationObject.currentStep;
  8386. var stepDecimal = currentStep / animationObject.numSteps;
  8387. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  8388. },
  8389. onAnimationProgress: animationOptions.onProgress,
  8390. onAnimationComplete: onComplete
  8391. });
  8392. core_animations.addAnimation(me, animation, duration, lazy);
  8393. } else {
  8394. me.draw();
  8395. // See https://github.com/chartjs/Chart.js/issues/3781
  8396. onComplete(new core_animation({numSteps: 0, chart: me}));
  8397. }
  8398. return me;
  8399. },
  8400. draw: function(easingValue) {
  8401. var me = this;
  8402. var i, layers;
  8403. me.clear();
  8404. if (helpers$1.isNullOrUndef(easingValue)) {
  8405. easingValue = 1;
  8406. }
  8407. me.transition(easingValue);
  8408. if (me.width <= 0 || me.height <= 0) {
  8409. return;
  8410. }
  8411. if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  8412. return;
  8413. }
  8414. // Because of plugin hooks (before/afterDatasetsDraw), datasets can't
  8415. // currently be part of layers. Instead, we draw
  8416. // layers <= 0 before(default, backward compat), and the rest after
  8417. layers = me._layers;
  8418. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  8419. layers[i].draw(me.chartArea);
  8420. }
  8421. me.drawDatasets(easingValue);
  8422. // Rest of layers
  8423. for (; i < layers.length; ++i) {
  8424. layers[i].draw(me.chartArea);
  8425. }
  8426. me._drawTooltip(easingValue);
  8427. core_plugins.notify(me, 'afterDraw', [easingValue]);
  8428. },
  8429. /**
  8430. * @private
  8431. */
  8432. transition: function(easingValue) {
  8433. var me = this;
  8434. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  8435. if (me.isDatasetVisible(i)) {
  8436. me.getDatasetMeta(i).controller.transition(easingValue);
  8437. }
  8438. }
  8439. me.tooltip.transition(easingValue);
  8440. },
  8441. /**
  8442. * @private
  8443. */
  8444. _getSortedDatasetMetas: function(filterVisible) {
  8445. var me = this;
  8446. var datasets = me.data.datasets || [];
  8447. var result = [];
  8448. var i, ilen;
  8449. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  8450. if (!filterVisible || me.isDatasetVisible(i)) {
  8451. result.push(me.getDatasetMeta(i));
  8452. }
  8453. }
  8454. result.sort(compare2Level('order', 'index'));
  8455. return result;
  8456. },
  8457. /**
  8458. * @private
  8459. */
  8460. _getSortedVisibleDatasetMetas: function() {
  8461. return this._getSortedDatasetMetas(true);
  8462. },
  8463. /**
  8464. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  8465. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  8466. * @private
  8467. */
  8468. drawDatasets: function(easingValue) {
  8469. var me = this;
  8470. var metasets, i;
  8471. if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  8472. return;
  8473. }
  8474. metasets = me._getSortedVisibleDatasetMetas();
  8475. for (i = metasets.length - 1; i >= 0; --i) {
  8476. me.drawDataset(metasets[i], easingValue);
  8477. }
  8478. core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  8479. },
  8480. /**
  8481. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  8482. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  8483. * @private
  8484. */
  8485. drawDataset: function(meta, easingValue) {
  8486. var me = this;
  8487. var args = {
  8488. meta: meta,
  8489. index: meta.index,
  8490. easingValue: easingValue
  8491. };
  8492. if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  8493. return;
  8494. }
  8495. meta.controller.draw(easingValue);
  8496. core_plugins.notify(me, 'afterDatasetDraw', [args]);
  8497. },
  8498. /**
  8499. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  8500. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  8501. * @private
  8502. */
  8503. _drawTooltip: function(easingValue) {
  8504. var me = this;
  8505. var tooltip = me.tooltip;
  8506. var args = {
  8507. tooltip: tooltip,
  8508. easingValue: easingValue
  8509. };
  8510. if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  8511. return;
  8512. }
  8513. tooltip.draw();
  8514. core_plugins.notify(me, 'afterTooltipDraw', [args]);
  8515. },
  8516. /**
  8517. * Get the single element that was clicked on
  8518. * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  8519. */
  8520. getElementAtEvent: function(e) {
  8521. return core_interaction.modes.single(this, e);
  8522. },
  8523. getElementsAtEvent: function(e) {
  8524. return core_interaction.modes.label(this, e, {intersect: true});
  8525. },
  8526. getElementsAtXAxis: function(e) {
  8527. return core_interaction.modes['x-axis'](this, e, {intersect: true});
  8528. },
  8529. getElementsAtEventForMode: function(e, mode, options) {
  8530. var method = core_interaction.modes[mode];
  8531. if (typeof method === 'function') {
  8532. return method(this, e, options);
  8533. }
  8534. return [];
  8535. },
  8536. getDatasetAtEvent: function(e) {
  8537. return core_interaction.modes.dataset(this, e, {intersect: true});
  8538. },
  8539. getDatasetMeta: function(datasetIndex) {
  8540. var me = this;
  8541. var dataset = me.data.datasets[datasetIndex];
  8542. if (!dataset._meta) {
  8543. dataset._meta = {};
  8544. }
  8545. var meta = dataset._meta[me.id];
  8546. if (!meta) {
  8547. meta = dataset._meta[me.id] = {
  8548. type: null,
  8549. data: [],
  8550. dataset: null,
  8551. controller: null,
  8552. hidden: null, // See isDatasetVisible() comment
  8553. xAxisID: null,
  8554. yAxisID: null,
  8555. order: dataset.order || 0,
  8556. index: datasetIndex
  8557. };
  8558. }
  8559. return meta;
  8560. },
  8561. getVisibleDatasetCount: function() {
  8562. var count = 0;
  8563. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  8564. if (this.isDatasetVisible(i)) {
  8565. count++;
  8566. }
  8567. }
  8568. return count;
  8569. },
  8570. isDatasetVisible: function(datasetIndex) {
  8571. var meta = this.getDatasetMeta(datasetIndex);
  8572. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  8573. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  8574. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  8575. },
  8576. generateLegend: function() {
  8577. return this.options.legendCallback(this);
  8578. },
  8579. /**
  8580. * @private
  8581. */
  8582. destroyDatasetMeta: function(datasetIndex) {
  8583. var id = this.id;
  8584. var dataset = this.data.datasets[datasetIndex];
  8585. var meta = dataset._meta && dataset._meta[id];
  8586. if (meta) {
  8587. meta.controller.destroy();
  8588. delete dataset._meta[id];
  8589. }
  8590. },
  8591. destroy: function() {
  8592. var me = this;
  8593. var canvas = me.canvas;
  8594. var i, ilen;
  8595. me.stop();
  8596. // dataset controllers need to cleanup associated data
  8597. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8598. me.destroyDatasetMeta(i);
  8599. }
  8600. if (canvas) {
  8601. me.unbindEvents();
  8602. helpers$1.canvas.clear(me);
  8603. platform.releaseContext(me.ctx);
  8604. me.canvas = null;
  8605. me.ctx = null;
  8606. }
  8607. core_plugins.notify(me, 'destroy');
  8608. delete Chart.instances[me.id];
  8609. },
  8610. toBase64Image: function() {
  8611. return this.canvas.toDataURL.apply(this.canvas, arguments);
  8612. },
  8613. initToolTip: function() {
  8614. var me = this;
  8615. me.tooltip = new core_tooltip({
  8616. _chart: me,
  8617. _chartInstance: me, // deprecated, backward compatibility
  8618. _data: me.data,
  8619. _options: me.options.tooltips
  8620. }, me);
  8621. },
  8622. /**
  8623. * @private
  8624. */
  8625. bindEvents: function() {
  8626. var me = this;
  8627. var listeners = me._listeners = {};
  8628. var listener = function() {
  8629. me.eventHandler.apply(me, arguments);
  8630. };
  8631. helpers$1.each(me.options.events, function(type) {
  8632. platform.addEventListener(me, type, listener);
  8633. listeners[type] = listener;
  8634. });
  8635. // Elements used to detect size change should not be injected for non responsive charts.
  8636. // See https://github.com/chartjs/Chart.js/issues/2210
  8637. if (me.options.responsive) {
  8638. listener = function() {
  8639. me.resize();
  8640. };
  8641. platform.addEventListener(me, 'resize', listener);
  8642. listeners.resize = listener;
  8643. }
  8644. },
  8645. /**
  8646. * @private
  8647. */
  8648. unbindEvents: function() {
  8649. var me = this;
  8650. var listeners = me._listeners;
  8651. if (!listeners) {
  8652. return;
  8653. }
  8654. delete me._listeners;
  8655. helpers$1.each(listeners, function(listener, type) {
  8656. platform.removeEventListener(me, type, listener);
  8657. });
  8658. },
  8659. updateHoverStyle: function(elements, mode, enabled) {
  8660. var prefix = enabled ? 'set' : 'remove';
  8661. var element, i, ilen;
  8662. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  8663. element = elements[i];
  8664. if (element) {
  8665. this.getDatasetMeta(element._datasetIndex).controller[prefix + 'HoverStyle'](element);
  8666. }
  8667. }
  8668. if (mode === 'dataset') {
  8669. this.getDatasetMeta(elements[0]._datasetIndex).controller['_' + prefix + 'DatasetHoverStyle']();
  8670. }
  8671. },
  8672. /**
  8673. * @private
  8674. */
  8675. eventHandler: function(e) {
  8676. var me = this;
  8677. var tooltip = me.tooltip;
  8678. if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
  8679. return;
  8680. }
  8681. // Buffer any update calls so that renders do not occur
  8682. me._bufferedRender = true;
  8683. me._bufferedRequest = null;
  8684. var changed = me.handleEvent(e);
  8685. // for smooth tooltip animations issue #4989
  8686. // the tooltip should be the source of change
  8687. // Animation check workaround:
  8688. // tooltip._start will be null when tooltip isn't animating
  8689. if (tooltip) {
  8690. changed = tooltip._start
  8691. ? tooltip.handleEvent(e)
  8692. : changed | tooltip.handleEvent(e);
  8693. }
  8694. core_plugins.notify(me, 'afterEvent', [e]);
  8695. var bufferedRequest = me._bufferedRequest;
  8696. if (bufferedRequest) {
  8697. // If we have an update that was triggered, we need to do a normal render
  8698. me.render(bufferedRequest);
  8699. } else if (changed && !me.animating) {
  8700. // If entering, leaving, or changing elements, animate the change via pivot
  8701. me.stop();
  8702. // We only need to render at this point. Updating will cause scales to be
  8703. // recomputed generating flicker & using more memory than necessary.
  8704. me.render({
  8705. duration: me.options.hover.animationDuration,
  8706. lazy: true
  8707. });
  8708. }
  8709. me._bufferedRender = false;
  8710. me._bufferedRequest = null;
  8711. return me;
  8712. },
  8713. /**
  8714. * Handle an event
  8715. * @private
  8716. * @param {IEvent} event the event to handle
  8717. * @return {boolean} true if the chart needs to re-render
  8718. */
  8719. handleEvent: function(e) {
  8720. var me = this;
  8721. var options = me.options || {};
  8722. var hoverOptions = options.hover;
  8723. var changed = false;
  8724. me.lastActive = me.lastActive || [];
  8725. // Find Active Elements for hover and tooltips
  8726. if (e.type === 'mouseout') {
  8727. me.active = [];
  8728. } else {
  8729. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  8730. }
  8731. // Invoke onHover hook
  8732. // Need to call with native event here to not break backwards compatibility
  8733. helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  8734. if (e.type === 'mouseup' || e.type === 'click') {
  8735. if (options.onClick) {
  8736. // Use e.native here for backwards compatibility
  8737. options.onClick.call(me, e.native, me.active);
  8738. }
  8739. }
  8740. // Remove styling for last active (even if it may still be active)
  8741. if (me.lastActive.length) {
  8742. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  8743. }
  8744. // Built in hover styling
  8745. if (me.active.length && hoverOptions.mode) {
  8746. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  8747. }
  8748. changed = !helpers$1.arrayEquals(me.active, me.lastActive);
  8749. // Remember Last Actives
  8750. me.lastActive = me.active;
  8751. return changed;
  8752. }
  8753. });
  8754. /**
  8755. * NOTE(SB) We actually don't use this container anymore but we need to keep it
  8756. * for backward compatibility. Though, it can still be useful for plugins that
  8757. * would need to work on multiple charts?!
  8758. */
  8759. Chart.instances = {};
  8760. var core_controller = Chart;
  8761. // DEPRECATIONS
  8762. /**
  8763. * Provided for backward compatibility, use Chart instead.
  8764. * @class Chart.Controller
  8765. * @deprecated since version 2.6
  8766. * @todo remove at version 3
  8767. * @private
  8768. */
  8769. Chart.Controller = Chart;
  8770. /**
  8771. * Provided for backward compatibility, not available anymore.
  8772. * @namespace Chart
  8773. * @deprecated since version 2.8
  8774. * @todo remove at version 3
  8775. * @private
  8776. */
  8777. Chart.types = {};
  8778. /**
  8779. * Provided for backward compatibility, not available anymore.
  8780. * @namespace Chart.helpers.configMerge
  8781. * @deprecated since version 2.8.0
  8782. * @todo remove at version 3
  8783. * @private
  8784. */
  8785. helpers$1.configMerge = mergeConfig;
  8786. /**
  8787. * Provided for backward compatibility, not available anymore.
  8788. * @namespace Chart.helpers.scaleMerge
  8789. * @deprecated since version 2.8.0
  8790. * @todo remove at version 3
  8791. * @private
  8792. */
  8793. helpers$1.scaleMerge = mergeScaleConfig;
  8794. var core_helpers = function() {
  8795. // -- Basic js utility methods
  8796. helpers$1.where = function(collection, filterCallback) {
  8797. if (helpers$1.isArray(collection) && Array.prototype.filter) {
  8798. return collection.filter(filterCallback);
  8799. }
  8800. var filtered = [];
  8801. helpers$1.each(collection, function(item) {
  8802. if (filterCallback(item)) {
  8803. filtered.push(item);
  8804. }
  8805. });
  8806. return filtered;
  8807. };
  8808. helpers$1.findIndex = Array.prototype.findIndex ?
  8809. function(array, callback, scope) {
  8810. return array.findIndex(callback, scope);
  8811. } :
  8812. function(array, callback, scope) {
  8813. scope = scope === undefined ? array : scope;
  8814. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  8815. if (callback.call(scope, array[i], i, array)) {
  8816. return i;
  8817. }
  8818. }
  8819. return -1;
  8820. };
  8821. helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
  8822. // Default to start of the array
  8823. if (helpers$1.isNullOrUndef(startIndex)) {
  8824. startIndex = -1;
  8825. }
  8826. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  8827. var currentItem = arrayToSearch[i];
  8828. if (filterCallback(currentItem)) {
  8829. return currentItem;
  8830. }
  8831. }
  8832. };
  8833. helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
  8834. // Default to end of the array
  8835. if (helpers$1.isNullOrUndef(startIndex)) {
  8836. startIndex = arrayToSearch.length;
  8837. }
  8838. for (var i = startIndex - 1; i >= 0; i--) {
  8839. var currentItem = arrayToSearch[i];
  8840. if (filterCallback(currentItem)) {
  8841. return currentItem;
  8842. }
  8843. }
  8844. };
  8845. // -- Math methods
  8846. helpers$1.isNumber = function(n) {
  8847. return !isNaN(parseFloat(n)) && isFinite(n);
  8848. };
  8849. helpers$1.almostEquals = function(x, y, epsilon) {
  8850. return Math.abs(x - y) < epsilon;
  8851. };
  8852. helpers$1.almostWhole = function(x, epsilon) {
  8853. var rounded = Math.round(x);
  8854. return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
  8855. };
  8856. helpers$1.max = function(array) {
  8857. return array.reduce(function(max, value) {
  8858. if (!isNaN(value)) {
  8859. return Math.max(max, value);
  8860. }
  8861. return max;
  8862. }, Number.NEGATIVE_INFINITY);
  8863. };
  8864. helpers$1.min = function(array) {
  8865. return array.reduce(function(min, value) {
  8866. if (!isNaN(value)) {
  8867. return Math.min(min, value);
  8868. }
  8869. return min;
  8870. }, Number.POSITIVE_INFINITY);
  8871. };
  8872. helpers$1.sign = Math.sign ?
  8873. function(x) {
  8874. return Math.sign(x);
  8875. } :
  8876. function(x) {
  8877. x = +x; // convert to a number
  8878. if (x === 0 || isNaN(x)) {
  8879. return x;
  8880. }
  8881. return x > 0 ? 1 : -1;
  8882. };
  8883. helpers$1.toRadians = function(degrees) {
  8884. return degrees * (Math.PI / 180);
  8885. };
  8886. helpers$1.toDegrees = function(radians) {
  8887. return radians * (180 / Math.PI);
  8888. };
  8889. /**
  8890. * Returns the number of decimal places
  8891. * i.e. the number of digits after the decimal point, of the value of this Number.
  8892. * @param {number} x - A number.
  8893. * @returns {number} The number of decimal places.
  8894. * @private
  8895. */
  8896. helpers$1._decimalPlaces = function(x) {
  8897. if (!helpers$1.isFinite(x)) {
  8898. return;
  8899. }
  8900. var e = 1;
  8901. var p = 0;
  8902. while (Math.round(x * e) / e !== x) {
  8903. e *= 10;
  8904. p++;
  8905. }
  8906. return p;
  8907. };
  8908. // Gets the angle from vertical upright to the point about a centre.
  8909. helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {
  8910. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  8911. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  8912. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  8913. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  8914. if (angle < (-0.5 * Math.PI)) {
  8915. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  8916. }
  8917. return {
  8918. angle: angle,
  8919. distance: radialDistanceFromCenter
  8920. };
  8921. };
  8922. helpers$1.distanceBetweenPoints = function(pt1, pt2) {
  8923. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  8924. };
  8925. /**
  8926. * Provided for backward compatibility, not available anymore
  8927. * @function Chart.helpers.aliasPixel
  8928. * @deprecated since version 2.8.0
  8929. * @todo remove at version 3
  8930. */
  8931. helpers$1.aliasPixel = function(pixelWidth) {
  8932. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  8933. };
  8934. /**
  8935. * Returns the aligned pixel value to avoid anti-aliasing blur
  8936. * @param {Chart} chart - The chart instance.
  8937. * @param {number} pixel - A pixel value.
  8938. * @param {number} width - The width of the element.
  8939. * @returns {number} The aligned pixel value.
  8940. * @private
  8941. */
  8942. helpers$1._alignPixel = function(chart, pixel, width) {
  8943. var devicePixelRatio = chart.currentDevicePixelRatio;
  8944. var halfWidth = width / 2;
  8945. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  8946. };
  8947. helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
  8948. // Props to Rob Spencer at scaled innovation for his post on splining between points
  8949. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  8950. // This function must also respect "skipped" points
  8951. var previous = firstPoint.skip ? middlePoint : firstPoint;
  8952. var current = middlePoint;
  8953. var next = afterPoint.skip ? middlePoint : afterPoint;
  8954. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  8955. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  8956. var s01 = d01 / (d01 + d12);
  8957. var s12 = d12 / (d01 + d12);
  8958. // If all points are the same, s01 & s02 will be inf
  8959. s01 = isNaN(s01) ? 0 : s01;
  8960. s12 = isNaN(s12) ? 0 : s12;
  8961. var fa = t * s01; // scaling factor for triangle Ta
  8962. var fb = t * s12;
  8963. return {
  8964. previous: {
  8965. x: current.x - fa * (next.x - previous.x),
  8966. y: current.y - fa * (next.y - previous.y)
  8967. },
  8968. next: {
  8969. x: current.x + fb * (next.x - previous.x),
  8970. y: current.y + fb * (next.y - previous.y)
  8971. }
  8972. };
  8973. };
  8974. helpers$1.EPSILON = Number.EPSILON || 1e-14;
  8975. helpers$1.splineCurveMonotone = function(points) {
  8976. // This function calculates Bézier control points in a similar way than |splineCurve|,
  8977. // but preserves monotonicity of the provided data and ensures no local extremums are added
  8978. // between the dataset discrete points due to the interpolation.
  8979. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  8980. var pointsWithTangents = (points || []).map(function(point) {
  8981. return {
  8982. model: point._model,
  8983. deltaK: 0,
  8984. mK: 0
  8985. };
  8986. });
  8987. // Calculate slopes (deltaK) and initialize tangents (mK)
  8988. var pointsLen = pointsWithTangents.length;
  8989. var i, pointBefore, pointCurrent, pointAfter;
  8990. for (i = 0; i < pointsLen; ++i) {
  8991. pointCurrent = pointsWithTangents[i];
  8992. if (pointCurrent.model.skip) {
  8993. continue;
  8994. }
  8995. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8996. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8997. if (pointAfter && !pointAfter.model.skip) {
  8998. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  8999. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  9000. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  9001. }
  9002. if (!pointBefore || pointBefore.model.skip) {
  9003. pointCurrent.mK = pointCurrent.deltaK;
  9004. } else if (!pointAfter || pointAfter.model.skip) {
  9005. pointCurrent.mK = pointBefore.deltaK;
  9006. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  9007. pointCurrent.mK = 0;
  9008. } else {
  9009. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  9010. }
  9011. }
  9012. // Adjust tangents to ensure monotonic properties
  9013. var alphaK, betaK, tauK, squaredMagnitude;
  9014. for (i = 0; i < pointsLen - 1; ++i) {
  9015. pointCurrent = pointsWithTangents[i];
  9016. pointAfter = pointsWithTangents[i + 1];
  9017. if (pointCurrent.model.skip || pointAfter.model.skip) {
  9018. continue;
  9019. }
  9020. if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  9021. pointCurrent.mK = pointAfter.mK = 0;
  9022. continue;
  9023. }
  9024. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  9025. betaK = pointAfter.mK / pointCurrent.deltaK;
  9026. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  9027. if (squaredMagnitude <= 9) {
  9028. continue;
  9029. }
  9030. tauK = 3 / Math.sqrt(squaredMagnitude);
  9031. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  9032. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  9033. }
  9034. // Compute control points
  9035. var deltaX;
  9036. for (i = 0; i < pointsLen; ++i) {
  9037. pointCurrent = pointsWithTangents[i];
  9038. if (pointCurrent.model.skip) {
  9039. continue;
  9040. }
  9041. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  9042. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  9043. if (pointBefore && !pointBefore.model.skip) {
  9044. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  9045. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  9046. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  9047. }
  9048. if (pointAfter && !pointAfter.model.skip) {
  9049. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  9050. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  9051. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  9052. }
  9053. }
  9054. };
  9055. helpers$1.nextItem = function(collection, index, loop) {
  9056. if (loop) {
  9057. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  9058. }
  9059. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  9060. };
  9061. helpers$1.previousItem = function(collection, index, loop) {
  9062. if (loop) {
  9063. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  9064. }
  9065. return index <= 0 ? collection[0] : collection[index - 1];
  9066. };
  9067. // Implementation of the nice number algorithm used in determining where axis labels will go
  9068. helpers$1.niceNum = function(range, round) {
  9069. var exponent = Math.floor(helpers$1.log10(range));
  9070. var fraction = range / Math.pow(10, exponent);
  9071. var niceFraction;
  9072. if (round) {
  9073. if (fraction < 1.5) {
  9074. niceFraction = 1;
  9075. } else if (fraction < 3) {
  9076. niceFraction = 2;
  9077. } else if (fraction < 7) {
  9078. niceFraction = 5;
  9079. } else {
  9080. niceFraction = 10;
  9081. }
  9082. } else if (fraction <= 1.0) {
  9083. niceFraction = 1;
  9084. } else if (fraction <= 2) {
  9085. niceFraction = 2;
  9086. } else if (fraction <= 5) {
  9087. niceFraction = 5;
  9088. } else {
  9089. niceFraction = 10;
  9090. }
  9091. return niceFraction * Math.pow(10, exponent);
  9092. };
  9093. // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  9094. helpers$1.requestAnimFrame = (function() {
  9095. if (typeof window === 'undefined') {
  9096. return function(callback) {
  9097. callback();
  9098. };
  9099. }
  9100. return window.requestAnimationFrame ||
  9101. window.webkitRequestAnimationFrame ||
  9102. window.mozRequestAnimationFrame ||
  9103. window.oRequestAnimationFrame ||
  9104. window.msRequestAnimationFrame ||
  9105. function(callback) {
  9106. return window.setTimeout(callback, 1000 / 60);
  9107. };
  9108. }());
  9109. // -- DOM methods
  9110. helpers$1.getRelativePosition = function(evt, chart) {
  9111. var mouseX, mouseY;
  9112. var e = evt.originalEvent || evt;
  9113. var canvas = evt.target || evt.srcElement;
  9114. var boundingRect = canvas.getBoundingClientRect();
  9115. var touches = e.touches;
  9116. if (touches && touches.length > 0) {
  9117. mouseX = touches[0].clientX;
  9118. mouseY = touches[0].clientY;
  9119. } else {
  9120. mouseX = e.clientX;
  9121. mouseY = e.clientY;
  9122. }
  9123. // Scale mouse coordinates into canvas coordinates
  9124. // by following the pattern laid out by 'jerryj' in the comments of
  9125. // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  9126. var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
  9127. var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
  9128. var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
  9129. var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
  9130. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  9131. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  9132. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  9133. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  9134. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  9135. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  9136. return {
  9137. x: mouseX,
  9138. y: mouseY
  9139. };
  9140. };
  9141. // Private helper function to convert max-width/max-height values that may be percentages into a number
  9142. function parseMaxStyle(styleValue, node, parentProperty) {
  9143. var valueInPixels;
  9144. if (typeof styleValue === 'string') {
  9145. valueInPixels = parseInt(styleValue, 10);
  9146. if (styleValue.indexOf('%') !== -1) {
  9147. // percentage * size in dimension
  9148. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  9149. }
  9150. } else {
  9151. valueInPixels = styleValue;
  9152. }
  9153. return valueInPixels;
  9154. }
  9155. /**
  9156. * Returns if the given value contains an effective constraint.
  9157. * @private
  9158. */
  9159. function isConstrainedValue(value) {
  9160. return value !== undefined && value !== null && value !== 'none';
  9161. }
  9162. /**
  9163. * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
  9164. * @param {HTMLElement} domNode - the node to check the constraint on
  9165. * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
  9166. * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
  9167. * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
  9168. */
  9169. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  9170. var view = document.defaultView;
  9171. var parentNode = helpers$1._getParentNode(domNode);
  9172. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  9173. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  9174. var hasCNode = isConstrainedValue(constrainedNode);
  9175. var hasCContainer = isConstrainedValue(constrainedContainer);
  9176. var infinity = Number.POSITIVE_INFINITY;
  9177. if (hasCNode || hasCContainer) {
  9178. return Math.min(
  9179. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  9180. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  9181. }
  9182. return 'none';
  9183. }
  9184. // returns Number or undefined if no constraint
  9185. helpers$1.getConstraintWidth = function(domNode) {
  9186. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  9187. };
  9188. // returns Number or undefined if no constraint
  9189. helpers$1.getConstraintHeight = function(domNode) {
  9190. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  9191. };
  9192. /**
  9193. * @private
  9194. */
  9195. helpers$1._calculatePadding = function(container, padding, parentDimension) {
  9196. padding = helpers$1.getStyle(container, padding);
  9197. return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
  9198. };
  9199. /**
  9200. * @private
  9201. */
  9202. helpers$1._getParentNode = function(domNode) {
  9203. var parent = domNode.parentNode;
  9204. if (parent && parent.toString() === '[object ShadowRoot]') {
  9205. parent = parent.host;
  9206. }
  9207. return parent;
  9208. };
  9209. helpers$1.getMaximumWidth = function(domNode) {
  9210. var container = helpers$1._getParentNode(domNode);
  9211. if (!container) {
  9212. return domNode.clientWidth;
  9213. }
  9214. var clientWidth = container.clientWidth;
  9215. var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
  9216. var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
  9217. var w = clientWidth - paddingLeft - paddingRight;
  9218. var cw = helpers$1.getConstraintWidth(domNode);
  9219. return isNaN(cw) ? w : Math.min(w, cw);
  9220. };
  9221. helpers$1.getMaximumHeight = function(domNode) {
  9222. var container = helpers$1._getParentNode(domNode);
  9223. if (!container) {
  9224. return domNode.clientHeight;
  9225. }
  9226. var clientHeight = container.clientHeight;
  9227. var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
  9228. var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
  9229. var h = clientHeight - paddingTop - paddingBottom;
  9230. var ch = helpers$1.getConstraintHeight(domNode);
  9231. return isNaN(ch) ? h : Math.min(h, ch);
  9232. };
  9233. helpers$1.getStyle = function(el, property) {
  9234. return el.currentStyle ?
  9235. el.currentStyle[property] :
  9236. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  9237. };
  9238. helpers$1.retinaScale = function(chart, forceRatio) {
  9239. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  9240. if (pixelRatio === 1) {
  9241. return;
  9242. }
  9243. var canvas = chart.canvas;
  9244. var height = chart.height;
  9245. var width = chart.width;
  9246. canvas.height = height * pixelRatio;
  9247. canvas.width = width * pixelRatio;
  9248. chart.ctx.scale(pixelRatio, pixelRatio);
  9249. // If no style has been set on the canvas, the render size is used as display size,
  9250. // making the chart visually bigger, so let's enforce it to the "correct" values.
  9251. // See https://github.com/chartjs/Chart.js/issues/3575
  9252. if (!canvas.style.height && !canvas.style.width) {
  9253. canvas.style.height = height + 'px';
  9254. canvas.style.width = width + 'px';
  9255. }
  9256. };
  9257. // -- Canvas methods
  9258. helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {
  9259. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  9260. };
  9261. helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {
  9262. cache = cache || {};
  9263. var data = cache.data = cache.data || {};
  9264. var gc = cache.garbageCollect = cache.garbageCollect || [];
  9265. if (cache.font !== font) {
  9266. data = cache.data = {};
  9267. gc = cache.garbageCollect = [];
  9268. cache.font = font;
  9269. }
  9270. ctx.font = font;
  9271. var longest = 0;
  9272. var ilen = arrayOfThings.length;
  9273. var i, j, jlen, thing, nestedThing;
  9274. for (i = 0; i < ilen; i++) {
  9275. thing = arrayOfThings[i];
  9276. // Undefined strings and arrays should not be measured
  9277. if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
  9278. longest = helpers$1.measureText(ctx, data, gc, longest, thing);
  9279. } else if (helpers$1.isArray(thing)) {
  9280. // if it is an array lets measure each element
  9281. // to do maybe simplify this function a bit so we can do this more recursively?
  9282. for (j = 0, jlen = thing.length; j < jlen; j++) {
  9283. nestedThing = thing[j];
  9284. // Undefined strings and arrays should not be measured
  9285. if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
  9286. longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
  9287. }
  9288. }
  9289. }
  9290. }
  9291. var gcLen = gc.length / 2;
  9292. if (gcLen > arrayOfThings.length) {
  9293. for (i = 0; i < gcLen; i++) {
  9294. delete data[gc[i]];
  9295. }
  9296. gc.splice(0, gcLen);
  9297. }
  9298. return longest;
  9299. };
  9300. helpers$1.measureText = function(ctx, data, gc, longest, string) {
  9301. var textWidth = data[string];
  9302. if (!textWidth) {
  9303. textWidth = data[string] = ctx.measureText(string).width;
  9304. gc.push(string);
  9305. }
  9306. if (textWidth > longest) {
  9307. longest = textWidth;
  9308. }
  9309. return longest;
  9310. };
  9311. /**
  9312. * @deprecated
  9313. */
  9314. helpers$1.numberOfLabelLines = function(arrayOfThings) {
  9315. var numberOfLines = 1;
  9316. helpers$1.each(arrayOfThings, function(thing) {
  9317. if (helpers$1.isArray(thing)) {
  9318. if (thing.length > numberOfLines) {
  9319. numberOfLines = thing.length;
  9320. }
  9321. }
  9322. });
  9323. return numberOfLines;
  9324. };
  9325. helpers$1.color = !chartjsColor ?
  9326. function(value) {
  9327. console.error('Color.js not found!');
  9328. return value;
  9329. } :
  9330. function(value) {
  9331. /* global CanvasGradient */
  9332. if (value instanceof CanvasGradient) {
  9333. value = core_defaults.global.defaultColor;
  9334. }
  9335. return chartjsColor(value);
  9336. };
  9337. helpers$1.getHoverColor = function(colorValue) {
  9338. /* global CanvasPattern */
  9339. return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
  9340. colorValue :
  9341. helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  9342. };
  9343. };
  9344. function abstract() {
  9345. throw new Error(
  9346. 'This method is not implemented: either no adapter can ' +
  9347. 'be found or an incomplete integration was provided.'
  9348. );
  9349. }
  9350. /**
  9351. * Date adapter (current used by the time scale)
  9352. * @namespace Chart._adapters._date
  9353. * @memberof Chart._adapters
  9354. * @private
  9355. */
  9356. /**
  9357. * Currently supported unit string values.
  9358. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
  9359. * @memberof Chart._adapters._date
  9360. * @name Unit
  9361. */
  9362. /**
  9363. * @class
  9364. */
  9365. function DateAdapter(options) {
  9366. this.options = options || {};
  9367. }
  9368. helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
  9369. /**
  9370. * Returns a map of time formats for the supported formatting units defined
  9371. * in Unit as well as 'datetime' representing a detailed date/time string.
  9372. * @returns {{string: string}}
  9373. */
  9374. formats: abstract,
  9375. /**
  9376. * Parses the given `value` and return the associated timestamp.
  9377. * @param {any} value - the value to parse (usually comes from the data)
  9378. * @param {string} [format] - the expected data format
  9379. * @returns {(number|null)}
  9380. * @function
  9381. */
  9382. parse: abstract,
  9383. /**
  9384. * Returns the formatted date in the specified `format` for a given `timestamp`.
  9385. * @param {number} timestamp - the timestamp to format
  9386. * @param {string} format - the date/time token
  9387. * @return {string}
  9388. * @function
  9389. */
  9390. format: abstract,
  9391. /**
  9392. * Adds the specified `amount` of `unit` to the given `timestamp`.
  9393. * @param {number} timestamp - the input timestamp
  9394. * @param {number} amount - the amount to add
  9395. * @param {Unit} unit - the unit as string
  9396. * @return {number}
  9397. * @function
  9398. */
  9399. add: abstract,
  9400. /**
  9401. * Returns the number of `unit` between the given timestamps.
  9402. * @param {number} max - the input timestamp (reference)
  9403. * @param {number} min - the timestamp to substract
  9404. * @param {Unit} unit - the unit as string
  9405. * @return {number}
  9406. * @function
  9407. */
  9408. diff: abstract,
  9409. /**
  9410. * Returns start of `unit` for the given `timestamp`.
  9411. * @param {number} timestamp - the input timestamp
  9412. * @param {Unit} unit - the unit as string
  9413. * @param {number} [weekday] - the ISO day of the week with 1 being Monday
  9414. * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
  9415. * @function
  9416. */
  9417. startOf: abstract,
  9418. /**
  9419. * Returns end of `unit` for the given `timestamp`.
  9420. * @param {number} timestamp - the input timestamp
  9421. * @param {Unit} unit - the unit as string
  9422. * @function
  9423. */
  9424. endOf: abstract,
  9425. // DEPRECATIONS
  9426. /**
  9427. * Provided for backward compatibility for scale.getValueForPixel(),
  9428. * this method should be overridden only by the moment adapter.
  9429. * @deprecated since version 2.8.0
  9430. * @todo remove at version 3
  9431. * @private
  9432. */
  9433. _create: function(value) {
  9434. return value;
  9435. }
  9436. });
  9437. DateAdapter.override = function(members) {
  9438. helpers$1.extend(DateAdapter.prototype, members);
  9439. };
  9440. var _date = DateAdapter;
  9441. var core_adapters = {
  9442. _date: _date
  9443. };
  9444. /**
  9445. * Namespace to hold static tick generation functions
  9446. * @namespace Chart.Ticks
  9447. */
  9448. var core_ticks = {
  9449. /**
  9450. * Namespace to hold formatters for different types of ticks
  9451. * @namespace Chart.Ticks.formatters
  9452. */
  9453. formatters: {
  9454. /**
  9455. * Formatter for value labels
  9456. * @method Chart.Ticks.formatters.values
  9457. * @param value the value to display
  9458. * @return {string|string[]} the label to display
  9459. */
  9460. values: function(value) {
  9461. return helpers$1.isArray(value) ? value : '' + value;
  9462. },
  9463. /**
  9464. * Formatter for linear numeric ticks
  9465. * @method Chart.Ticks.formatters.linear
  9466. * @param tickValue {number} the value to be formatted
  9467. * @param index {number} the position of the tickValue parameter in the ticks array
  9468. * @param ticks {number[]} the list of ticks being converted
  9469. * @return {string} string representation of the tickValue parameter
  9470. */
  9471. linear: function(tickValue, index, ticks) {
  9472. // If we have lots of ticks, don't use the ones
  9473. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  9474. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  9475. if (Math.abs(delta) > 1) {
  9476. if (tickValue !== Math.floor(tickValue)) {
  9477. // not an integer
  9478. delta = tickValue - Math.floor(tickValue);
  9479. }
  9480. }
  9481. var logDelta = helpers$1.log10(Math.abs(delta));
  9482. var tickString = '';
  9483. if (tickValue !== 0) {
  9484. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  9485. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  9486. var logTick = helpers$1.log10(Math.abs(tickValue));
  9487. var numExponential = Math.floor(logTick) - Math.floor(logDelta);
  9488. numExponential = Math.max(Math.min(numExponential, 20), 0);
  9489. tickString = tickValue.toExponential(numExponential);
  9490. } else {
  9491. var numDecimal = -1 * Math.floor(logDelta);
  9492. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  9493. tickString = tickValue.toFixed(numDecimal);
  9494. }
  9495. } else {
  9496. tickString = '0'; // never show decimal places for 0
  9497. }
  9498. return tickString;
  9499. },
  9500. logarithmic: function(tickValue, index, ticks) {
  9501. var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
  9502. if (tickValue === 0) {
  9503. return '0';
  9504. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  9505. return tickValue.toExponential();
  9506. }
  9507. return '';
  9508. }
  9509. }
  9510. };
  9511. var isArray = helpers$1.isArray;
  9512. var isNullOrUndef = helpers$1.isNullOrUndef;
  9513. var valueOrDefault$a = helpers$1.valueOrDefault;
  9514. var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
  9515. core_defaults._set('scale', {
  9516. display: true,
  9517. position: 'left',
  9518. offset: false,
  9519. // grid line settings
  9520. gridLines: {
  9521. display: true,
  9522. color: 'rgba(0,0,0,0.1)',
  9523. lineWidth: 1,
  9524. drawBorder: true,
  9525. drawOnChartArea: true,
  9526. drawTicks: true,
  9527. tickMarkLength: 10,
  9528. zeroLineWidth: 1,
  9529. zeroLineColor: 'rgba(0,0,0,0.25)',
  9530. zeroLineBorderDash: [],
  9531. zeroLineBorderDashOffset: 0.0,
  9532. offsetGridLines: false,
  9533. borderDash: [],
  9534. borderDashOffset: 0.0
  9535. },
  9536. // scale label
  9537. scaleLabel: {
  9538. // display property
  9539. display: false,
  9540. // actual label
  9541. labelString: '',
  9542. // top/bottom padding
  9543. padding: {
  9544. top: 4,
  9545. bottom: 4
  9546. }
  9547. },
  9548. // label settings
  9549. ticks: {
  9550. beginAtZero: false,
  9551. minRotation: 0,
  9552. maxRotation: 50,
  9553. mirror: false,
  9554. padding: 0,
  9555. reverse: false,
  9556. display: true,
  9557. autoSkip: true,
  9558. autoSkipPadding: 0,
  9559. labelOffset: 0,
  9560. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  9561. callback: core_ticks.formatters.values,
  9562. minor: {},
  9563. major: {}
  9564. }
  9565. });
  9566. /** Returns a new array containing numItems from arr */
  9567. function sample(arr, numItems) {
  9568. var result = [];
  9569. var increment = arr.length / numItems;
  9570. var i = 0;
  9571. var len = arr.length;
  9572. for (; i < len; i += increment) {
  9573. result.push(arr[Math.floor(i)]);
  9574. }
  9575. return result;
  9576. }
  9577. function getPixelForGridLine(scale, index, offsetGridLines) {
  9578. var length = scale.getTicks().length;
  9579. var validIndex = Math.min(index, length - 1);
  9580. var lineValue = scale.getPixelForTick(validIndex);
  9581. var start = scale._startPixel;
  9582. var end = scale._endPixel;
  9583. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  9584. var offset;
  9585. if (offsetGridLines) {
  9586. if (length === 1) {
  9587. offset = Math.max(lineValue - start, end - lineValue);
  9588. } else if (index === 0) {
  9589. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  9590. } else {
  9591. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  9592. }
  9593. lineValue += validIndex < index ? offset : -offset;
  9594. // Return undefined if the pixel is out of the range
  9595. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  9596. return;
  9597. }
  9598. }
  9599. return lineValue;
  9600. }
  9601. function garbageCollect(caches, length) {
  9602. helpers$1.each(caches, function(cache) {
  9603. var gc = cache.gc;
  9604. var gcLen = gc.length / 2;
  9605. var i;
  9606. if (gcLen > length) {
  9607. for (i = 0; i < gcLen; ++i) {
  9608. delete cache.data[gc[i]];
  9609. }
  9610. gc.splice(0, gcLen);
  9611. }
  9612. });
  9613. }
  9614. /**
  9615. * Returns {width, height, offset} objects for the first, last, widest, highest tick
  9616. * labels where offset indicates the anchor point offset from the top in pixels.
  9617. */
  9618. function computeLabelSizes(ctx, tickFonts, ticks, caches) {
  9619. var length = ticks.length;
  9620. var widths = [];
  9621. var heights = [];
  9622. var offsets = [];
  9623. var widestLabelSize = 0;
  9624. var highestLabelSize = 0;
  9625. var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest;
  9626. for (i = 0; i < length; ++i) {
  9627. label = ticks[i].label;
  9628. tickFont = ticks[i].major ? tickFonts.major : tickFonts.minor;
  9629. ctx.font = fontString = tickFont.string;
  9630. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  9631. lineHeight = tickFont.lineHeight;
  9632. width = height = 0;
  9633. // Undefined labels and arrays should not be measured
  9634. if (!isNullOrUndef(label) && !isArray(label)) {
  9635. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, label);
  9636. height = lineHeight;
  9637. } else if (isArray(label)) {
  9638. // if it is an array let's measure each element
  9639. for (j = 0, jlen = label.length; j < jlen; ++j) {
  9640. nestedLabel = label[j];
  9641. // Undefined labels and arrays should not be measured
  9642. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  9643. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  9644. height += lineHeight;
  9645. }
  9646. }
  9647. }
  9648. widths.push(width);
  9649. heights.push(height);
  9650. offsets.push(lineHeight / 2);
  9651. widestLabelSize = Math.max(width, widestLabelSize);
  9652. highestLabelSize = Math.max(height, highestLabelSize);
  9653. }
  9654. garbageCollect(caches, length);
  9655. widest = widths.indexOf(widestLabelSize);
  9656. highest = heights.indexOf(highestLabelSize);
  9657. function valueAt(idx) {
  9658. return {
  9659. width: widths[idx] || 0,
  9660. height: heights[idx] || 0,
  9661. offset: offsets[idx] || 0
  9662. };
  9663. }
  9664. return {
  9665. first: valueAt(0),
  9666. last: valueAt(length - 1),
  9667. widest: valueAt(widest),
  9668. highest: valueAt(highest)
  9669. };
  9670. }
  9671. function getTickMarkLength(options) {
  9672. return options.drawTicks ? options.tickMarkLength : 0;
  9673. }
  9674. function getScaleLabelHeight(options) {
  9675. var font, padding;
  9676. if (!options.display) {
  9677. return 0;
  9678. }
  9679. font = helpers$1.options._parseFont(options);
  9680. padding = helpers$1.options.toPadding(options.padding);
  9681. return font.lineHeight + padding.height;
  9682. }
  9683. function parseFontOptions(options, nestedOpts) {
  9684. return helpers$1.extend(helpers$1.options._parseFont({
  9685. fontFamily: valueOrDefault$a(nestedOpts.fontFamily, options.fontFamily),
  9686. fontSize: valueOrDefault$a(nestedOpts.fontSize, options.fontSize),
  9687. fontStyle: valueOrDefault$a(nestedOpts.fontStyle, options.fontStyle),
  9688. lineHeight: valueOrDefault$a(nestedOpts.lineHeight, options.lineHeight)
  9689. }), {
  9690. color: helpers$1.options.resolve([nestedOpts.fontColor, options.fontColor, core_defaults.global.defaultFontColor])
  9691. });
  9692. }
  9693. function parseTickFontOptions(options) {
  9694. var minor = parseFontOptions(options, options.minor);
  9695. var major = options.major.enabled ? parseFontOptions(options, options.major) : minor;
  9696. return {minor: minor, major: major};
  9697. }
  9698. function nonSkipped(ticksToFilter) {
  9699. var filtered = [];
  9700. var item, index, len;
  9701. for (index = 0, len = ticksToFilter.length; index < len; ++index) {
  9702. item = ticksToFilter[index];
  9703. if (typeof item._index !== 'undefined') {
  9704. filtered.push(item);
  9705. }
  9706. }
  9707. return filtered;
  9708. }
  9709. function getEvenSpacing(arr) {
  9710. var len = arr.length;
  9711. var i, diff;
  9712. if (len < 2) {
  9713. return false;
  9714. }
  9715. for (diff = arr[0], i = 1; i < len; ++i) {
  9716. if (arr[i] - arr[i - 1] !== diff) {
  9717. return false;
  9718. }
  9719. }
  9720. return diff;
  9721. }
  9722. function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
  9723. var evenMajorSpacing = getEvenSpacing(majorIndices);
  9724. var spacing = (ticks.length - 1) / ticksLimit;
  9725. var factors, factor, i, ilen;
  9726. // If the major ticks are evenly spaced apart, place the minor ticks
  9727. // so that they divide the major ticks into even chunks
  9728. if (!evenMajorSpacing) {
  9729. return Math.max(spacing, 1);
  9730. }
  9731. factors = helpers$1.math._factorize(evenMajorSpacing);
  9732. for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
  9733. factor = factors[i];
  9734. if (factor > spacing) {
  9735. return factor;
  9736. }
  9737. }
  9738. return Math.max(spacing, 1);
  9739. }
  9740. function getMajorIndices(ticks) {
  9741. var result = [];
  9742. var i, ilen;
  9743. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  9744. if (ticks[i].major) {
  9745. result.push(i);
  9746. }
  9747. }
  9748. return result;
  9749. }
  9750. function skipMajors(ticks, majorIndices, spacing) {
  9751. var count = 0;
  9752. var next = majorIndices[0];
  9753. var i, tick;
  9754. spacing = Math.ceil(spacing);
  9755. for (i = 0; i < ticks.length; i++) {
  9756. tick = ticks[i];
  9757. if (i === next) {
  9758. tick._index = i;
  9759. count++;
  9760. next = majorIndices[count * spacing];
  9761. } else {
  9762. delete tick.label;
  9763. }
  9764. }
  9765. }
  9766. function skip(ticks, spacing, majorStart, majorEnd) {
  9767. var start = valueOrDefault$a(majorStart, 0);
  9768. var end = Math.min(valueOrDefault$a(majorEnd, ticks.length), ticks.length);
  9769. var count = 0;
  9770. var length, i, tick, next;
  9771. spacing = Math.ceil(spacing);
  9772. if (majorEnd) {
  9773. length = majorEnd - majorStart;
  9774. spacing = length / Math.floor(length / spacing);
  9775. }
  9776. next = start;
  9777. while (next < 0) {
  9778. count++;
  9779. next = Math.round(start + count * spacing);
  9780. }
  9781. for (i = Math.max(start, 0); i < end; i++) {
  9782. tick = ticks[i];
  9783. if (i === next) {
  9784. tick._index = i;
  9785. count++;
  9786. next = Math.round(start + count * spacing);
  9787. } else {
  9788. delete tick.label;
  9789. }
  9790. }
  9791. }
  9792. var Scale = core_element.extend({
  9793. zeroLineIndex: 0,
  9794. /**
  9795. * Get the padding needed for the scale
  9796. * @method getPadding
  9797. * @private
  9798. * @returns {Padding} the necessary padding
  9799. */
  9800. getPadding: function() {
  9801. var me = this;
  9802. return {
  9803. left: me.paddingLeft || 0,
  9804. top: me.paddingTop || 0,
  9805. right: me.paddingRight || 0,
  9806. bottom: me.paddingBottom || 0
  9807. };
  9808. },
  9809. /**
  9810. * Returns the scale tick objects ({label, major})
  9811. * @since 2.7
  9812. */
  9813. getTicks: function() {
  9814. return this._ticks;
  9815. },
  9816. /**
  9817. * @private
  9818. */
  9819. _getLabels: function() {
  9820. var data = this.chart.data;
  9821. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  9822. },
  9823. // These methods are ordered by lifecyle. Utilities then follow.
  9824. // Any function defined here is inherited by all scale types.
  9825. // Any function can be extended by the scale type
  9826. /**
  9827. * Provided for backward compatibility, not available anymore
  9828. * @function Chart.Scale.mergeTicksOptions
  9829. * @deprecated since version 2.8.0
  9830. * @todo remove at version 3
  9831. */
  9832. mergeTicksOptions: function() {
  9833. // noop
  9834. },
  9835. beforeUpdate: function() {
  9836. helpers$1.callback(this.options.beforeUpdate, [this]);
  9837. },
  9838. /**
  9839. * @param {number} maxWidth - the max width in pixels
  9840. * @param {number} maxHeight - the max height in pixels
  9841. * @param {object} margins - the space between the edge of the other scales and edge of the chart
  9842. * This space comes from two sources:
  9843. * - padding - space that's required to show the labels at the edges of the scale
  9844. * - thickness of scales or legends in another orientation
  9845. */
  9846. update: function(maxWidth, maxHeight, margins) {
  9847. var me = this;
  9848. var tickOpts = me.options.ticks;
  9849. var sampleSize = tickOpts.sampleSize;
  9850. var i, ilen, labels, ticks, samplingEnabled;
  9851. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  9852. me.beforeUpdate();
  9853. // Absorb the master measurements
  9854. me.maxWidth = maxWidth;
  9855. me.maxHeight = maxHeight;
  9856. me.margins = helpers$1.extend({
  9857. left: 0,
  9858. right: 0,
  9859. top: 0,
  9860. bottom: 0
  9861. }, margins);
  9862. me._ticks = null;
  9863. me.ticks = null;
  9864. me._labelSizes = null;
  9865. me._maxLabelLines = 0;
  9866. me.longestLabelWidth = 0;
  9867. me.longestTextCache = me.longestTextCache || {};
  9868. me._gridLineItems = null;
  9869. me._labelItems = null;
  9870. // Dimensions
  9871. me.beforeSetDimensions();
  9872. me.setDimensions();
  9873. me.afterSetDimensions();
  9874. // Data min/max
  9875. me.beforeDataLimits();
  9876. me.determineDataLimits();
  9877. me.afterDataLimits();
  9878. // Ticks - `this.ticks` is now DEPRECATED!
  9879. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  9880. // and must not be accessed directly from outside this class. `this.ticks` being
  9881. // around for long time and not marked as private, we can't change its structure
  9882. // without unexpected breaking changes. If you need to access the scale ticks,
  9883. // use scale.getTicks() instead.
  9884. me.beforeBuildTicks();
  9885. // New implementations should return an array of objects but for BACKWARD COMPAT,
  9886. // we still support no return (`this.ticks` internally set by calling this method).
  9887. ticks = me.buildTicks() || [];
  9888. // Allow modification of ticks in callback.
  9889. ticks = me.afterBuildTicks(ticks) || ticks;
  9890. // Ensure ticks contains ticks in new tick format
  9891. if ((!ticks || !ticks.length) && me.ticks) {
  9892. ticks = [];
  9893. for (i = 0, ilen = me.ticks.length; i < ilen; ++i) {
  9894. ticks.push({
  9895. value: me.ticks[i],
  9896. major: false
  9897. });
  9898. }
  9899. }
  9900. me._ticks = ticks;
  9901. // Compute tick rotation and fit using a sampled subset of labels
  9902. // We generally don't need to compute the size of every single label for determining scale size
  9903. samplingEnabled = sampleSize < ticks.length;
  9904. labels = me._convertTicksToLabels(samplingEnabled ? sample(ticks, sampleSize) : ticks);
  9905. // _configure is called twice, once here, once from core.controller.updateLayout.
  9906. // Here we haven't been positioned yet, but dimensions are correct.
  9907. // Variables set in _configure are needed for calculateTickRotation, and
  9908. // it's ok that coordinates are not correct there, only dimensions matter.
  9909. me._configure();
  9910. // Tick Rotation
  9911. me.beforeCalculateTickRotation();
  9912. me.calculateTickRotation();
  9913. me.afterCalculateTickRotation();
  9914. me.beforeFit();
  9915. me.fit();
  9916. me.afterFit();
  9917. // Auto-skip
  9918. me._ticksToDraw = tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto') ? me._autoSkip(ticks) : ticks;
  9919. if (samplingEnabled) {
  9920. // Generate labels using all non-skipped ticks
  9921. labels = me._convertTicksToLabels(me._ticksToDraw);
  9922. }
  9923. me.ticks = labels; // BACKWARD COMPATIBILITY
  9924. // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
  9925. me.afterUpdate();
  9926. // TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused
  9927. // make maxWidth and maxHeight private
  9928. return me.minSize;
  9929. },
  9930. /**
  9931. * @private
  9932. */
  9933. _configure: function() {
  9934. var me = this;
  9935. var reversePixels = me.options.ticks.reverse;
  9936. var startPixel, endPixel;
  9937. if (me.isHorizontal()) {
  9938. startPixel = me.left;
  9939. endPixel = me.right;
  9940. } else {
  9941. startPixel = me.top;
  9942. endPixel = me.bottom;
  9943. // by default vertical scales are from bottom to top, so pixels are reversed
  9944. reversePixels = !reversePixels;
  9945. }
  9946. me._startPixel = startPixel;
  9947. me._endPixel = endPixel;
  9948. me._reversePixels = reversePixels;
  9949. me._length = endPixel - startPixel;
  9950. },
  9951. afterUpdate: function() {
  9952. helpers$1.callback(this.options.afterUpdate, [this]);
  9953. },
  9954. //
  9955. beforeSetDimensions: function() {
  9956. helpers$1.callback(this.options.beforeSetDimensions, [this]);
  9957. },
  9958. setDimensions: function() {
  9959. var me = this;
  9960. // Set the unconstrained dimension before label rotation
  9961. if (me.isHorizontal()) {
  9962. // Reset position before calculating rotation
  9963. me.width = me.maxWidth;
  9964. me.left = 0;
  9965. me.right = me.width;
  9966. } else {
  9967. me.height = me.maxHeight;
  9968. // Reset position before calculating rotation
  9969. me.top = 0;
  9970. me.bottom = me.height;
  9971. }
  9972. // Reset padding
  9973. me.paddingLeft = 0;
  9974. me.paddingTop = 0;
  9975. me.paddingRight = 0;
  9976. me.paddingBottom = 0;
  9977. },
  9978. afterSetDimensions: function() {
  9979. helpers$1.callback(this.options.afterSetDimensions, [this]);
  9980. },
  9981. // Data limits
  9982. beforeDataLimits: function() {
  9983. helpers$1.callback(this.options.beforeDataLimits, [this]);
  9984. },
  9985. determineDataLimits: helpers$1.noop,
  9986. afterDataLimits: function() {
  9987. helpers$1.callback(this.options.afterDataLimits, [this]);
  9988. },
  9989. //
  9990. beforeBuildTicks: function() {
  9991. helpers$1.callback(this.options.beforeBuildTicks, [this]);
  9992. },
  9993. buildTicks: helpers$1.noop,
  9994. afterBuildTicks: function(ticks) {
  9995. var me = this;
  9996. // ticks is empty for old axis implementations here
  9997. if (isArray(ticks) && ticks.length) {
  9998. return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
  9999. }
  10000. // Support old implementations (that modified `this.ticks` directly in buildTicks)
  10001. me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
  10002. return ticks;
  10003. },
  10004. beforeTickToLabelConversion: function() {
  10005. helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
  10006. },
  10007. convertTicksToLabels: function() {
  10008. var me = this;
  10009. // Convert ticks to strings
  10010. var tickOpts = me.options.ticks;
  10011. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  10012. },
  10013. afterTickToLabelConversion: function() {
  10014. helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
  10015. },
  10016. //
  10017. beforeCalculateTickRotation: function() {
  10018. helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
  10019. },
  10020. calculateTickRotation: function() {
  10021. var me = this;
  10022. var options = me.options;
  10023. var tickOpts = options.ticks;
  10024. var numTicks = me.getTicks().length;
  10025. var minRotation = tickOpts.minRotation || 0;
  10026. var maxRotation = tickOpts.maxRotation;
  10027. var labelRotation = minRotation;
  10028. var labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal;
  10029. if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
  10030. me.labelRotation = minRotation;
  10031. return;
  10032. }
  10033. labelSizes = me._getLabelSizes();
  10034. maxLabelWidth = labelSizes.widest.width;
  10035. maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;
  10036. // Estimate the width of each grid based on the canvas width, the maximum
  10037. // label width and the number of tick intervals
  10038. maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);
  10039. tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
  10040. // Allow 3 pixels x2 padding either side for label readability
  10041. if (maxLabelWidth + 6 > tickWidth) {
  10042. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  10043. maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)
  10044. - tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
  10045. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  10046. labelRotation = helpers$1.toDegrees(Math.min(
  10047. Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
  10048. Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
  10049. ));
  10050. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  10051. }
  10052. me.labelRotation = labelRotation;
  10053. },
  10054. afterCalculateTickRotation: function() {
  10055. helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
  10056. },
  10057. //
  10058. beforeFit: function() {
  10059. helpers$1.callback(this.options.beforeFit, [this]);
  10060. },
  10061. fit: function() {
  10062. var me = this;
  10063. // Reset
  10064. var minSize = me.minSize = {
  10065. width: 0,
  10066. height: 0
  10067. };
  10068. var chart = me.chart;
  10069. var opts = me.options;
  10070. var tickOpts = opts.ticks;
  10071. var scaleLabelOpts = opts.scaleLabel;
  10072. var gridLineOpts = opts.gridLines;
  10073. var display = me._isVisible();
  10074. var isBottom = opts.position === 'bottom';
  10075. var isHorizontal = me.isHorizontal();
  10076. // Width
  10077. if (isHorizontal) {
  10078. minSize.width = me.maxWidth;
  10079. } else if (display) {
  10080. minSize.width = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10081. }
  10082. // height
  10083. if (!isHorizontal) {
  10084. minSize.height = me.maxHeight; // fill all the height
  10085. } else if (display) {
  10086. minSize.height = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10087. }
  10088. // Don't bother fitting the ticks if we are not showing the labels
  10089. if (tickOpts.display && display) {
  10090. var tickFonts = parseTickFontOptions(tickOpts);
  10091. var labelSizes = me._getLabelSizes();
  10092. var firstLabelSize = labelSizes.first;
  10093. var lastLabelSize = labelSizes.last;
  10094. var widestLabelSize = labelSizes.widest;
  10095. var highestLabelSize = labelSizes.highest;
  10096. var lineSpace = tickFonts.minor.lineHeight * 0.4;
  10097. var tickPadding = tickOpts.padding;
  10098. if (isHorizontal) {
  10099. // A horizontal axis is more constrained by the height.
  10100. var isRotated = me.labelRotation !== 0;
  10101. var angleRadians = helpers$1.toRadians(me.labelRotation);
  10102. var cosRotation = Math.cos(angleRadians);
  10103. var sinRotation = Math.sin(angleRadians);
  10104. var labelHeight = sinRotation * widestLabelSize.width
  10105. + cosRotation * (highestLabelSize.height - (isRotated ? highestLabelSize.offset : 0))
  10106. + (isRotated ? 0 : lineSpace); // padding
  10107. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  10108. var offsetLeft = me.getPixelForTick(0) - me.left;
  10109. var offsetRight = me.right - me.getPixelForTick(me.getTicks().length - 1);
  10110. var paddingLeft, paddingRight;
  10111. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  10112. // which means that the right padding is dominated by the font height
  10113. if (isRotated) {
  10114. paddingLeft = isBottom ?
  10115. cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset :
  10116. sinRotation * (firstLabelSize.height - firstLabelSize.offset);
  10117. paddingRight = isBottom ?
  10118. sinRotation * (lastLabelSize.height - lastLabelSize.offset) :
  10119. cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset;
  10120. } else {
  10121. paddingLeft = firstLabelSize.width / 2;
  10122. paddingRight = lastLabelSize.width / 2;
  10123. }
  10124. // Adjust padding taking into account changes in offsets
  10125. // and add 3 px to move away from canvas edges
  10126. me.paddingLeft = Math.max((paddingLeft - offsetLeft) * me.width / (me.width - offsetLeft), 0) + 3;
  10127. me.paddingRight = Math.max((paddingRight - offsetRight) * me.width / (me.width - offsetRight), 0) + 3;
  10128. } else {
  10129. // A vertical axis is more constrained by the width. Labels are the
  10130. // dominant factor here, so get that length first and account for padding
  10131. var labelWidth = tickOpts.mirror ? 0 :
  10132. // use lineSpace for consistency with horizontal axis
  10133. // tickPadding is not implemented for horizontal
  10134. widestLabelSize.width + tickPadding + lineSpace;
  10135. minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth);
  10136. me.paddingTop = firstLabelSize.height / 2;
  10137. me.paddingBottom = lastLabelSize.height / 2;
  10138. }
  10139. }
  10140. me.handleMargins();
  10141. if (isHorizontal) {
  10142. me.width = me._length = chart.width - me.margins.left - me.margins.right;
  10143. me.height = minSize.height;
  10144. } else {
  10145. me.width = minSize.width;
  10146. me.height = me._length = chart.height - me.margins.top - me.margins.bottom;
  10147. }
  10148. },
  10149. /**
  10150. * Handle margins and padding interactions
  10151. * @private
  10152. */
  10153. handleMargins: function() {
  10154. var me = this;
  10155. if (me.margins) {
  10156. me.margins.left = Math.max(me.paddingLeft, me.margins.left);
  10157. me.margins.top = Math.max(me.paddingTop, me.margins.top);
  10158. me.margins.right = Math.max(me.paddingRight, me.margins.right);
  10159. me.margins.bottom = Math.max(me.paddingBottom, me.margins.bottom);
  10160. }
  10161. },
  10162. afterFit: function() {
  10163. helpers$1.callback(this.options.afterFit, [this]);
  10164. },
  10165. // Shared Methods
  10166. isHorizontal: function() {
  10167. var pos = this.options.position;
  10168. return pos === 'top' || pos === 'bottom';
  10169. },
  10170. isFullWidth: function() {
  10171. return this.options.fullWidth;
  10172. },
  10173. // 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
  10174. getRightValue: function(rawValue) {
  10175. // Null and undefined values first
  10176. if (isNullOrUndef(rawValue)) {
  10177. return NaN;
  10178. }
  10179. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  10180. if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
  10181. return NaN;
  10182. }
  10183. // If it is in fact an object, dive in one more level
  10184. if (rawValue) {
  10185. if (this.isHorizontal()) {
  10186. if (rawValue.x !== undefined) {
  10187. return this.getRightValue(rawValue.x);
  10188. }
  10189. } else if (rawValue.y !== undefined) {
  10190. return this.getRightValue(rawValue.y);
  10191. }
  10192. }
  10193. // Value is good, return it
  10194. return rawValue;
  10195. },
  10196. _convertTicksToLabels: function(ticks) {
  10197. var me = this;
  10198. var labels, i, ilen;
  10199. me.ticks = ticks.map(function(tick) {
  10200. return tick.value;
  10201. });
  10202. me.beforeTickToLabelConversion();
  10203. // New implementations should return the formatted tick labels but for BACKWARD
  10204. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  10205. // this method and supposed to contain only string values).
  10206. labels = me.convertTicksToLabels(ticks) || me.ticks;
  10207. me.afterTickToLabelConversion();
  10208. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  10209. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10210. ticks[i].label = labels[i];
  10211. }
  10212. return labels;
  10213. },
  10214. /**
  10215. * @private
  10216. */
  10217. _getLabelSizes: function() {
  10218. var me = this;
  10219. var labelSizes = me._labelSizes;
  10220. if (!labelSizes) {
  10221. me._labelSizes = labelSizes = computeLabelSizes(me.ctx, parseTickFontOptions(me.options.ticks), me.getTicks(), me.longestTextCache);
  10222. me.longestLabelWidth = labelSizes.widest.width;
  10223. }
  10224. return labelSizes;
  10225. },
  10226. /**
  10227. * @private
  10228. */
  10229. _parseValue: function(value) {
  10230. var start, end, min, max;
  10231. if (isArray(value)) {
  10232. start = +this.getRightValue(value[0]);
  10233. end = +this.getRightValue(value[1]);
  10234. min = Math.min(start, end);
  10235. max = Math.max(start, end);
  10236. } else {
  10237. value = +this.getRightValue(value);
  10238. start = undefined;
  10239. end = value;
  10240. min = value;
  10241. max = value;
  10242. }
  10243. return {
  10244. min: min,
  10245. max: max,
  10246. start: start,
  10247. end: end
  10248. };
  10249. },
  10250. /**
  10251. * @private
  10252. */
  10253. _getScaleLabel: function(rawValue) {
  10254. var v = this._parseValue(rawValue);
  10255. if (v.start !== undefined) {
  10256. return '[' + v.start + ', ' + v.end + ']';
  10257. }
  10258. return +this.getRightValue(rawValue);
  10259. },
  10260. /**
  10261. * Used to get the value to display in the tooltip for the data at the given index
  10262. * @param index
  10263. * @param datasetIndex
  10264. */
  10265. getLabelForIndex: helpers$1.noop,
  10266. /**
  10267. * Returns the location of the given data point. Value can either be an index or a numerical value
  10268. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10269. * @param value
  10270. * @param index
  10271. * @param datasetIndex
  10272. */
  10273. getPixelForValue: helpers$1.noop,
  10274. /**
  10275. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  10276. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10277. * @param pixel
  10278. */
  10279. getValueForPixel: helpers$1.noop,
  10280. /**
  10281. * Returns the location of the tick at the given index
  10282. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10283. */
  10284. getPixelForTick: function(index) {
  10285. var me = this;
  10286. var offset = me.options.offset;
  10287. var numTicks = me._ticks.length;
  10288. var tickWidth = 1 / Math.max(numTicks - (offset ? 0 : 1), 1);
  10289. return index < 0 || index > numTicks - 1
  10290. ? null
  10291. : me.getPixelForDecimal(index * tickWidth + (offset ? tickWidth / 2 : 0));
  10292. },
  10293. /**
  10294. * Utility for getting the pixel location of a percentage of scale
  10295. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10296. */
  10297. getPixelForDecimal: function(decimal) {
  10298. var me = this;
  10299. if (me._reversePixels) {
  10300. decimal = 1 - decimal;
  10301. }
  10302. return me._startPixel + decimal * me._length;
  10303. },
  10304. getDecimalForPixel: function(pixel) {
  10305. var decimal = (pixel - this._startPixel) / this._length;
  10306. return this._reversePixels ? 1 - decimal : decimal;
  10307. },
  10308. /**
  10309. * Returns the pixel for the minimum chart value
  10310. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10311. */
  10312. getBasePixel: function() {
  10313. return this.getPixelForValue(this.getBaseValue());
  10314. },
  10315. getBaseValue: function() {
  10316. var me = this;
  10317. var min = me.min;
  10318. var max = me.max;
  10319. return me.beginAtZero ? 0 :
  10320. min < 0 && max < 0 ? max :
  10321. min > 0 && max > 0 ? min :
  10322. 0;
  10323. },
  10324. /**
  10325. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  10326. * @private
  10327. */
  10328. _autoSkip: function(ticks) {
  10329. var me = this;
  10330. var tickOpts = me.options.ticks;
  10331. var axisLength = me._length;
  10332. var ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1;
  10333. var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  10334. var numMajorIndices = majorIndices.length;
  10335. var first = majorIndices[0];
  10336. var last = majorIndices[numMajorIndices - 1];
  10337. var i, ilen, spacing, avgMajorSpacing;
  10338. // If there are too many major ticks to display them all
  10339. if (numMajorIndices > ticksLimit) {
  10340. skipMajors(ticks, majorIndices, numMajorIndices / ticksLimit);
  10341. return nonSkipped(ticks);
  10342. }
  10343. spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit);
  10344. if (numMajorIndices > 0) {
  10345. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  10346. skip(ticks, spacing, majorIndices[i], majorIndices[i + 1]);
  10347. }
  10348. avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null;
  10349. skip(ticks, spacing, helpers$1.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  10350. skip(ticks, spacing, last, helpers$1.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  10351. return nonSkipped(ticks);
  10352. }
  10353. skip(ticks, spacing);
  10354. return nonSkipped(ticks);
  10355. },
  10356. /**
  10357. * @private
  10358. */
  10359. _tickSize: function() {
  10360. var me = this;
  10361. var optionTicks = me.options.ticks;
  10362. // Calculate space needed by label in axis direction.
  10363. var rot = helpers$1.toRadians(me.labelRotation);
  10364. var cos = Math.abs(Math.cos(rot));
  10365. var sin = Math.abs(Math.sin(rot));
  10366. var labelSizes = me._getLabelSizes();
  10367. var padding = optionTicks.autoSkipPadding || 0;
  10368. var w = labelSizes ? labelSizes.widest.width + padding : 0;
  10369. var h = labelSizes ? labelSizes.highest.height + padding : 0;
  10370. // Calculate space needed for 1 tick in axis direction.
  10371. return me.isHorizontal()
  10372. ? h * cos > w * sin ? w / cos : h / sin
  10373. : h * sin < w * cos ? h / cos : w / sin;
  10374. },
  10375. /**
  10376. * @private
  10377. */
  10378. _isVisible: function() {
  10379. var me = this;
  10380. var chart = me.chart;
  10381. var display = me.options.display;
  10382. var i, ilen, meta;
  10383. if (display !== 'auto') {
  10384. return !!display;
  10385. }
  10386. // When 'auto', the scale is visible if at least one associated dataset is visible.
  10387. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  10388. if (chart.isDatasetVisible(i)) {
  10389. meta = chart.getDatasetMeta(i);
  10390. if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
  10391. return true;
  10392. }
  10393. }
  10394. }
  10395. return false;
  10396. },
  10397. /**
  10398. * @private
  10399. */
  10400. _computeGridLineItems: function(chartArea) {
  10401. var me = this;
  10402. var chart = me.chart;
  10403. var options = me.options;
  10404. var gridLines = options.gridLines;
  10405. var position = options.position;
  10406. var offsetGridLines = gridLines.offsetGridLines;
  10407. var isHorizontal = me.isHorizontal();
  10408. var ticks = me._ticksToDraw;
  10409. var ticksLength = ticks.length + (offsetGridLines ? 1 : 0);
  10410. var tl = getTickMarkLength(gridLines);
  10411. var items = [];
  10412. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10413. var axisHalfWidth = axisWidth / 2;
  10414. var alignPixel = helpers$1._alignPixel;
  10415. var alignBorderValue = function(pixel) {
  10416. return alignPixel(chart, pixel, axisWidth);
  10417. };
  10418. var borderValue, i, tick, lineValue, alignedLineValue;
  10419. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, lineWidth, lineColor, borderDash, borderDashOffset;
  10420. if (position === 'top') {
  10421. borderValue = alignBorderValue(me.bottom);
  10422. ty1 = me.bottom - tl;
  10423. ty2 = borderValue - axisHalfWidth;
  10424. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  10425. y2 = chartArea.bottom;
  10426. } else if (position === 'bottom') {
  10427. borderValue = alignBorderValue(me.top);
  10428. y1 = chartArea.top;
  10429. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  10430. ty1 = borderValue + axisHalfWidth;
  10431. ty2 = me.top + tl;
  10432. } else if (position === 'left') {
  10433. borderValue = alignBorderValue(me.right);
  10434. tx1 = me.right - tl;
  10435. tx2 = borderValue - axisHalfWidth;
  10436. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  10437. x2 = chartArea.right;
  10438. } else {
  10439. borderValue = alignBorderValue(me.left);
  10440. x1 = chartArea.left;
  10441. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  10442. tx1 = borderValue + axisHalfWidth;
  10443. tx2 = me.left + tl;
  10444. }
  10445. for (i = 0; i < ticksLength; ++i) {
  10446. tick = ticks[i] || {};
  10447. // autoskipper skipped this tick (#4635)
  10448. if (isNullOrUndef(tick.label) && i < ticks.length) {
  10449. continue;
  10450. }
  10451. if (i === me.zeroLineIndex && options.offset === offsetGridLines) {
  10452. // Draw the first index specially
  10453. lineWidth = gridLines.zeroLineWidth;
  10454. lineColor = gridLines.zeroLineColor;
  10455. borderDash = gridLines.zeroLineBorderDash || [];
  10456. borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
  10457. } else {
  10458. lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, i, 1);
  10459. lineColor = valueAtIndexOrDefault(gridLines.color, i, 'rgba(0,0,0,0.1)');
  10460. borderDash = gridLines.borderDash || [];
  10461. borderDashOffset = gridLines.borderDashOffset || 0.0;
  10462. }
  10463. lineValue = getPixelForGridLine(me, tick._index || i, offsetGridLines);
  10464. // Skip if the pixel is out of the range
  10465. if (lineValue === undefined) {
  10466. continue;
  10467. }
  10468. alignedLineValue = alignPixel(chart, lineValue, lineWidth);
  10469. if (isHorizontal) {
  10470. tx1 = tx2 = x1 = x2 = alignedLineValue;
  10471. } else {
  10472. ty1 = ty2 = y1 = y2 = alignedLineValue;
  10473. }
  10474. items.push({
  10475. tx1: tx1,
  10476. ty1: ty1,
  10477. tx2: tx2,
  10478. ty2: ty2,
  10479. x1: x1,
  10480. y1: y1,
  10481. x2: x2,
  10482. y2: y2,
  10483. width: lineWidth,
  10484. color: lineColor,
  10485. borderDash: borderDash,
  10486. borderDashOffset: borderDashOffset,
  10487. });
  10488. }
  10489. items.ticksLength = ticksLength;
  10490. items.borderValue = borderValue;
  10491. return items;
  10492. },
  10493. /**
  10494. * @private
  10495. */
  10496. _computeLabelItems: function() {
  10497. var me = this;
  10498. var options = me.options;
  10499. var optionTicks = options.ticks;
  10500. var position = options.position;
  10501. var isMirrored = optionTicks.mirror;
  10502. var isHorizontal = me.isHorizontal();
  10503. var ticks = me._ticksToDraw;
  10504. var fonts = parseTickFontOptions(optionTicks);
  10505. var tickPadding = optionTicks.padding;
  10506. var tl = getTickMarkLength(options.gridLines);
  10507. var rotation = -helpers$1.toRadians(me.labelRotation);
  10508. var items = [];
  10509. var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  10510. if (position === 'top') {
  10511. y = me.bottom - tl - tickPadding;
  10512. textAlign = !rotation ? 'center' : 'left';
  10513. } else if (position === 'bottom') {
  10514. y = me.top + tl + tickPadding;
  10515. textAlign = !rotation ? 'center' : 'right';
  10516. } else if (position === 'left') {
  10517. x = me.right - (isMirrored ? 0 : tl) - tickPadding;
  10518. textAlign = isMirrored ? 'left' : 'right';
  10519. } else {
  10520. x = me.left + (isMirrored ? 0 : tl) + tickPadding;
  10521. textAlign = isMirrored ? 'right' : 'left';
  10522. }
  10523. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10524. tick = ticks[i];
  10525. label = tick.label;
  10526. // autoskipper skipped this tick (#4635)
  10527. if (isNullOrUndef(label)) {
  10528. continue;
  10529. }
  10530. pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset;
  10531. font = tick.major ? fonts.major : fonts.minor;
  10532. lineHeight = font.lineHeight;
  10533. lineCount = isArray(label) ? label.length : 1;
  10534. if (isHorizontal) {
  10535. x = pixel;
  10536. textOffset = position === 'top'
  10537. ? ((!rotation ? 0.5 : 1) - lineCount) * lineHeight
  10538. : (!rotation ? 0.5 : 0) * lineHeight;
  10539. } else {
  10540. y = pixel;
  10541. textOffset = (1 - lineCount) * lineHeight / 2;
  10542. }
  10543. items.push({
  10544. x: x,
  10545. y: y,
  10546. rotation: rotation,
  10547. label: label,
  10548. font: font,
  10549. textOffset: textOffset,
  10550. textAlign: textAlign
  10551. });
  10552. }
  10553. return items;
  10554. },
  10555. /**
  10556. * @private
  10557. */
  10558. _drawGrid: function(chartArea) {
  10559. var me = this;
  10560. var gridLines = me.options.gridLines;
  10561. if (!gridLines.display) {
  10562. return;
  10563. }
  10564. var ctx = me.ctx;
  10565. var chart = me.chart;
  10566. var alignPixel = helpers$1._alignPixel;
  10567. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10568. var items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
  10569. var width, color, i, ilen, item;
  10570. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10571. item = items[i];
  10572. width = item.width;
  10573. color = item.color;
  10574. if (width && color) {
  10575. ctx.save();
  10576. ctx.lineWidth = width;
  10577. ctx.strokeStyle = color;
  10578. if (ctx.setLineDash) {
  10579. ctx.setLineDash(item.borderDash);
  10580. ctx.lineDashOffset = item.borderDashOffset;
  10581. }
  10582. ctx.beginPath();
  10583. if (gridLines.drawTicks) {
  10584. ctx.moveTo(item.tx1, item.ty1);
  10585. ctx.lineTo(item.tx2, item.ty2);
  10586. }
  10587. if (gridLines.drawOnChartArea) {
  10588. ctx.moveTo(item.x1, item.y1);
  10589. ctx.lineTo(item.x2, item.y2);
  10590. }
  10591. ctx.stroke();
  10592. ctx.restore();
  10593. }
  10594. }
  10595. if (axisWidth) {
  10596. // Draw the line at the edge of the axis
  10597. var firstLineWidth = axisWidth;
  10598. var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, items.ticksLength - 1, 1);
  10599. var borderValue = items.borderValue;
  10600. var x1, x2, y1, y2;
  10601. if (me.isHorizontal()) {
  10602. x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
  10603. x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  10604. y1 = y2 = borderValue;
  10605. } else {
  10606. y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
  10607. y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  10608. x1 = x2 = borderValue;
  10609. }
  10610. ctx.lineWidth = axisWidth;
  10611. ctx.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
  10612. ctx.beginPath();
  10613. ctx.moveTo(x1, y1);
  10614. ctx.lineTo(x2, y2);
  10615. ctx.stroke();
  10616. }
  10617. },
  10618. /**
  10619. * @private
  10620. */
  10621. _drawLabels: function() {
  10622. var me = this;
  10623. var optionTicks = me.options.ticks;
  10624. if (!optionTicks.display) {
  10625. return;
  10626. }
  10627. var ctx = me.ctx;
  10628. var items = me._labelItems || (me._labelItems = me._computeLabelItems());
  10629. var i, j, ilen, jlen, item, tickFont, label, y;
  10630. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10631. item = items[i];
  10632. tickFont = item.font;
  10633. // Make sure we draw text in the correct color and font
  10634. ctx.save();
  10635. ctx.translate(item.x, item.y);
  10636. ctx.rotate(item.rotation);
  10637. ctx.font = tickFont.string;
  10638. ctx.fillStyle = tickFont.color;
  10639. ctx.textBaseline = 'middle';
  10640. ctx.textAlign = item.textAlign;
  10641. label = item.label;
  10642. y = item.textOffset;
  10643. if (isArray(label)) {
  10644. for (j = 0, jlen = label.length; j < jlen; ++j) {
  10645. // We just make sure the multiline element is a string here..
  10646. ctx.fillText('' + label[j], 0, y);
  10647. y += tickFont.lineHeight;
  10648. }
  10649. } else {
  10650. ctx.fillText(label, 0, y);
  10651. }
  10652. ctx.restore();
  10653. }
  10654. },
  10655. /**
  10656. * @private
  10657. */
  10658. _drawTitle: function() {
  10659. var me = this;
  10660. var ctx = me.ctx;
  10661. var options = me.options;
  10662. var scaleLabel = options.scaleLabel;
  10663. if (!scaleLabel.display) {
  10664. return;
  10665. }
  10666. var scaleLabelFontColor = valueOrDefault$a(scaleLabel.fontColor, core_defaults.global.defaultFontColor);
  10667. var scaleLabelFont = helpers$1.options._parseFont(scaleLabel);
  10668. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
  10669. var halfLineHeight = scaleLabelFont.lineHeight / 2;
  10670. var position = options.position;
  10671. var rotation = 0;
  10672. var scaleLabelX, scaleLabelY;
  10673. if (me.isHorizontal()) {
  10674. scaleLabelX = me.left + me.width / 2; // midpoint of the width
  10675. scaleLabelY = position === 'bottom'
  10676. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  10677. : me.top + halfLineHeight + scaleLabelPadding.top;
  10678. } else {
  10679. var isLeft = position === 'left';
  10680. scaleLabelX = isLeft
  10681. ? me.left + halfLineHeight + scaleLabelPadding.top
  10682. : me.right - halfLineHeight - scaleLabelPadding.top;
  10683. scaleLabelY = me.top + me.height / 2;
  10684. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  10685. }
  10686. ctx.save();
  10687. ctx.translate(scaleLabelX, scaleLabelY);
  10688. ctx.rotate(rotation);
  10689. ctx.textAlign = 'center';
  10690. ctx.textBaseline = 'middle';
  10691. ctx.fillStyle = scaleLabelFontColor; // render in correct colour
  10692. ctx.font = scaleLabelFont.string;
  10693. ctx.fillText(scaleLabel.labelString, 0, 0);
  10694. ctx.restore();
  10695. },
  10696. draw: function(chartArea) {
  10697. var me = this;
  10698. if (!me._isVisible()) {
  10699. return;
  10700. }
  10701. me._drawGrid(chartArea);
  10702. me._drawTitle();
  10703. me._drawLabels();
  10704. },
  10705. /**
  10706. * @private
  10707. */
  10708. _layers: function() {
  10709. var me = this;
  10710. var opts = me.options;
  10711. var tz = opts.ticks && opts.ticks.z || 0;
  10712. var gz = opts.gridLines && opts.gridLines.z || 0;
  10713. if (!me._isVisible() || tz === gz || me.draw !== me._draw) {
  10714. // backward compatibility: draw has been overridden by custom scale
  10715. return [{
  10716. z: tz,
  10717. draw: function() {
  10718. me.draw.apply(me, arguments);
  10719. }
  10720. }];
  10721. }
  10722. return [{
  10723. z: gz,
  10724. draw: function() {
  10725. me._drawGrid.apply(me, arguments);
  10726. me._drawTitle.apply(me, arguments);
  10727. }
  10728. }, {
  10729. z: tz,
  10730. draw: function() {
  10731. me._drawLabels.apply(me, arguments);
  10732. }
  10733. }];
  10734. },
  10735. /**
  10736. * @private
  10737. */
  10738. _getMatchingVisibleMetas: function(type) {
  10739. var me = this;
  10740. var isHorizontal = me.isHorizontal();
  10741. return me.chart._getSortedVisibleDatasetMetas()
  10742. .filter(function(meta) {
  10743. return (!type || meta.type === type)
  10744. && (isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id);
  10745. });
  10746. }
  10747. });
  10748. Scale.prototype._draw = Scale.prototype.draw;
  10749. var core_scale = Scale;
  10750. var isNullOrUndef$1 = helpers$1.isNullOrUndef;
  10751. var defaultConfig = {
  10752. position: 'bottom'
  10753. };
  10754. var scale_category = core_scale.extend({
  10755. determineDataLimits: function() {
  10756. var me = this;
  10757. var labels = me._getLabels();
  10758. var ticksOpts = me.options.ticks;
  10759. var min = ticksOpts.min;
  10760. var max = ticksOpts.max;
  10761. var minIndex = 0;
  10762. var maxIndex = labels.length - 1;
  10763. var findIndex;
  10764. if (min !== undefined) {
  10765. // user specified min value
  10766. findIndex = labels.indexOf(min);
  10767. if (findIndex >= 0) {
  10768. minIndex = findIndex;
  10769. }
  10770. }
  10771. if (max !== undefined) {
  10772. // user specified max value
  10773. findIndex = labels.indexOf(max);
  10774. if (findIndex >= 0) {
  10775. maxIndex = findIndex;
  10776. }
  10777. }
  10778. me.minIndex = minIndex;
  10779. me.maxIndex = maxIndex;
  10780. me.min = labels[minIndex];
  10781. me.max = labels[maxIndex];
  10782. },
  10783. buildTicks: function() {
  10784. var me = this;
  10785. var labels = me._getLabels();
  10786. var minIndex = me.minIndex;
  10787. var maxIndex = me.maxIndex;
  10788. // If we are viewing some subset of labels, slice the original array
  10789. me.ticks = (minIndex === 0 && maxIndex === labels.length - 1) ? labels : labels.slice(minIndex, maxIndex + 1);
  10790. },
  10791. getLabelForIndex: function(index, datasetIndex) {
  10792. var me = this;
  10793. var chart = me.chart;
  10794. if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {
  10795. return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);
  10796. }
  10797. return me._getLabels()[index];
  10798. },
  10799. _configure: function() {
  10800. var me = this;
  10801. var offset = me.options.offset;
  10802. var ticks = me.ticks;
  10803. core_scale.prototype._configure.call(me);
  10804. if (!me.isHorizontal()) {
  10805. // For backward compatibility, vertical category scale reverse is inverted.
  10806. me._reversePixels = !me._reversePixels;
  10807. }
  10808. if (!ticks) {
  10809. return;
  10810. }
  10811. me._startValue = me.minIndex - (offset ? 0.5 : 0);
  10812. me._valueRange = Math.max(ticks.length - (offset ? 0 : 1), 1);
  10813. },
  10814. // Used to get data value locations. Value can either be an index or a numerical value
  10815. getPixelForValue: function(value, index, datasetIndex) {
  10816. var me = this;
  10817. var valueCategory, labels, idx;
  10818. if (!isNullOrUndef$1(index) && !isNullOrUndef$1(datasetIndex)) {
  10819. value = me.chart.data.datasets[datasetIndex].data[index];
  10820. }
  10821. // If value is a data object, then index is the index in the data array,
  10822. // not the index of the scale. We need to change that.
  10823. if (!isNullOrUndef$1(value)) {
  10824. valueCategory = me.isHorizontal() ? value.x : value.y;
  10825. }
  10826. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  10827. labels = me._getLabels();
  10828. value = helpers$1.valueOrDefault(valueCategory, value);
  10829. idx = labels.indexOf(value);
  10830. index = idx !== -1 ? idx : index;
  10831. if (isNaN(index)) {
  10832. index = value;
  10833. }
  10834. }
  10835. return me.getPixelForDecimal((index - me._startValue) / me._valueRange);
  10836. },
  10837. getPixelForTick: function(index) {
  10838. var ticks = this.ticks;
  10839. return index < 0 || index > ticks.length - 1
  10840. ? null
  10841. : this.getPixelForValue(ticks[index], index + this.minIndex);
  10842. },
  10843. getValueForPixel: function(pixel) {
  10844. var me = this;
  10845. var value = Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
  10846. return Math.min(Math.max(value, 0), me.ticks.length - 1);
  10847. },
  10848. getBasePixel: function() {
  10849. return this.bottom;
  10850. }
  10851. });
  10852. // INTERNAL: static default options, registered in src/index.js
  10853. var _defaults = defaultConfig;
  10854. scale_category._defaults = _defaults;
  10855. var noop = helpers$1.noop;
  10856. var isNullOrUndef$2 = helpers$1.isNullOrUndef;
  10857. /**
  10858. * Generate a set of linear ticks
  10859. * @param generationOptions the options used to generate the ticks
  10860. * @param dataRange the range of the data
  10861. * @returns {number[]} array of tick values
  10862. */
  10863. function generateTicks(generationOptions, dataRange) {
  10864. var ticks = [];
  10865. // To get a "nice" value for the tick spacing, we will use the appropriately named
  10866. // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  10867. // for details.
  10868. var MIN_SPACING = 1e-14;
  10869. var stepSize = generationOptions.stepSize;
  10870. var unit = stepSize || 1;
  10871. var maxNumSpaces = generationOptions.maxTicks - 1;
  10872. var min = generationOptions.min;
  10873. var max = generationOptions.max;
  10874. var precision = generationOptions.precision;
  10875. var rmin = dataRange.min;
  10876. var rmax = dataRange.max;
  10877. var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
  10878. var factor, niceMin, niceMax, numSpaces;
  10879. // Beyond MIN_SPACING floating point numbers being to lose precision
  10880. // such that we can't do the math necessary to generate ticks
  10881. if (spacing < MIN_SPACING && isNullOrUndef$2(min) && isNullOrUndef$2(max)) {
  10882. return [rmin, rmax];
  10883. }
  10884. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  10885. if (numSpaces > maxNumSpaces) {
  10886. // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
  10887. spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
  10888. }
  10889. if (stepSize || isNullOrUndef$2(precision)) {
  10890. // If a precision is not specified, calculate factor based on spacing
  10891. factor = Math.pow(10, helpers$1._decimalPlaces(spacing));
  10892. } else {
  10893. // If the user specified a precision, round to that number of decimal places
  10894. factor = Math.pow(10, precision);
  10895. spacing = Math.ceil(spacing * factor) / factor;
  10896. }
  10897. niceMin = Math.floor(rmin / spacing) * spacing;
  10898. niceMax = Math.ceil(rmax / spacing) * spacing;
  10899. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  10900. if (stepSize) {
  10901. // If very close to our whole number, use it.
  10902. if (!isNullOrUndef$2(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
  10903. niceMin = min;
  10904. }
  10905. if (!isNullOrUndef$2(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
  10906. niceMax = max;
  10907. }
  10908. }
  10909. numSpaces = (niceMax - niceMin) / spacing;
  10910. // If very close to our rounded value, use it.
  10911. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  10912. numSpaces = Math.round(numSpaces);
  10913. } else {
  10914. numSpaces = Math.ceil(numSpaces);
  10915. }
  10916. niceMin = Math.round(niceMin * factor) / factor;
  10917. niceMax = Math.round(niceMax * factor) / factor;
  10918. ticks.push(isNullOrUndef$2(min) ? niceMin : min);
  10919. for (var j = 1; j < numSpaces; ++j) {
  10920. ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
  10921. }
  10922. ticks.push(isNullOrUndef$2(max) ? niceMax : max);
  10923. return ticks;
  10924. }
  10925. var scale_linearbase = core_scale.extend({
  10926. getRightValue: function(value) {
  10927. if (typeof value === 'string') {
  10928. return +value;
  10929. }
  10930. return core_scale.prototype.getRightValue.call(this, value);
  10931. },
  10932. handleTickRangeOptions: function() {
  10933. var me = this;
  10934. var opts = me.options;
  10935. var tickOpts = opts.ticks;
  10936. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  10937. // do nothing since that would make the chart weird. If the user really wants a weird chart
  10938. // axis, they can manually override it
  10939. if (tickOpts.beginAtZero) {
  10940. var minSign = helpers$1.sign(me.min);
  10941. var maxSign = helpers$1.sign(me.max);
  10942. if (minSign < 0 && maxSign < 0) {
  10943. // move the top up to 0
  10944. me.max = 0;
  10945. } else if (minSign > 0 && maxSign > 0) {
  10946. // move the bottom down to 0
  10947. me.min = 0;
  10948. }
  10949. }
  10950. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  10951. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  10952. if (tickOpts.min !== undefined) {
  10953. me.min = tickOpts.min;
  10954. } else if (tickOpts.suggestedMin !== undefined) {
  10955. if (me.min === null) {
  10956. me.min = tickOpts.suggestedMin;
  10957. } else {
  10958. me.min = Math.min(me.min, tickOpts.suggestedMin);
  10959. }
  10960. }
  10961. if (tickOpts.max !== undefined) {
  10962. me.max = tickOpts.max;
  10963. } else if (tickOpts.suggestedMax !== undefined) {
  10964. if (me.max === null) {
  10965. me.max = tickOpts.suggestedMax;
  10966. } else {
  10967. me.max = Math.max(me.max, tickOpts.suggestedMax);
  10968. }
  10969. }
  10970. if (setMin !== setMax) {
  10971. // We set the min or the max but not both.
  10972. // So ensure that our range is good
  10973. // Inverted or 0 length range can happen when
  10974. // ticks.min is set, and no datasets are visible
  10975. if (me.min >= me.max) {
  10976. if (setMin) {
  10977. me.max = me.min + 1;
  10978. } else {
  10979. me.min = me.max - 1;
  10980. }
  10981. }
  10982. }
  10983. if (me.min === me.max) {
  10984. me.max++;
  10985. if (!tickOpts.beginAtZero) {
  10986. me.min--;
  10987. }
  10988. }
  10989. },
  10990. getTickLimit: function() {
  10991. var me = this;
  10992. var tickOpts = me.options.ticks;
  10993. var stepSize = tickOpts.stepSize;
  10994. var maxTicksLimit = tickOpts.maxTicksLimit;
  10995. var maxTicks;
  10996. if (stepSize) {
  10997. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  10998. } else {
  10999. maxTicks = me._computeTickLimit();
  11000. maxTicksLimit = maxTicksLimit || 11;
  11001. }
  11002. if (maxTicksLimit) {
  11003. maxTicks = Math.min(maxTicksLimit, maxTicks);
  11004. }
  11005. return maxTicks;
  11006. },
  11007. _computeTickLimit: function() {
  11008. return Number.POSITIVE_INFINITY;
  11009. },
  11010. handleDirectionalChanges: noop,
  11011. buildTicks: function() {
  11012. var me = this;
  11013. var opts = me.options;
  11014. var tickOpts = opts.ticks;
  11015. // Figure out what the max number of ticks we can support it is based on the size of
  11016. // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
  11017. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  11018. // the graph. Make sure we always have at least 2 ticks
  11019. var maxTicks = me.getTickLimit();
  11020. maxTicks = Math.max(2, maxTicks);
  11021. var numericGeneratorOptions = {
  11022. maxTicks: maxTicks,
  11023. min: tickOpts.min,
  11024. max: tickOpts.max,
  11025. precision: tickOpts.precision,
  11026. stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  11027. };
  11028. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  11029. me.handleDirectionalChanges();
  11030. // At this point, we need to update our max and min given the tick values since we have expanded the
  11031. // range of the scale
  11032. me.max = helpers$1.max(ticks);
  11033. me.min = helpers$1.min(ticks);
  11034. if (tickOpts.reverse) {
  11035. ticks.reverse();
  11036. me.start = me.max;
  11037. me.end = me.min;
  11038. } else {
  11039. me.start = me.min;
  11040. me.end = me.max;
  11041. }
  11042. },
  11043. convertTicksToLabels: function() {
  11044. var me = this;
  11045. me.ticksAsNumbers = me.ticks.slice();
  11046. me.zeroLineIndex = me.ticks.indexOf(0);
  11047. core_scale.prototype.convertTicksToLabels.call(me);
  11048. },
  11049. _configure: function() {
  11050. var me = this;
  11051. var ticks = me.getTicks();
  11052. var start = me.min;
  11053. var end = me.max;
  11054. var offset;
  11055. core_scale.prototype._configure.call(me);
  11056. if (me.options.offset && ticks.length) {
  11057. offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  11058. start -= offset;
  11059. end += offset;
  11060. }
  11061. me._startValue = start;
  11062. me._endValue = end;
  11063. me._valueRange = end - start;
  11064. }
  11065. });
  11066. var defaultConfig$1 = {
  11067. position: 'left',
  11068. ticks: {
  11069. callback: core_ticks.formatters.linear
  11070. }
  11071. };
  11072. var DEFAULT_MIN = 0;
  11073. var DEFAULT_MAX = 1;
  11074. function getOrCreateStack(stacks, stacked, meta) {
  11075. var key = [
  11076. meta.type,
  11077. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11078. stacked === undefined && meta.stack === undefined ? meta.index : '',
  11079. meta.stack
  11080. ].join('.');
  11081. if (stacks[key] === undefined) {
  11082. stacks[key] = {
  11083. pos: [],
  11084. neg: []
  11085. };
  11086. }
  11087. return stacks[key];
  11088. }
  11089. function stackData(scale, stacks, meta, data) {
  11090. var opts = scale.options;
  11091. var stacked = opts.stacked;
  11092. var stack = getOrCreateStack(stacks, stacked, meta);
  11093. var pos = stack.pos;
  11094. var neg = stack.neg;
  11095. var ilen = data.length;
  11096. var i, value;
  11097. for (i = 0; i < ilen; ++i) {
  11098. value = scale._parseValue(data[i]);
  11099. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11100. continue;
  11101. }
  11102. pos[i] = pos[i] || 0;
  11103. neg[i] = neg[i] || 0;
  11104. if (opts.relativePoints) {
  11105. pos[i] = 100;
  11106. } else if (value.min < 0 || value.max < 0) {
  11107. neg[i] += value.min;
  11108. } else {
  11109. pos[i] += value.max;
  11110. }
  11111. }
  11112. }
  11113. function updateMinMax(scale, meta, data) {
  11114. var ilen = data.length;
  11115. var i, value;
  11116. for (i = 0; i < ilen; ++i) {
  11117. value = scale._parseValue(data[i]);
  11118. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11119. continue;
  11120. }
  11121. scale.min = Math.min(scale.min, value.min);
  11122. scale.max = Math.max(scale.max, value.max);
  11123. }
  11124. }
  11125. var scale_linear = scale_linearbase.extend({
  11126. determineDataLimits: function() {
  11127. var me = this;
  11128. var opts = me.options;
  11129. var chart = me.chart;
  11130. var datasets = chart.data.datasets;
  11131. var metasets = me._getMatchingVisibleMetas();
  11132. var hasStacks = opts.stacked;
  11133. var stacks = {};
  11134. var ilen = metasets.length;
  11135. var i, meta, data, values;
  11136. me.min = Number.POSITIVE_INFINITY;
  11137. me.max = Number.NEGATIVE_INFINITY;
  11138. if (hasStacks === undefined) {
  11139. for (i = 0; !hasStacks && i < ilen; ++i) {
  11140. meta = metasets[i];
  11141. hasStacks = meta.stack !== undefined;
  11142. }
  11143. }
  11144. for (i = 0; i < ilen; ++i) {
  11145. meta = metasets[i];
  11146. data = datasets[meta.index].data;
  11147. if (hasStacks) {
  11148. stackData(me, stacks, meta, data);
  11149. } else {
  11150. updateMinMax(me, meta, data);
  11151. }
  11152. }
  11153. helpers$1.each(stacks, function(stackValues) {
  11154. values = stackValues.pos.concat(stackValues.neg);
  11155. me.min = Math.min(me.min, helpers$1.min(values));
  11156. me.max = Math.max(me.max, helpers$1.max(values));
  11157. });
  11158. me.min = helpers$1.isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  11159. me.max = helpers$1.isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  11160. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11161. me.handleTickRangeOptions();
  11162. },
  11163. // Returns the maximum number of ticks based on the scale dimension
  11164. _computeTickLimit: function() {
  11165. var me = this;
  11166. var tickFont;
  11167. if (me.isHorizontal()) {
  11168. return Math.ceil(me.width / 40);
  11169. }
  11170. tickFont = helpers$1.options._parseFont(me.options.ticks);
  11171. return Math.ceil(me.height / tickFont.lineHeight);
  11172. },
  11173. // Called after the ticks are built. We need
  11174. handleDirectionalChanges: function() {
  11175. if (!this.isHorizontal()) {
  11176. // We are in a vertical orientation. The top value is the highest. So reverse the array
  11177. this.ticks.reverse();
  11178. }
  11179. },
  11180. getLabelForIndex: function(index, datasetIndex) {
  11181. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11182. },
  11183. // Utils
  11184. getPixelForValue: function(value) {
  11185. var me = this;
  11186. return me.getPixelForDecimal((+me.getRightValue(value) - me._startValue) / me._valueRange);
  11187. },
  11188. getValueForPixel: function(pixel) {
  11189. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  11190. },
  11191. getPixelForTick: function(index) {
  11192. var ticks = this.ticksAsNumbers;
  11193. if (index < 0 || index > ticks.length - 1) {
  11194. return null;
  11195. }
  11196. return this.getPixelForValue(ticks[index]);
  11197. }
  11198. });
  11199. // INTERNAL: static default options, registered in src/index.js
  11200. var _defaults$1 = defaultConfig$1;
  11201. scale_linear._defaults = _defaults$1;
  11202. var valueOrDefault$b = helpers$1.valueOrDefault;
  11203. var log10 = helpers$1.math.log10;
  11204. /**
  11205. * Generate a set of logarithmic ticks
  11206. * @param generationOptions the options used to generate the ticks
  11207. * @param dataRange the range of the data
  11208. * @returns {number[]} array of tick values
  11209. */
  11210. function generateTicks$1(generationOptions, dataRange) {
  11211. var ticks = [];
  11212. var tickVal = valueOrDefault$b(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  11213. var endExp = Math.floor(log10(dataRange.max));
  11214. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  11215. var exp, significand;
  11216. if (tickVal === 0) {
  11217. exp = Math.floor(log10(dataRange.minNotZero));
  11218. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  11219. ticks.push(tickVal);
  11220. tickVal = significand * Math.pow(10, exp);
  11221. } else {
  11222. exp = Math.floor(log10(tickVal));
  11223. significand = Math.floor(tickVal / Math.pow(10, exp));
  11224. }
  11225. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  11226. do {
  11227. ticks.push(tickVal);
  11228. ++significand;
  11229. if (significand === 10) {
  11230. significand = 1;
  11231. ++exp;
  11232. precision = exp >= 0 ? 1 : precision;
  11233. }
  11234. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  11235. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  11236. var lastTick = valueOrDefault$b(generationOptions.max, tickVal);
  11237. ticks.push(lastTick);
  11238. return ticks;
  11239. }
  11240. var defaultConfig$2 = {
  11241. position: 'left',
  11242. // label settings
  11243. ticks: {
  11244. callback: core_ticks.formatters.logarithmic
  11245. }
  11246. };
  11247. // TODO(v3): change this to positiveOrDefault
  11248. function nonNegativeOrDefault(value, defaultValue) {
  11249. return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;
  11250. }
  11251. var scale_logarithmic = core_scale.extend({
  11252. determineDataLimits: function() {
  11253. var me = this;
  11254. var opts = me.options;
  11255. var chart = me.chart;
  11256. var datasets = chart.data.datasets;
  11257. var isHorizontal = me.isHorizontal();
  11258. function IDMatches(meta) {
  11259. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  11260. }
  11261. var datasetIndex, meta, value, data, i, ilen;
  11262. // Calculate Range
  11263. me.min = Number.POSITIVE_INFINITY;
  11264. me.max = Number.NEGATIVE_INFINITY;
  11265. me.minNotZero = Number.POSITIVE_INFINITY;
  11266. var hasStacks = opts.stacked;
  11267. if (hasStacks === undefined) {
  11268. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11269. meta = chart.getDatasetMeta(datasetIndex);
  11270. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  11271. meta.stack !== undefined) {
  11272. hasStacks = true;
  11273. break;
  11274. }
  11275. }
  11276. }
  11277. if (opts.stacked || hasStacks) {
  11278. var valuesPerStack = {};
  11279. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11280. meta = chart.getDatasetMeta(datasetIndex);
  11281. var key = [
  11282. meta.type,
  11283. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11284. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  11285. meta.stack
  11286. ].join('.');
  11287. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11288. if (valuesPerStack[key] === undefined) {
  11289. valuesPerStack[key] = [];
  11290. }
  11291. data = datasets[datasetIndex].data;
  11292. for (i = 0, ilen = data.length; i < ilen; i++) {
  11293. var values = valuesPerStack[key];
  11294. value = me._parseValue(data[i]);
  11295. // invalid, hidden and negative values are ignored
  11296. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11297. continue;
  11298. }
  11299. values[i] = values[i] || 0;
  11300. values[i] += value.max;
  11301. }
  11302. }
  11303. }
  11304. helpers$1.each(valuesPerStack, function(valuesForType) {
  11305. if (valuesForType.length > 0) {
  11306. var minVal = helpers$1.min(valuesForType);
  11307. var maxVal = helpers$1.max(valuesForType);
  11308. me.min = Math.min(me.min, minVal);
  11309. me.max = Math.max(me.max, maxVal);
  11310. }
  11311. });
  11312. } else {
  11313. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11314. meta = chart.getDatasetMeta(datasetIndex);
  11315. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11316. data = datasets[datasetIndex].data;
  11317. for (i = 0, ilen = data.length; i < ilen; i++) {
  11318. value = me._parseValue(data[i]);
  11319. // invalid, hidden and negative values are ignored
  11320. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11321. continue;
  11322. }
  11323. me.min = Math.min(value.min, me.min);
  11324. me.max = Math.max(value.max, me.max);
  11325. if (value.min !== 0) {
  11326. me.minNotZero = Math.min(value.min, me.minNotZero);
  11327. }
  11328. }
  11329. }
  11330. }
  11331. }
  11332. me.min = helpers$1.isFinite(me.min) ? me.min : null;
  11333. me.max = helpers$1.isFinite(me.max) ? me.max : null;
  11334. me.minNotZero = helpers$1.isFinite(me.minNotZero) ? me.minNotZero : null;
  11335. // Common base implementation to handle ticks.min, ticks.max
  11336. this.handleTickRangeOptions();
  11337. },
  11338. handleTickRangeOptions: function() {
  11339. var me = this;
  11340. var tickOpts = me.options.ticks;
  11341. var DEFAULT_MIN = 1;
  11342. var DEFAULT_MAX = 10;
  11343. me.min = nonNegativeOrDefault(tickOpts.min, me.min);
  11344. me.max = nonNegativeOrDefault(tickOpts.max, me.max);
  11345. if (me.min === me.max) {
  11346. if (me.min !== 0 && me.min !== null) {
  11347. me.min = Math.pow(10, Math.floor(log10(me.min)) - 1);
  11348. me.max = Math.pow(10, Math.floor(log10(me.max)) + 1);
  11349. } else {
  11350. me.min = DEFAULT_MIN;
  11351. me.max = DEFAULT_MAX;
  11352. }
  11353. }
  11354. if (me.min === null) {
  11355. me.min = Math.pow(10, Math.floor(log10(me.max)) - 1);
  11356. }
  11357. if (me.max === null) {
  11358. me.max = me.min !== 0
  11359. ? Math.pow(10, Math.floor(log10(me.min)) + 1)
  11360. : DEFAULT_MAX;
  11361. }
  11362. if (me.minNotZero === null) {
  11363. if (me.min > 0) {
  11364. me.minNotZero = me.min;
  11365. } else if (me.max < 1) {
  11366. me.minNotZero = Math.pow(10, Math.floor(log10(me.max)));
  11367. } else {
  11368. me.minNotZero = DEFAULT_MIN;
  11369. }
  11370. }
  11371. },
  11372. buildTicks: function() {
  11373. var me = this;
  11374. var tickOpts = me.options.ticks;
  11375. var reverse = !me.isHorizontal();
  11376. var generationOptions = {
  11377. min: nonNegativeOrDefault(tickOpts.min),
  11378. max: nonNegativeOrDefault(tickOpts.max)
  11379. };
  11380. var ticks = me.ticks = generateTicks$1(generationOptions, me);
  11381. // At this point, we need to update our max and min given the tick values since we have expanded the
  11382. // range of the scale
  11383. me.max = helpers$1.max(ticks);
  11384. me.min = helpers$1.min(ticks);
  11385. if (tickOpts.reverse) {
  11386. reverse = !reverse;
  11387. me.start = me.max;
  11388. me.end = me.min;
  11389. } else {
  11390. me.start = me.min;
  11391. me.end = me.max;
  11392. }
  11393. if (reverse) {
  11394. ticks.reverse();
  11395. }
  11396. },
  11397. convertTicksToLabels: function() {
  11398. this.tickValues = this.ticks.slice();
  11399. core_scale.prototype.convertTicksToLabels.call(this);
  11400. },
  11401. // Get the correct tooltip label
  11402. getLabelForIndex: function(index, datasetIndex) {
  11403. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11404. },
  11405. getPixelForTick: function(index) {
  11406. var ticks = this.tickValues;
  11407. if (index < 0 || index > ticks.length - 1) {
  11408. return null;
  11409. }
  11410. return this.getPixelForValue(ticks[index]);
  11411. },
  11412. /**
  11413. * Returns the value of the first tick.
  11414. * @param {number} value - The minimum not zero value.
  11415. * @return {number} The first tick value.
  11416. * @private
  11417. */
  11418. _getFirstTickValue: function(value) {
  11419. var exp = Math.floor(log10(value));
  11420. var significand = Math.floor(value / Math.pow(10, exp));
  11421. return significand * Math.pow(10, exp);
  11422. },
  11423. _configure: function() {
  11424. var me = this;
  11425. var start = me.min;
  11426. var offset = 0;
  11427. core_scale.prototype._configure.call(me);
  11428. if (start === 0) {
  11429. start = me._getFirstTickValue(me.minNotZero);
  11430. offset = valueOrDefault$b(me.options.ticks.fontSize, core_defaults.global.defaultFontSize) / me._length;
  11431. }
  11432. me._startValue = log10(start);
  11433. me._valueOffset = offset;
  11434. me._valueRange = (log10(me.max) - log10(start)) / (1 - offset);
  11435. },
  11436. getPixelForValue: function(value) {
  11437. var me = this;
  11438. var decimal = 0;
  11439. value = +me.getRightValue(value);
  11440. if (value > me.min && value > 0) {
  11441. decimal = (log10(value) - me._startValue) / me._valueRange + me._valueOffset;
  11442. }
  11443. return me.getPixelForDecimal(decimal);
  11444. },
  11445. getValueForPixel: function(pixel) {
  11446. var me = this;
  11447. var decimal = me.getDecimalForPixel(pixel);
  11448. return decimal === 0 && me.min === 0
  11449. ? 0
  11450. : Math.pow(10, me._startValue + (decimal - me._valueOffset) * me._valueRange);
  11451. }
  11452. });
  11453. // INTERNAL: static default options, registered in src/index.js
  11454. var _defaults$2 = defaultConfig$2;
  11455. scale_logarithmic._defaults = _defaults$2;
  11456. var valueOrDefault$c = helpers$1.valueOrDefault;
  11457. var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
  11458. var resolve$4 = helpers$1.options.resolve;
  11459. var defaultConfig$3 = {
  11460. display: true,
  11461. // Boolean - Whether to animate scaling the chart from the centre
  11462. animate: true,
  11463. position: 'chartArea',
  11464. angleLines: {
  11465. display: true,
  11466. color: 'rgba(0,0,0,0.1)',
  11467. lineWidth: 1,
  11468. borderDash: [],
  11469. borderDashOffset: 0.0
  11470. },
  11471. gridLines: {
  11472. circular: false
  11473. },
  11474. // label settings
  11475. ticks: {
  11476. // Boolean - Show a backdrop to the scale label
  11477. showLabelBackdrop: true,
  11478. // String - The colour of the label backdrop
  11479. backdropColor: 'rgba(255,255,255,0.75)',
  11480. // Number - The backdrop padding above & below the label in pixels
  11481. backdropPaddingY: 2,
  11482. // Number - The backdrop padding to the side of the label in pixels
  11483. backdropPaddingX: 2,
  11484. callback: core_ticks.formatters.linear
  11485. },
  11486. pointLabels: {
  11487. // Boolean - if true, show point labels
  11488. display: true,
  11489. // Number - Point label font size in pixels
  11490. fontSize: 10,
  11491. // Function - Used to convert point labels
  11492. callback: function(label) {
  11493. return label;
  11494. }
  11495. }
  11496. };
  11497. function getTickBackdropHeight(opts) {
  11498. var tickOpts = opts.ticks;
  11499. if (tickOpts.display && opts.display) {
  11500. return valueOrDefault$c(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
  11501. }
  11502. return 0;
  11503. }
  11504. function measureLabelSize(ctx, lineHeight, label) {
  11505. if (helpers$1.isArray(label)) {
  11506. return {
  11507. w: helpers$1.longestText(ctx, ctx.font, label),
  11508. h: label.length * lineHeight
  11509. };
  11510. }
  11511. return {
  11512. w: ctx.measureText(label).width,
  11513. h: lineHeight
  11514. };
  11515. }
  11516. function determineLimits(angle, pos, size, min, max) {
  11517. if (angle === min || angle === max) {
  11518. return {
  11519. start: pos - (size / 2),
  11520. end: pos + (size / 2)
  11521. };
  11522. } else if (angle < min || angle > max) {
  11523. return {
  11524. start: pos - size,
  11525. end: pos
  11526. };
  11527. }
  11528. return {
  11529. start: pos,
  11530. end: pos + size
  11531. };
  11532. }
  11533. /**
  11534. * Helper function to fit a radial linear scale with point labels
  11535. */
  11536. function fitWithPointLabels(scale) {
  11537. // Right, this is really confusing and there is a lot of maths going on here
  11538. // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  11539. //
  11540. // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  11541. //
  11542. // Solution:
  11543. //
  11544. // We assume the radius of the polygon is half the size of the canvas at first
  11545. // at each index we check if the text overlaps.
  11546. //
  11547. // Where it does, we store that angle and that index.
  11548. //
  11549. // After finding the largest index and angle we calculate how much we need to remove
  11550. // from the shape radius to move the point inwards by that x.
  11551. //
  11552. // We average the left and right distances to get the maximum shape radius that can fit in the box
  11553. // along with labels.
  11554. //
  11555. // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  11556. // on each side, removing that from the size, halving it and adding the left x protrusion width.
  11557. //
  11558. // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  11559. // and position it in the most space efficient manner
  11560. //
  11561. // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  11562. var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
  11563. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  11564. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  11565. var furthestLimits = {
  11566. l: 0,
  11567. r: scale.width,
  11568. t: 0,
  11569. b: scale.height - scale.paddingTop
  11570. };
  11571. var furthestAngles = {};
  11572. var i, textSize, pointPosition;
  11573. scale.ctx.font = plFont.string;
  11574. scale._pointLabelSizes = [];
  11575. var valueCount = scale.chart.data.labels.length;
  11576. for (i = 0; i < valueCount; i++) {
  11577. pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
  11578. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);
  11579. scale._pointLabelSizes[i] = textSize;
  11580. // Add quarter circle to make degree 0 mean top of circle
  11581. var angleRadians = scale.getIndexAngle(i);
  11582. var angle = helpers$1.toDegrees(angleRadians) % 360;
  11583. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  11584. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  11585. if (hLimits.start < furthestLimits.l) {
  11586. furthestLimits.l = hLimits.start;
  11587. furthestAngles.l = angleRadians;
  11588. }
  11589. if (hLimits.end > furthestLimits.r) {
  11590. furthestLimits.r = hLimits.end;
  11591. furthestAngles.r = angleRadians;
  11592. }
  11593. if (vLimits.start < furthestLimits.t) {
  11594. furthestLimits.t = vLimits.start;
  11595. furthestAngles.t = angleRadians;
  11596. }
  11597. if (vLimits.end > furthestLimits.b) {
  11598. furthestLimits.b = vLimits.end;
  11599. furthestAngles.b = angleRadians;
  11600. }
  11601. }
  11602. scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  11603. }
  11604. function getTextAlignForAngle(angle) {
  11605. if (angle === 0 || angle === 180) {
  11606. return 'center';
  11607. } else if (angle < 180) {
  11608. return 'left';
  11609. }
  11610. return 'right';
  11611. }
  11612. function fillText(ctx, text, position, lineHeight) {
  11613. var y = position.y + lineHeight / 2;
  11614. var i, ilen;
  11615. if (helpers$1.isArray(text)) {
  11616. for (i = 0, ilen = text.length; i < ilen; ++i) {
  11617. ctx.fillText(text[i], position.x, y);
  11618. y += lineHeight;
  11619. }
  11620. } else {
  11621. ctx.fillText(text, position.x, y);
  11622. }
  11623. }
  11624. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  11625. if (angle === 90 || angle === 270) {
  11626. position.y -= (textSize.h / 2);
  11627. } else if (angle > 270 || angle < 90) {
  11628. position.y -= textSize.h;
  11629. }
  11630. }
  11631. function drawPointLabels(scale) {
  11632. var ctx = scale.ctx;
  11633. var opts = scale.options;
  11634. var pointLabelOpts = opts.pointLabels;
  11635. var tickBackdropHeight = getTickBackdropHeight(opts);
  11636. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  11637. var plFont = helpers$1.options._parseFont(pointLabelOpts);
  11638. ctx.save();
  11639. ctx.font = plFont.string;
  11640. ctx.textBaseline = 'middle';
  11641. for (var i = scale.chart.data.labels.length - 1; i >= 0; i--) {
  11642. // Extra pixels out for some label spacing
  11643. var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  11644. var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
  11645. // Keep this in loop since we may support array properties here
  11646. var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
  11647. ctx.fillStyle = pointLabelFontColor;
  11648. var angleRadians = scale.getIndexAngle(i);
  11649. var angle = helpers$1.toDegrees(angleRadians);
  11650. ctx.textAlign = getTextAlignForAngle(angle);
  11651. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  11652. fillText(ctx, scale.pointLabels[i], pointLabelPosition, plFont.lineHeight);
  11653. }
  11654. ctx.restore();
  11655. }
  11656. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  11657. var ctx = scale.ctx;
  11658. var circular = gridLineOpts.circular;
  11659. var valueCount = scale.chart.data.labels.length;
  11660. var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
  11661. var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
  11662. var pointPosition;
  11663. if ((!circular && !valueCount) || !lineColor || !lineWidth) {
  11664. return;
  11665. }
  11666. ctx.save();
  11667. ctx.strokeStyle = lineColor;
  11668. ctx.lineWidth = lineWidth;
  11669. if (ctx.setLineDash) {
  11670. ctx.setLineDash(gridLineOpts.borderDash || []);
  11671. ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
  11672. }
  11673. ctx.beginPath();
  11674. if (circular) {
  11675. // Draw circular arcs between the points
  11676. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  11677. } else {
  11678. // Draw straight lines connecting each index
  11679. pointPosition = scale.getPointPosition(0, radius);
  11680. ctx.moveTo(pointPosition.x, pointPosition.y);
  11681. for (var i = 1; i < valueCount; i++) {
  11682. pointPosition = scale.getPointPosition(i, radius);
  11683. ctx.lineTo(pointPosition.x, pointPosition.y);
  11684. }
  11685. }
  11686. ctx.closePath();
  11687. ctx.stroke();
  11688. ctx.restore();
  11689. }
  11690. function numberOrZero(param) {
  11691. return helpers$1.isNumber(param) ? param : 0;
  11692. }
  11693. var scale_radialLinear = scale_linearbase.extend({
  11694. setDimensions: function() {
  11695. var me = this;
  11696. // Set the unconstrained dimension before label rotation
  11697. me.width = me.maxWidth;
  11698. me.height = me.maxHeight;
  11699. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  11700. me.xCenter = Math.floor(me.width / 2);
  11701. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  11702. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  11703. },
  11704. determineDataLimits: function() {
  11705. var me = this;
  11706. var chart = me.chart;
  11707. var min = Number.POSITIVE_INFINITY;
  11708. var max = Number.NEGATIVE_INFINITY;
  11709. helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {
  11710. if (chart.isDatasetVisible(datasetIndex)) {
  11711. var meta = chart.getDatasetMeta(datasetIndex);
  11712. helpers$1.each(dataset.data, function(rawValue, index) {
  11713. var value = +me.getRightValue(rawValue);
  11714. if (isNaN(value) || meta.data[index].hidden) {
  11715. return;
  11716. }
  11717. min = Math.min(value, min);
  11718. max = Math.max(value, max);
  11719. });
  11720. }
  11721. });
  11722. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  11723. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  11724. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11725. me.handleTickRangeOptions();
  11726. },
  11727. // Returns the maximum number of ticks based on the scale dimension
  11728. _computeTickLimit: function() {
  11729. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  11730. },
  11731. convertTicksToLabels: function() {
  11732. var me = this;
  11733. scale_linearbase.prototype.convertTicksToLabels.call(me);
  11734. // Point labels
  11735. me.pointLabels = me.chart.data.labels.map(function() {
  11736. var label = helpers$1.callback(me.options.pointLabels.callback, arguments, me);
  11737. return label || label === 0 ? label : '';
  11738. });
  11739. },
  11740. getLabelForIndex: function(index, datasetIndex) {
  11741. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  11742. },
  11743. fit: function() {
  11744. var me = this;
  11745. var opts = me.options;
  11746. if (opts.display && opts.pointLabels.display) {
  11747. fitWithPointLabels(me);
  11748. } else {
  11749. me.setCenterPoint(0, 0, 0, 0);
  11750. }
  11751. },
  11752. /**
  11753. * Set radius reductions and determine new radius and center point
  11754. * @private
  11755. */
  11756. setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
  11757. var me = this;
  11758. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  11759. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  11760. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  11761. var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  11762. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  11763. radiusReductionRight = numberOrZero(radiusReductionRight);
  11764. radiusReductionTop = numberOrZero(radiusReductionTop);
  11765. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  11766. me.drawingArea = Math.min(
  11767. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  11768. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  11769. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  11770. },
  11771. setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
  11772. var me = this;
  11773. var maxRight = me.width - rightMovement - me.drawingArea;
  11774. var maxLeft = leftMovement + me.drawingArea;
  11775. var maxTop = topMovement + me.drawingArea;
  11776. var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  11777. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  11778. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  11779. },
  11780. getIndexAngle: function(index) {
  11781. var chart = this.chart;
  11782. var angleMultiplier = 360 / chart.data.labels.length;
  11783. var options = chart.options || {};
  11784. var startAngle = options.startAngle || 0;
  11785. // Start from the top instead of right, so remove a quarter of the circle
  11786. var angle = (index * angleMultiplier + startAngle) % 360;
  11787. return (angle < 0 ? angle + 360 : angle) * Math.PI * 2 / 360;
  11788. },
  11789. getDistanceFromCenterForValue: function(value) {
  11790. var me = this;
  11791. if (helpers$1.isNullOrUndef(value)) {
  11792. return NaN;
  11793. }
  11794. // Take into account half font size + the yPadding of the top value
  11795. var scalingFactor = me.drawingArea / (me.max - me.min);
  11796. if (me.options.ticks.reverse) {
  11797. return (me.max - value) * scalingFactor;
  11798. }
  11799. return (value - me.min) * scalingFactor;
  11800. },
  11801. getPointPosition: function(index, distanceFromCenter) {
  11802. var me = this;
  11803. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  11804. return {
  11805. x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
  11806. y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
  11807. };
  11808. },
  11809. getPointPositionForValue: function(index, value) {
  11810. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  11811. },
  11812. getBasePosition: function(index) {
  11813. var me = this;
  11814. var min = me.min;
  11815. var max = me.max;
  11816. return me.getPointPositionForValue(index || 0,
  11817. me.beginAtZero ? 0 :
  11818. min < 0 && max < 0 ? max :
  11819. min > 0 && max > 0 ? min :
  11820. 0);
  11821. },
  11822. /**
  11823. * @private
  11824. */
  11825. _drawGrid: function() {
  11826. var me = this;
  11827. var ctx = me.ctx;
  11828. var opts = me.options;
  11829. var gridLineOpts = opts.gridLines;
  11830. var angleLineOpts = opts.angleLines;
  11831. var lineWidth = valueOrDefault$c(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
  11832. var lineColor = valueOrDefault$c(angleLineOpts.color, gridLineOpts.color);
  11833. var i, offset, position;
  11834. if (opts.pointLabels.display) {
  11835. drawPointLabels(me);
  11836. }
  11837. if (gridLineOpts.display) {
  11838. helpers$1.each(me.ticks, function(label, index) {
  11839. if (index !== 0) {
  11840. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11841. drawRadiusLine(me, gridLineOpts, offset, index);
  11842. }
  11843. });
  11844. }
  11845. if (angleLineOpts.display && lineWidth && lineColor) {
  11846. ctx.save();
  11847. ctx.lineWidth = lineWidth;
  11848. ctx.strokeStyle = lineColor;
  11849. if (ctx.setLineDash) {
  11850. ctx.setLineDash(resolve$4([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
  11851. ctx.lineDashOffset = resolve$4([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
  11852. }
  11853. for (i = me.chart.data.labels.length - 1; i >= 0; i--) {
  11854. offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
  11855. position = me.getPointPosition(i, offset);
  11856. ctx.beginPath();
  11857. ctx.moveTo(me.xCenter, me.yCenter);
  11858. ctx.lineTo(position.x, position.y);
  11859. ctx.stroke();
  11860. }
  11861. ctx.restore();
  11862. }
  11863. },
  11864. /**
  11865. * @private
  11866. */
  11867. _drawLabels: function() {
  11868. var me = this;
  11869. var ctx = me.ctx;
  11870. var opts = me.options;
  11871. var tickOpts = opts.ticks;
  11872. if (!tickOpts.display) {
  11873. return;
  11874. }
  11875. var startAngle = me.getIndexAngle(0);
  11876. var tickFont = helpers$1.options._parseFont(tickOpts);
  11877. var tickFontColor = valueOrDefault$c(tickOpts.fontColor, core_defaults.global.defaultFontColor);
  11878. var offset, width;
  11879. ctx.save();
  11880. ctx.font = tickFont.string;
  11881. ctx.translate(me.xCenter, me.yCenter);
  11882. ctx.rotate(startAngle);
  11883. ctx.textAlign = 'center';
  11884. ctx.textBaseline = 'middle';
  11885. helpers$1.each(me.ticks, function(label, index) {
  11886. if (index === 0 && !tickOpts.reverse) {
  11887. return;
  11888. }
  11889. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11890. if (tickOpts.showLabelBackdrop) {
  11891. width = ctx.measureText(label).width;
  11892. ctx.fillStyle = tickOpts.backdropColor;
  11893. ctx.fillRect(
  11894. -width / 2 - tickOpts.backdropPaddingX,
  11895. -offset - tickFont.size / 2 - tickOpts.backdropPaddingY,
  11896. width + tickOpts.backdropPaddingX * 2,
  11897. tickFont.size + tickOpts.backdropPaddingY * 2
  11898. );
  11899. }
  11900. ctx.fillStyle = tickFontColor;
  11901. ctx.fillText(label, 0, -offset);
  11902. });
  11903. ctx.restore();
  11904. },
  11905. /**
  11906. * @private
  11907. */
  11908. _drawTitle: helpers$1.noop
  11909. });
  11910. // INTERNAL: static default options, registered in src/index.js
  11911. var _defaults$3 = defaultConfig$3;
  11912. scale_radialLinear._defaults = _defaults$3;
  11913. var deprecated$1 = helpers$1._deprecated;
  11914. var resolve$5 = helpers$1.options.resolve;
  11915. var valueOrDefault$d = helpers$1.valueOrDefault;
  11916. // Integer constants are from the ES6 spec.
  11917. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  11918. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  11919. var INTERVALS = {
  11920. millisecond: {
  11921. common: true,
  11922. size: 1,
  11923. steps: 1000
  11924. },
  11925. second: {
  11926. common: true,
  11927. size: 1000,
  11928. steps: 60
  11929. },
  11930. minute: {
  11931. common: true,
  11932. size: 60000,
  11933. steps: 60
  11934. },
  11935. hour: {
  11936. common: true,
  11937. size: 3600000,
  11938. steps: 24
  11939. },
  11940. day: {
  11941. common: true,
  11942. size: 86400000,
  11943. steps: 30
  11944. },
  11945. week: {
  11946. common: false,
  11947. size: 604800000,
  11948. steps: 4
  11949. },
  11950. month: {
  11951. common: true,
  11952. size: 2.628e9,
  11953. steps: 12
  11954. },
  11955. quarter: {
  11956. common: false,
  11957. size: 7.884e9,
  11958. steps: 4
  11959. },
  11960. year: {
  11961. common: true,
  11962. size: 3.154e10
  11963. }
  11964. };
  11965. var UNITS = Object.keys(INTERVALS);
  11966. function sorter(a, b) {
  11967. return a - b;
  11968. }
  11969. function arrayUnique(items) {
  11970. var hash = {};
  11971. var out = [];
  11972. var i, ilen, item;
  11973. for (i = 0, ilen = items.length; i < ilen; ++i) {
  11974. item = items[i];
  11975. if (!hash[item]) {
  11976. hash[item] = true;
  11977. out.push(item);
  11978. }
  11979. }
  11980. return out;
  11981. }
  11982. function getMin(options) {
  11983. return helpers$1.valueOrDefault(options.time.min, options.ticks.min);
  11984. }
  11985. function getMax(options) {
  11986. return helpers$1.valueOrDefault(options.time.max, options.ticks.max);
  11987. }
  11988. /**
  11989. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  11990. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  11991. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  11992. * extremity (left + width or top + height). Note that it would be more optimized to directly
  11993. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  11994. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  11995. *
  11996. * @param {number[]} timestamps - timestamps sorted from lowest to highest.
  11997. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
  11998. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  11999. * If 'series', timestamps will be positioned at the same distance from each other. In this
  12000. * case, only timestamps that break the time linearity are registered, meaning that in the
  12001. * best case, all timestamps are linear, the table contains only min and max.
  12002. */
  12003. function buildLookupTable(timestamps, min, max, distribution) {
  12004. if (distribution === 'linear' || !timestamps.length) {
  12005. return [
  12006. {time: min, pos: 0},
  12007. {time: max, pos: 1}
  12008. ];
  12009. }
  12010. var table = [];
  12011. var items = [min];
  12012. var i, ilen, prev, curr, next;
  12013. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12014. curr = timestamps[i];
  12015. if (curr > min && curr < max) {
  12016. items.push(curr);
  12017. }
  12018. }
  12019. items.push(max);
  12020. for (i = 0, ilen = items.length; i < ilen; ++i) {
  12021. next = items[i + 1];
  12022. prev = items[i - 1];
  12023. curr = items[i];
  12024. // only add points that breaks the scale linearity
  12025. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  12026. table.push({time: curr, pos: i / (ilen - 1)});
  12027. }
  12028. }
  12029. return table;
  12030. }
  12031. // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  12032. function lookup(table, key, value) {
  12033. var lo = 0;
  12034. var hi = table.length - 1;
  12035. var mid, i0, i1;
  12036. while (lo >= 0 && lo <= hi) {
  12037. mid = (lo + hi) >> 1;
  12038. i0 = table[mid - 1] || null;
  12039. i1 = table[mid];
  12040. if (!i0) {
  12041. // given value is outside table (before first item)
  12042. return {lo: null, hi: i1};
  12043. } else if (i1[key] < value) {
  12044. lo = mid + 1;
  12045. } else if (i0[key] > value) {
  12046. hi = mid - 1;
  12047. } else {
  12048. return {lo: i0, hi: i1};
  12049. }
  12050. }
  12051. // given value is outside table (after last item)
  12052. return {lo: i1, hi: null};
  12053. }
  12054. /**
  12055. * Linearly interpolates the given source `value` using the table items `skey` values and
  12056. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  12057. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  12058. * index [0, 1] or [n - 1, n] are used for the interpolation.
  12059. */
  12060. function interpolate$1(table, skey, sval, tkey) {
  12061. var range = lookup(table, skey, sval);
  12062. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  12063. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  12064. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  12065. var span = next[skey] - prev[skey];
  12066. var ratio = span ? (sval - prev[skey]) / span : 0;
  12067. var offset = (next[tkey] - prev[tkey]) * ratio;
  12068. return prev[tkey] + offset;
  12069. }
  12070. function toTimestamp(scale, input) {
  12071. var adapter = scale._adapter;
  12072. var options = scale.options.time;
  12073. var parser = options.parser;
  12074. var format = parser || options.format;
  12075. var value = input;
  12076. if (typeof parser === 'function') {
  12077. value = parser(value);
  12078. }
  12079. // Only parse if its not a timestamp already
  12080. if (!helpers$1.isFinite(value)) {
  12081. value = typeof format === 'string'
  12082. ? adapter.parse(value, format)
  12083. : adapter.parse(value);
  12084. }
  12085. if (value !== null) {
  12086. return +value;
  12087. }
  12088. // Labels are in an incompatible format and no `parser` has been provided.
  12089. // The user might still use the deprecated `format` option for parsing.
  12090. if (!parser && typeof format === 'function') {
  12091. value = format(input);
  12092. // `format` could return something else than a timestamp, if so, parse it
  12093. if (!helpers$1.isFinite(value)) {
  12094. value = adapter.parse(value);
  12095. }
  12096. }
  12097. return value;
  12098. }
  12099. function parse(scale, input) {
  12100. if (helpers$1.isNullOrUndef(input)) {
  12101. return null;
  12102. }
  12103. var options = scale.options.time;
  12104. var value = toTimestamp(scale, scale.getRightValue(input));
  12105. if (value === null) {
  12106. return value;
  12107. }
  12108. if (options.round) {
  12109. value = +scale._adapter.startOf(value, options.round);
  12110. }
  12111. return value;
  12112. }
  12113. /**
  12114. * Figures out what unit results in an appropriate number of auto-generated ticks
  12115. */
  12116. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  12117. var ilen = UNITS.length;
  12118. var i, interval, factor;
  12119. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  12120. interval = INTERVALS[UNITS[i]];
  12121. factor = interval.steps ? interval.steps : MAX_INTEGER;
  12122. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  12123. return UNITS[i];
  12124. }
  12125. }
  12126. return UNITS[ilen - 1];
  12127. }
  12128. /**
  12129. * Figures out what unit to format a set of ticks with
  12130. */
  12131. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  12132. var i, unit;
  12133. for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  12134. unit = UNITS[i];
  12135. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  12136. return unit;
  12137. }
  12138. }
  12139. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  12140. }
  12141. function determineMajorUnit(unit) {
  12142. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  12143. if (INTERVALS[UNITS[i]].common) {
  12144. return UNITS[i];
  12145. }
  12146. }
  12147. }
  12148. /**
  12149. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  12150. * `minor` unit using the given scale time `options`.
  12151. * Important: this method can return ticks outside the min and max range, it's the
  12152. * responsibility of the calling code to clamp values if needed.
  12153. */
  12154. function generate(scale, min, max, capacity) {
  12155. var adapter = scale._adapter;
  12156. var options = scale.options;
  12157. var timeOpts = options.time;
  12158. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  12159. var stepSize = resolve$5([timeOpts.stepSize, timeOpts.unitStepSize, 1]);
  12160. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  12161. var first = min;
  12162. var ticks = [];
  12163. var time;
  12164. // For 'week' unit, handle the first day of week option
  12165. if (weekday) {
  12166. first = +adapter.startOf(first, 'isoWeek', weekday);
  12167. }
  12168. // Align first ticks on unit
  12169. first = +adapter.startOf(first, weekday ? 'day' : minor);
  12170. // Prevent browser from freezing in case user options request millions of milliseconds
  12171. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  12172. throw min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor;
  12173. }
  12174. for (time = first; time < max; time = +adapter.add(time, stepSize, minor)) {
  12175. ticks.push(time);
  12176. }
  12177. if (time === max || options.bounds === 'ticks') {
  12178. ticks.push(time);
  12179. }
  12180. return ticks;
  12181. }
  12182. /**
  12183. * Returns the start and end offsets from edges in the form of {start, end}
  12184. * where each value is a relative width to the scale and ranges between 0 and 1.
  12185. * They add extra margins on the both sides by scaling down the original scale.
  12186. * Offsets are added when the `offset` option is true.
  12187. */
  12188. function computeOffsets(table, ticks, min, max, options) {
  12189. var start = 0;
  12190. var end = 0;
  12191. var first, last;
  12192. if (options.offset && ticks.length) {
  12193. first = interpolate$1(table, 'time', ticks[0], 'pos');
  12194. if (ticks.length === 1) {
  12195. start = 1 - first;
  12196. } else {
  12197. start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
  12198. }
  12199. last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
  12200. if (ticks.length === 1) {
  12201. end = last;
  12202. } else {
  12203. end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
  12204. }
  12205. }
  12206. return {start: start, end: end, factor: 1 / (start + 1 + end)};
  12207. }
  12208. function setMajorTicks(scale, ticks, map, majorUnit) {
  12209. var adapter = scale._adapter;
  12210. var first = +adapter.startOf(ticks[0].value, majorUnit);
  12211. var last = ticks[ticks.length - 1].value;
  12212. var major, index;
  12213. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  12214. index = map[major];
  12215. if (index >= 0) {
  12216. ticks[index].major = true;
  12217. }
  12218. }
  12219. return ticks;
  12220. }
  12221. function ticksFromTimestamps(scale, values, majorUnit) {
  12222. var ticks = [];
  12223. var map = {};
  12224. var ilen = values.length;
  12225. var i, value;
  12226. for (i = 0; i < ilen; ++i) {
  12227. value = values[i];
  12228. map[value] = i;
  12229. ticks.push({
  12230. value: value,
  12231. major: false
  12232. });
  12233. }
  12234. // We set the major ticks separately from the above loop because calling startOf for every tick
  12235. // is expensive when there is a large number of ticks
  12236. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  12237. }
  12238. var defaultConfig$4 = {
  12239. position: 'bottom',
  12240. /**
  12241. * Data distribution along the scale:
  12242. * - 'linear': data are spread according to their time (distances can vary),
  12243. * - 'series': data are spread at the same distance from each other.
  12244. * @see https://github.com/chartjs/Chart.js/pull/4507
  12245. * @since 2.7.0
  12246. */
  12247. distribution: 'linear',
  12248. /**
  12249. * Scale boundary strategy (bypassed by min/max time options)
  12250. * - `data`: make sure data are fully visible, ticks outside are removed
  12251. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  12252. * @see https://github.com/chartjs/Chart.js/pull/4556
  12253. * @since 2.7.0
  12254. */
  12255. bounds: 'data',
  12256. adapters: {},
  12257. time: {
  12258. 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
  12259. unit: false, // false == automatic or override with week, month, year, etc.
  12260. round: false, // none, or override with week, month, year, etc.
  12261. displayFormat: false, // DEPRECATED
  12262. isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
  12263. minUnit: 'millisecond',
  12264. displayFormats: {}
  12265. },
  12266. ticks: {
  12267. autoSkip: false,
  12268. /**
  12269. * Ticks generation input values:
  12270. * - 'auto': generates "optimal" ticks based on scale size and time options.
  12271. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  12272. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  12273. * @see https://github.com/chartjs/Chart.js/pull/4507
  12274. * @since 2.7.0
  12275. */
  12276. source: 'auto',
  12277. major: {
  12278. enabled: false
  12279. }
  12280. }
  12281. };
  12282. var scale_time = core_scale.extend({
  12283. initialize: function() {
  12284. this.mergeTicksOptions();
  12285. core_scale.prototype.initialize.call(this);
  12286. },
  12287. update: function() {
  12288. var me = this;
  12289. var options = me.options;
  12290. var time = options.time || (options.time = {});
  12291. var adapter = me._adapter = new core_adapters._date(options.adapters.date);
  12292. // DEPRECATIONS: output a message only one time per update
  12293. deprecated$1('time scale', time.format, 'time.format', 'time.parser');
  12294. deprecated$1('time scale', time.min, 'time.min', 'ticks.min');
  12295. deprecated$1('time scale', time.max, 'time.max', 'ticks.max');
  12296. // Backward compatibility: before introducing adapter, `displayFormats` was
  12297. // supposed to contain *all* unit/string pairs but this can't be resolved
  12298. // when loading the scale (adapters are loaded afterward), so let's populate
  12299. // missing formats on update
  12300. helpers$1.mergeIf(time.displayFormats, adapter.formats());
  12301. return core_scale.prototype.update.apply(me, arguments);
  12302. },
  12303. /**
  12304. * Allows data to be referenced via 't' attribute
  12305. */
  12306. getRightValue: function(rawValue) {
  12307. if (rawValue && rawValue.t !== undefined) {
  12308. rawValue = rawValue.t;
  12309. }
  12310. return core_scale.prototype.getRightValue.call(this, rawValue);
  12311. },
  12312. determineDataLimits: function() {
  12313. var me = this;
  12314. var chart = me.chart;
  12315. var adapter = me._adapter;
  12316. var options = me.options;
  12317. var unit = options.time.unit || 'day';
  12318. var min = MAX_INTEGER;
  12319. var max = MIN_INTEGER;
  12320. var timestamps = [];
  12321. var datasets = [];
  12322. var labels = [];
  12323. var i, j, ilen, jlen, data, timestamp, labelsAdded;
  12324. var dataLabels = me._getLabels();
  12325. for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
  12326. labels.push(parse(me, dataLabels[i]));
  12327. }
  12328. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  12329. if (chart.isDatasetVisible(i)) {
  12330. data = chart.data.datasets[i].data;
  12331. // Let's consider that all data have the same format.
  12332. if (helpers$1.isObject(data[0])) {
  12333. datasets[i] = [];
  12334. for (j = 0, jlen = data.length; j < jlen; ++j) {
  12335. timestamp = parse(me, data[j]);
  12336. timestamps.push(timestamp);
  12337. datasets[i][j] = timestamp;
  12338. }
  12339. } else {
  12340. datasets[i] = labels.slice(0);
  12341. if (!labelsAdded) {
  12342. timestamps = timestamps.concat(labels);
  12343. labelsAdded = true;
  12344. }
  12345. }
  12346. } else {
  12347. datasets[i] = [];
  12348. }
  12349. }
  12350. if (labels.length) {
  12351. min = Math.min(min, labels[0]);
  12352. max = Math.max(max, labels[labels.length - 1]);
  12353. }
  12354. if (timestamps.length) {
  12355. timestamps = ilen > 1 ? arrayUnique(timestamps).sort(sorter) : timestamps.sort(sorter);
  12356. min = Math.min(min, timestamps[0]);
  12357. max = Math.max(max, timestamps[timestamps.length - 1]);
  12358. }
  12359. min = parse(me, getMin(options)) || min;
  12360. max = parse(me, getMax(options)) || max;
  12361. // In case there is no valid min/max, set limits based on unit time option
  12362. min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
  12363. max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;
  12364. // Make sure that max is strictly higher than min (required by the lookup table)
  12365. me.min = Math.min(min, max);
  12366. me.max = Math.max(min + 1, max);
  12367. // PRIVATE
  12368. me._table = [];
  12369. me._timestamps = {
  12370. data: timestamps,
  12371. datasets: datasets,
  12372. labels: labels
  12373. };
  12374. },
  12375. buildTicks: function() {
  12376. var me = this;
  12377. var min = me.min;
  12378. var max = me.max;
  12379. var options = me.options;
  12380. var tickOpts = options.ticks;
  12381. var timeOpts = options.time;
  12382. var timestamps = me._timestamps;
  12383. var ticks = [];
  12384. var capacity = me.getLabelCapacity(min);
  12385. var source = tickOpts.source;
  12386. var distribution = options.distribution;
  12387. var i, ilen, timestamp;
  12388. if (source === 'data' || (source === 'auto' && distribution === 'series')) {
  12389. timestamps = timestamps.data;
  12390. } else if (source === 'labels') {
  12391. timestamps = timestamps.labels;
  12392. } else {
  12393. timestamps = generate(me, min, max, capacity);
  12394. }
  12395. if (options.bounds === 'ticks' && timestamps.length) {
  12396. min = timestamps[0];
  12397. max = timestamps[timestamps.length - 1];
  12398. }
  12399. // Enforce limits with user min/max options
  12400. min = parse(me, getMin(options)) || min;
  12401. max = parse(me, getMax(options)) || max;
  12402. // Remove ticks outside the min/max range
  12403. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12404. timestamp = timestamps[i];
  12405. if (timestamp >= min && timestamp <= max) {
  12406. ticks.push(timestamp);
  12407. }
  12408. }
  12409. me.min = min;
  12410. me.max = max;
  12411. // PRIVATE
  12412. // determineUnitForFormatting relies on the number of ticks so we don't use it when
  12413. // autoSkip is enabled because we don't yet know what the final number of ticks will be
  12414. me._unit = timeOpts.unit || (tickOpts.autoSkip
  12415. ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, capacity)
  12416. : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
  12417. me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
  12418. : determineMajorUnit(me._unit);
  12419. me._table = buildLookupTable(me._timestamps.data, min, max, distribution);
  12420. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  12421. if (tickOpts.reverse) {
  12422. ticks.reverse();
  12423. }
  12424. return ticksFromTimestamps(me, ticks, me._majorUnit);
  12425. },
  12426. getLabelForIndex: function(index, datasetIndex) {
  12427. var me = this;
  12428. var adapter = me._adapter;
  12429. var data = me.chart.data;
  12430. var timeOpts = me.options.time;
  12431. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  12432. var value = data.datasets[datasetIndex].data[index];
  12433. if (helpers$1.isObject(value)) {
  12434. label = me.getRightValue(value);
  12435. }
  12436. if (timeOpts.tooltipFormat) {
  12437. return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
  12438. }
  12439. if (typeof label === 'string') {
  12440. return label;
  12441. }
  12442. return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
  12443. },
  12444. /**
  12445. * Function to format an individual tick mark
  12446. * @private
  12447. */
  12448. tickFormatFunction: function(time, index, ticks, format) {
  12449. var me = this;
  12450. var adapter = me._adapter;
  12451. var options = me.options;
  12452. var formats = options.time.displayFormats;
  12453. var minorFormat = formats[me._unit];
  12454. var majorUnit = me._majorUnit;
  12455. var majorFormat = formats[majorUnit];
  12456. var tick = ticks[index];
  12457. var tickOpts = options.ticks;
  12458. var major = majorUnit && majorFormat && tick && tick.major;
  12459. var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
  12460. var nestedTickOpts = major ? tickOpts.major : tickOpts.minor;
  12461. var formatter = resolve$5([
  12462. nestedTickOpts.callback,
  12463. nestedTickOpts.userCallback,
  12464. tickOpts.callback,
  12465. tickOpts.userCallback
  12466. ]);
  12467. return formatter ? formatter(label, index, ticks) : label;
  12468. },
  12469. convertTicksToLabels: function(ticks) {
  12470. var labels = [];
  12471. var i, ilen;
  12472. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  12473. labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
  12474. }
  12475. return labels;
  12476. },
  12477. /**
  12478. * @private
  12479. */
  12480. getPixelForOffset: function(time) {
  12481. var me = this;
  12482. var offsets = me._offsets;
  12483. var pos = interpolate$1(me._table, 'time', time, 'pos');
  12484. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  12485. },
  12486. getPixelForValue: function(value, index, datasetIndex) {
  12487. var me = this;
  12488. var time = null;
  12489. if (index !== undefined && datasetIndex !== undefined) {
  12490. time = me._timestamps.datasets[datasetIndex][index];
  12491. }
  12492. if (time === null) {
  12493. time = parse(me, value);
  12494. }
  12495. if (time !== null) {
  12496. return me.getPixelForOffset(time);
  12497. }
  12498. },
  12499. getPixelForTick: function(index) {
  12500. var ticks = this.getTicks();
  12501. return index >= 0 && index < ticks.length ?
  12502. this.getPixelForOffset(ticks[index].value) :
  12503. null;
  12504. },
  12505. getValueForPixel: function(pixel) {
  12506. var me = this;
  12507. var offsets = me._offsets;
  12508. var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  12509. var time = interpolate$1(me._table, 'pos', pos, 'time');
  12510. // DEPRECATION, we should return time directly
  12511. return me._adapter._create(time);
  12512. },
  12513. /**
  12514. * @private
  12515. */
  12516. _getLabelSize: function(label) {
  12517. var me = this;
  12518. var ticksOpts = me.options.ticks;
  12519. var tickLabelWidth = me.ctx.measureText(label).width;
  12520. var angle = helpers$1.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  12521. var cosRotation = Math.cos(angle);
  12522. var sinRotation = Math.sin(angle);
  12523. var tickFontSize = valueOrDefault$d(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
  12524. return {
  12525. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  12526. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  12527. };
  12528. },
  12529. /**
  12530. * Crude approximation of what the label width might be
  12531. * @private
  12532. */
  12533. getLabelWidth: function(label) {
  12534. return this._getLabelSize(label).w;
  12535. },
  12536. /**
  12537. * @private
  12538. */
  12539. getLabelCapacity: function(exampleTime) {
  12540. var me = this;
  12541. var timeOpts = me.options.time;
  12542. var displayFormats = timeOpts.displayFormats;
  12543. // pick the longest format (milliseconds) for guestimation
  12544. var format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  12545. var exampleLabel = me.tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
  12546. var size = me._getLabelSize(exampleLabel);
  12547. var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h);
  12548. if (me.options.offset) {
  12549. capacity--;
  12550. }
  12551. return capacity > 0 ? capacity : 1;
  12552. }
  12553. });
  12554. // INTERNAL: static default options, registered in src/index.js
  12555. var _defaults$4 = defaultConfig$4;
  12556. scale_time._defaults = _defaults$4;
  12557. var scales = {
  12558. category: scale_category,
  12559. linear: scale_linear,
  12560. logarithmic: scale_logarithmic,
  12561. radialLinear: scale_radialLinear,
  12562. time: scale_time
  12563. };
  12564. var moment = createCommonjsModule(function (module, exports) {
  12565. (function (global, factory) {
  12566. module.exports = factory() ;
  12567. }(commonjsGlobal, (function () {
  12568. var hookCallback;
  12569. function hooks () {
  12570. return hookCallback.apply(null, arguments);
  12571. }
  12572. // This is done to register the method called with moment()
  12573. // without creating circular dependencies.
  12574. function setHookCallback (callback) {
  12575. hookCallback = callback;
  12576. }
  12577. function isArray(input) {
  12578. return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
  12579. }
  12580. function isObject(input) {
  12581. // IE8 will treat undefined and null as object if it wasn't for
  12582. // input != null
  12583. return input != null && Object.prototype.toString.call(input) === '[object Object]';
  12584. }
  12585. function isObjectEmpty(obj) {
  12586. if (Object.getOwnPropertyNames) {
  12587. return (Object.getOwnPropertyNames(obj).length === 0);
  12588. } else {
  12589. var k;
  12590. for (k in obj) {
  12591. if (obj.hasOwnProperty(k)) {
  12592. return false;
  12593. }
  12594. }
  12595. return true;
  12596. }
  12597. }
  12598. function isUndefined(input) {
  12599. return input === void 0;
  12600. }
  12601. function isNumber(input) {
  12602. return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
  12603. }
  12604. function isDate(input) {
  12605. return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
  12606. }
  12607. function map(arr, fn) {
  12608. var res = [], i;
  12609. for (i = 0; i < arr.length; ++i) {
  12610. res.push(fn(arr[i], i));
  12611. }
  12612. return res;
  12613. }
  12614. function hasOwnProp(a, b) {
  12615. return Object.prototype.hasOwnProperty.call(a, b);
  12616. }
  12617. function extend(a, b) {
  12618. for (var i in b) {
  12619. if (hasOwnProp(b, i)) {
  12620. a[i] = b[i];
  12621. }
  12622. }
  12623. if (hasOwnProp(b, 'toString')) {
  12624. a.toString = b.toString;
  12625. }
  12626. if (hasOwnProp(b, 'valueOf')) {
  12627. a.valueOf = b.valueOf;
  12628. }
  12629. return a;
  12630. }
  12631. function createUTC (input, format, locale, strict) {
  12632. return createLocalOrUTC(input, format, locale, strict, true).utc();
  12633. }
  12634. function defaultParsingFlags() {
  12635. // We need to deep clone this object.
  12636. return {
  12637. empty : false,
  12638. unusedTokens : [],
  12639. unusedInput : [],
  12640. overflow : -2,
  12641. charsLeftOver : 0,
  12642. nullInput : false,
  12643. invalidMonth : null,
  12644. invalidFormat : false,
  12645. userInvalidated : false,
  12646. iso : false,
  12647. parsedDateParts : [],
  12648. meridiem : null,
  12649. rfc2822 : false,
  12650. weekdayMismatch : false
  12651. };
  12652. }
  12653. function getParsingFlags(m) {
  12654. if (m._pf == null) {
  12655. m._pf = defaultParsingFlags();
  12656. }
  12657. return m._pf;
  12658. }
  12659. var some;
  12660. if (Array.prototype.some) {
  12661. some = Array.prototype.some;
  12662. } else {
  12663. some = function (fun) {
  12664. var t = Object(this);
  12665. var len = t.length >>> 0;
  12666. for (var i = 0; i < len; i++) {
  12667. if (i in t && fun.call(this, t[i], i, t)) {
  12668. return true;
  12669. }
  12670. }
  12671. return false;
  12672. };
  12673. }
  12674. function isValid(m) {
  12675. if (m._isValid == null) {
  12676. var flags = getParsingFlags(m);
  12677. var parsedParts = some.call(flags.parsedDateParts, function (i) {
  12678. return i != null;
  12679. });
  12680. var isNowValid = !isNaN(m._d.getTime()) &&
  12681. flags.overflow < 0 &&
  12682. !flags.empty &&
  12683. !flags.invalidMonth &&
  12684. !flags.invalidWeekday &&
  12685. !flags.weekdayMismatch &&
  12686. !flags.nullInput &&
  12687. !flags.invalidFormat &&
  12688. !flags.userInvalidated &&
  12689. (!flags.meridiem || (flags.meridiem && parsedParts));
  12690. if (m._strict) {
  12691. isNowValid = isNowValid &&
  12692. flags.charsLeftOver === 0 &&
  12693. flags.unusedTokens.length === 0 &&
  12694. flags.bigHour === undefined;
  12695. }
  12696. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  12697. m._isValid = isNowValid;
  12698. }
  12699. else {
  12700. return isNowValid;
  12701. }
  12702. }
  12703. return m._isValid;
  12704. }
  12705. function createInvalid (flags) {
  12706. var m = createUTC(NaN);
  12707. if (flags != null) {
  12708. extend(getParsingFlags(m), flags);
  12709. }
  12710. else {
  12711. getParsingFlags(m).userInvalidated = true;
  12712. }
  12713. return m;
  12714. }
  12715. // Plugins that add properties should also add the key here (null value),
  12716. // so we can properly clone ourselves.
  12717. var momentProperties = hooks.momentProperties = [];
  12718. function copyConfig(to, from) {
  12719. var i, prop, val;
  12720. if (!isUndefined(from._isAMomentObject)) {
  12721. to._isAMomentObject = from._isAMomentObject;
  12722. }
  12723. if (!isUndefined(from._i)) {
  12724. to._i = from._i;
  12725. }
  12726. if (!isUndefined(from._f)) {
  12727. to._f = from._f;
  12728. }
  12729. if (!isUndefined(from._l)) {
  12730. to._l = from._l;
  12731. }
  12732. if (!isUndefined(from._strict)) {
  12733. to._strict = from._strict;
  12734. }
  12735. if (!isUndefined(from._tzm)) {
  12736. to._tzm = from._tzm;
  12737. }
  12738. if (!isUndefined(from._isUTC)) {
  12739. to._isUTC = from._isUTC;
  12740. }
  12741. if (!isUndefined(from._offset)) {
  12742. to._offset = from._offset;
  12743. }
  12744. if (!isUndefined(from._pf)) {
  12745. to._pf = getParsingFlags(from);
  12746. }
  12747. if (!isUndefined(from._locale)) {
  12748. to._locale = from._locale;
  12749. }
  12750. if (momentProperties.length > 0) {
  12751. for (i = 0; i < momentProperties.length; i++) {
  12752. prop = momentProperties[i];
  12753. val = from[prop];
  12754. if (!isUndefined(val)) {
  12755. to[prop] = val;
  12756. }
  12757. }
  12758. }
  12759. return to;
  12760. }
  12761. var updateInProgress = false;
  12762. // Moment prototype object
  12763. function Moment(config) {
  12764. copyConfig(this, config);
  12765. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  12766. if (!this.isValid()) {
  12767. this._d = new Date(NaN);
  12768. }
  12769. // Prevent infinite loop in case updateOffset creates new moment
  12770. // objects.
  12771. if (updateInProgress === false) {
  12772. updateInProgress = true;
  12773. hooks.updateOffset(this);
  12774. updateInProgress = false;
  12775. }
  12776. }
  12777. function isMoment (obj) {
  12778. return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
  12779. }
  12780. function absFloor (number) {
  12781. if (number < 0) {
  12782. // -0 -> 0
  12783. return Math.ceil(number) || 0;
  12784. } else {
  12785. return Math.floor(number);
  12786. }
  12787. }
  12788. function toInt(argumentForCoercion) {
  12789. var coercedNumber = +argumentForCoercion,
  12790. value = 0;
  12791. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  12792. value = absFloor(coercedNumber);
  12793. }
  12794. return value;
  12795. }
  12796. // compare two arrays, return the number of differences
  12797. function compareArrays(array1, array2, dontConvert) {
  12798. var len = Math.min(array1.length, array2.length),
  12799. lengthDiff = Math.abs(array1.length - array2.length),
  12800. diffs = 0,
  12801. i;
  12802. for (i = 0; i < len; i++) {
  12803. if ((dontConvert && array1[i] !== array2[i]) ||
  12804. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  12805. diffs++;
  12806. }
  12807. }
  12808. return diffs + lengthDiff;
  12809. }
  12810. function warn(msg) {
  12811. if (hooks.suppressDeprecationWarnings === false &&
  12812. (typeof console !== 'undefined') && console.warn) {
  12813. console.warn('Deprecation warning: ' + msg);
  12814. }
  12815. }
  12816. function deprecate(msg, fn) {
  12817. var firstTime = true;
  12818. return extend(function () {
  12819. if (hooks.deprecationHandler != null) {
  12820. hooks.deprecationHandler(null, msg);
  12821. }
  12822. if (firstTime) {
  12823. var args = [];
  12824. var arg;
  12825. for (var i = 0; i < arguments.length; i++) {
  12826. arg = '';
  12827. if (typeof arguments[i] === 'object') {
  12828. arg += '\n[' + i + '] ';
  12829. for (var key in arguments[0]) {
  12830. arg += key + ': ' + arguments[0][key] + ', ';
  12831. }
  12832. arg = arg.slice(0, -2); // Remove trailing comma and space
  12833. } else {
  12834. arg = arguments[i];
  12835. }
  12836. args.push(arg);
  12837. }
  12838. warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
  12839. firstTime = false;
  12840. }
  12841. return fn.apply(this, arguments);
  12842. }, fn);
  12843. }
  12844. var deprecations = {};
  12845. function deprecateSimple(name, msg) {
  12846. if (hooks.deprecationHandler != null) {
  12847. hooks.deprecationHandler(name, msg);
  12848. }
  12849. if (!deprecations[name]) {
  12850. warn(msg);
  12851. deprecations[name] = true;
  12852. }
  12853. }
  12854. hooks.suppressDeprecationWarnings = false;
  12855. hooks.deprecationHandler = null;
  12856. function isFunction(input) {
  12857. return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
  12858. }
  12859. function set (config) {
  12860. var prop, i;
  12861. for (i in config) {
  12862. prop = config[i];
  12863. if (isFunction(prop)) {
  12864. this[i] = prop;
  12865. } else {
  12866. this['_' + i] = prop;
  12867. }
  12868. }
  12869. this._config = config;
  12870. // Lenient ordinal parsing accepts just a number in addition to
  12871. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  12872. // TODO: Remove "ordinalParse" fallback in next major release.
  12873. this._dayOfMonthOrdinalParseLenient = new RegExp(
  12874. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  12875. '|' + (/\d{1,2}/).source);
  12876. }
  12877. function mergeConfigs(parentConfig, childConfig) {
  12878. var res = extend({}, parentConfig), prop;
  12879. for (prop in childConfig) {
  12880. if (hasOwnProp(childConfig, prop)) {
  12881. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  12882. res[prop] = {};
  12883. extend(res[prop], parentConfig[prop]);
  12884. extend(res[prop], childConfig[prop]);
  12885. } else if (childConfig[prop] != null) {
  12886. res[prop] = childConfig[prop];
  12887. } else {
  12888. delete res[prop];
  12889. }
  12890. }
  12891. }
  12892. for (prop in parentConfig) {
  12893. if (hasOwnProp(parentConfig, prop) &&
  12894. !hasOwnProp(childConfig, prop) &&
  12895. isObject(parentConfig[prop])) {
  12896. // make sure changes to properties don't modify parent config
  12897. res[prop] = extend({}, res[prop]);
  12898. }
  12899. }
  12900. return res;
  12901. }
  12902. function Locale(config) {
  12903. if (config != null) {
  12904. this.set(config);
  12905. }
  12906. }
  12907. var keys;
  12908. if (Object.keys) {
  12909. keys = Object.keys;
  12910. } else {
  12911. keys = function (obj) {
  12912. var i, res = [];
  12913. for (i in obj) {
  12914. if (hasOwnProp(obj, i)) {
  12915. res.push(i);
  12916. }
  12917. }
  12918. return res;
  12919. };
  12920. }
  12921. var defaultCalendar = {
  12922. sameDay : '[Today at] LT',
  12923. nextDay : '[Tomorrow at] LT',
  12924. nextWeek : 'dddd [at] LT',
  12925. lastDay : '[Yesterday at] LT',
  12926. lastWeek : '[Last] dddd [at] LT',
  12927. sameElse : 'L'
  12928. };
  12929. function calendar (key, mom, now) {
  12930. var output = this._calendar[key] || this._calendar['sameElse'];
  12931. return isFunction(output) ? output.call(mom, now) : output;
  12932. }
  12933. var defaultLongDateFormat = {
  12934. LTS : 'h:mm:ss A',
  12935. LT : 'h:mm A',
  12936. L : 'MM/DD/YYYY',
  12937. LL : 'MMMM D, YYYY',
  12938. LLL : 'MMMM D, YYYY h:mm A',
  12939. LLLL : 'dddd, MMMM D, YYYY h:mm A'
  12940. };
  12941. function longDateFormat (key) {
  12942. var format = this._longDateFormat[key],
  12943. formatUpper = this._longDateFormat[key.toUpperCase()];
  12944. if (format || !formatUpper) {
  12945. return format;
  12946. }
  12947. this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
  12948. return val.slice(1);
  12949. });
  12950. return this._longDateFormat[key];
  12951. }
  12952. var defaultInvalidDate = 'Invalid date';
  12953. function invalidDate () {
  12954. return this._invalidDate;
  12955. }
  12956. var defaultOrdinal = '%d';
  12957. var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  12958. function ordinal (number) {
  12959. return this._ordinal.replace('%d', number);
  12960. }
  12961. var defaultRelativeTime = {
  12962. future : 'in %s',
  12963. past : '%s ago',
  12964. s : 'a few seconds',
  12965. ss : '%d seconds',
  12966. m : 'a minute',
  12967. mm : '%d minutes',
  12968. h : 'an hour',
  12969. hh : '%d hours',
  12970. d : 'a day',
  12971. dd : '%d days',
  12972. M : 'a month',
  12973. MM : '%d months',
  12974. y : 'a year',
  12975. yy : '%d years'
  12976. };
  12977. function relativeTime (number, withoutSuffix, string, isFuture) {
  12978. var output = this._relativeTime[string];
  12979. return (isFunction(output)) ?
  12980. output(number, withoutSuffix, string, isFuture) :
  12981. output.replace(/%d/i, number);
  12982. }
  12983. function pastFuture (diff, output) {
  12984. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  12985. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  12986. }
  12987. var aliases = {};
  12988. function addUnitAlias (unit, shorthand) {
  12989. var lowerCase = unit.toLowerCase();
  12990. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  12991. }
  12992. function normalizeUnits(units) {
  12993. return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
  12994. }
  12995. function normalizeObjectUnits(inputObject) {
  12996. var normalizedInput = {},
  12997. normalizedProp,
  12998. prop;
  12999. for (prop in inputObject) {
  13000. if (hasOwnProp(inputObject, prop)) {
  13001. normalizedProp = normalizeUnits(prop);
  13002. if (normalizedProp) {
  13003. normalizedInput[normalizedProp] = inputObject[prop];
  13004. }
  13005. }
  13006. }
  13007. return normalizedInput;
  13008. }
  13009. var priorities = {};
  13010. function addUnitPriority(unit, priority) {
  13011. priorities[unit] = priority;
  13012. }
  13013. function getPrioritizedUnits(unitsObj) {
  13014. var units = [];
  13015. for (var u in unitsObj) {
  13016. units.push({unit: u, priority: priorities[u]});
  13017. }
  13018. units.sort(function (a, b) {
  13019. return a.priority - b.priority;
  13020. });
  13021. return units;
  13022. }
  13023. function zeroFill(number, targetLength, forceSign) {
  13024. var absNumber = '' + Math.abs(number),
  13025. zerosToFill = targetLength - absNumber.length,
  13026. sign = number >= 0;
  13027. return (sign ? (forceSign ? '+' : '') : '-') +
  13028. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
  13029. }
  13030. var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
  13031. var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
  13032. var formatFunctions = {};
  13033. var formatTokenFunctions = {};
  13034. // token: 'M'
  13035. // padded: ['MM', 2]
  13036. // ordinal: 'Mo'
  13037. // callback: function () { this.month() + 1 }
  13038. function addFormatToken (token, padded, ordinal, callback) {
  13039. var func = callback;
  13040. if (typeof callback === 'string') {
  13041. func = function () {
  13042. return this[callback]();
  13043. };
  13044. }
  13045. if (token) {
  13046. formatTokenFunctions[token] = func;
  13047. }
  13048. if (padded) {
  13049. formatTokenFunctions[padded[0]] = function () {
  13050. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  13051. };
  13052. }
  13053. if (ordinal) {
  13054. formatTokenFunctions[ordinal] = function () {
  13055. return this.localeData().ordinal(func.apply(this, arguments), token);
  13056. };
  13057. }
  13058. }
  13059. function removeFormattingTokens(input) {
  13060. if (input.match(/\[[\s\S]/)) {
  13061. return input.replace(/^\[|\]$/g, '');
  13062. }
  13063. return input.replace(/\\/g, '');
  13064. }
  13065. function makeFormatFunction(format) {
  13066. var array = format.match(formattingTokens), i, length;
  13067. for (i = 0, length = array.length; i < length; i++) {
  13068. if (formatTokenFunctions[array[i]]) {
  13069. array[i] = formatTokenFunctions[array[i]];
  13070. } else {
  13071. array[i] = removeFormattingTokens(array[i]);
  13072. }
  13073. }
  13074. return function (mom) {
  13075. var output = '', i;
  13076. for (i = 0; i < length; i++) {
  13077. output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
  13078. }
  13079. return output;
  13080. };
  13081. }
  13082. // format date using native date object
  13083. function formatMoment(m, format) {
  13084. if (!m.isValid()) {
  13085. return m.localeData().invalidDate();
  13086. }
  13087. format = expandFormat(format, m.localeData());
  13088. formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
  13089. return formatFunctions[format](m);
  13090. }
  13091. function expandFormat(format, locale) {
  13092. var i = 5;
  13093. function replaceLongDateFormatTokens(input) {
  13094. return locale.longDateFormat(input) || input;
  13095. }
  13096. localFormattingTokens.lastIndex = 0;
  13097. while (i >= 0 && localFormattingTokens.test(format)) {
  13098. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  13099. localFormattingTokens.lastIndex = 0;
  13100. i -= 1;
  13101. }
  13102. return format;
  13103. }
  13104. var match1 = /\d/; // 0 - 9
  13105. var match2 = /\d\d/; // 00 - 99
  13106. var match3 = /\d{3}/; // 000 - 999
  13107. var match4 = /\d{4}/; // 0000 - 9999
  13108. var match6 = /[+-]?\d{6}/; // -999999 - 999999
  13109. var match1to2 = /\d\d?/; // 0 - 99
  13110. var match3to4 = /\d\d\d\d?/; // 999 - 9999
  13111. var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
  13112. var match1to3 = /\d{1,3}/; // 0 - 999
  13113. var match1to4 = /\d{1,4}/; // 0 - 9999
  13114. var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
  13115. var matchUnsigned = /\d+/; // 0 - inf
  13116. var matchSigned = /[+-]?\d+/; // -inf - inf
  13117. var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
  13118. var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  13119. var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
  13120. // any word (or two) characters or numbers including two/three word month in arabic.
  13121. // includes scottish gaelic two word and hyphenated months
  13122. var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;
  13123. var regexes = {};
  13124. function addRegexToken (token, regex, strictRegex) {
  13125. regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
  13126. return (isStrict && strictRegex) ? strictRegex : regex;
  13127. };
  13128. }
  13129. function getParseRegexForToken (token, config) {
  13130. if (!hasOwnProp(regexes, token)) {
  13131. return new RegExp(unescapeFormat(token));
  13132. }
  13133. return regexes[token](config._strict, config._locale);
  13134. }
  13135. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  13136. function unescapeFormat(s) {
  13137. return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  13138. return p1 || p2 || p3 || p4;
  13139. }));
  13140. }
  13141. function regexEscape(s) {
  13142. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  13143. }
  13144. var tokens = {};
  13145. function addParseToken (token, callback) {
  13146. var i, func = callback;
  13147. if (typeof token === 'string') {
  13148. token = [token];
  13149. }
  13150. if (isNumber(callback)) {
  13151. func = function (input, array) {
  13152. array[callback] = toInt(input);
  13153. };
  13154. }
  13155. for (i = 0; i < token.length; i++) {
  13156. tokens[token[i]] = func;
  13157. }
  13158. }
  13159. function addWeekParseToken (token, callback) {
  13160. addParseToken(token, function (input, array, config, token) {
  13161. config._w = config._w || {};
  13162. callback(input, config._w, config, token);
  13163. });
  13164. }
  13165. function addTimeToArrayFromToken(token, input, config) {
  13166. if (input != null && hasOwnProp(tokens, token)) {
  13167. tokens[token](input, config._a, config, token);
  13168. }
  13169. }
  13170. var YEAR = 0;
  13171. var MONTH = 1;
  13172. var DATE = 2;
  13173. var HOUR = 3;
  13174. var MINUTE = 4;
  13175. var SECOND = 5;
  13176. var MILLISECOND = 6;
  13177. var WEEK = 7;
  13178. var WEEKDAY = 8;
  13179. // FORMATTING
  13180. addFormatToken('Y', 0, 0, function () {
  13181. var y = this.year();
  13182. return y <= 9999 ? '' + y : '+' + y;
  13183. });
  13184. addFormatToken(0, ['YY', 2], 0, function () {
  13185. return this.year() % 100;
  13186. });
  13187. addFormatToken(0, ['YYYY', 4], 0, 'year');
  13188. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  13189. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  13190. // ALIASES
  13191. addUnitAlias('year', 'y');
  13192. // PRIORITIES
  13193. addUnitPriority('year', 1);
  13194. // PARSING
  13195. addRegexToken('Y', matchSigned);
  13196. addRegexToken('YY', match1to2, match2);
  13197. addRegexToken('YYYY', match1to4, match4);
  13198. addRegexToken('YYYYY', match1to6, match6);
  13199. addRegexToken('YYYYYY', match1to6, match6);
  13200. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  13201. addParseToken('YYYY', function (input, array) {
  13202. array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  13203. });
  13204. addParseToken('YY', function (input, array) {
  13205. array[YEAR] = hooks.parseTwoDigitYear(input);
  13206. });
  13207. addParseToken('Y', function (input, array) {
  13208. array[YEAR] = parseInt(input, 10);
  13209. });
  13210. // HELPERS
  13211. function daysInYear(year) {
  13212. return isLeapYear(year) ? 366 : 365;
  13213. }
  13214. function isLeapYear(year) {
  13215. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  13216. }
  13217. // HOOKS
  13218. hooks.parseTwoDigitYear = function (input) {
  13219. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  13220. };
  13221. // MOMENTS
  13222. var getSetYear = makeGetSet('FullYear', true);
  13223. function getIsLeapYear () {
  13224. return isLeapYear(this.year());
  13225. }
  13226. function makeGetSet (unit, keepTime) {
  13227. return function (value) {
  13228. if (value != null) {
  13229. set$1(this, unit, value);
  13230. hooks.updateOffset(this, keepTime);
  13231. return this;
  13232. } else {
  13233. return get(this, unit);
  13234. }
  13235. };
  13236. }
  13237. function get (mom, unit) {
  13238. return mom.isValid() ?
  13239. mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
  13240. }
  13241. function set$1 (mom, unit, value) {
  13242. if (mom.isValid() && !isNaN(value)) {
  13243. if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
  13244. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
  13245. }
  13246. else {
  13247. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  13248. }
  13249. }
  13250. }
  13251. // MOMENTS
  13252. function stringGet (units) {
  13253. units = normalizeUnits(units);
  13254. if (isFunction(this[units])) {
  13255. return this[units]();
  13256. }
  13257. return this;
  13258. }
  13259. function stringSet (units, value) {
  13260. if (typeof units === 'object') {
  13261. units = normalizeObjectUnits(units);
  13262. var prioritized = getPrioritizedUnits(units);
  13263. for (var i = 0; i < prioritized.length; i++) {
  13264. this[prioritized[i].unit](units[prioritized[i].unit]);
  13265. }
  13266. } else {
  13267. units = normalizeUnits(units);
  13268. if (isFunction(this[units])) {
  13269. return this[units](value);
  13270. }
  13271. }
  13272. return this;
  13273. }
  13274. function mod(n, x) {
  13275. return ((n % x) + x) % x;
  13276. }
  13277. var indexOf;
  13278. if (Array.prototype.indexOf) {
  13279. indexOf = Array.prototype.indexOf;
  13280. } else {
  13281. indexOf = function (o) {
  13282. // I know
  13283. var i;
  13284. for (i = 0; i < this.length; ++i) {
  13285. if (this[i] === o) {
  13286. return i;
  13287. }
  13288. }
  13289. return -1;
  13290. };
  13291. }
  13292. function daysInMonth(year, month) {
  13293. if (isNaN(year) || isNaN(month)) {
  13294. return NaN;
  13295. }
  13296. var modMonth = mod(month, 12);
  13297. year += (month - modMonth) / 12;
  13298. return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2);
  13299. }
  13300. // FORMATTING
  13301. addFormatToken('M', ['MM', 2], 'Mo', function () {
  13302. return this.month() + 1;
  13303. });
  13304. addFormatToken('MMM', 0, 0, function (format) {
  13305. return this.localeData().monthsShort(this, format);
  13306. });
  13307. addFormatToken('MMMM', 0, 0, function (format) {
  13308. return this.localeData().months(this, format);
  13309. });
  13310. // ALIASES
  13311. addUnitAlias('month', 'M');
  13312. // PRIORITY
  13313. addUnitPriority('month', 8);
  13314. // PARSING
  13315. addRegexToken('M', match1to2);
  13316. addRegexToken('MM', match1to2, match2);
  13317. addRegexToken('MMM', function (isStrict, locale) {
  13318. return locale.monthsShortRegex(isStrict);
  13319. });
  13320. addRegexToken('MMMM', function (isStrict, locale) {
  13321. return locale.monthsRegex(isStrict);
  13322. });
  13323. addParseToken(['M', 'MM'], function (input, array) {
  13324. array[MONTH] = toInt(input) - 1;
  13325. });
  13326. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  13327. var month = config._locale.monthsParse(input, token, config._strict);
  13328. // if we didn't find a month name, mark the date as invalid.
  13329. if (month != null) {
  13330. array[MONTH] = month;
  13331. } else {
  13332. getParsingFlags(config).invalidMonth = input;
  13333. }
  13334. });
  13335. // LOCALES
  13336. var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
  13337. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
  13338. function localeMonths (m, format) {
  13339. if (!m) {
  13340. return isArray(this._months) ? this._months :
  13341. this._months['standalone'];
  13342. }
  13343. return isArray(this._months) ? this._months[m.month()] :
  13344. this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
  13345. }
  13346. var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
  13347. function localeMonthsShort (m, format) {
  13348. if (!m) {
  13349. return isArray(this._monthsShort) ? this._monthsShort :
  13350. this._monthsShort['standalone'];
  13351. }
  13352. return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
  13353. this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
  13354. }
  13355. function handleStrictParse(monthName, format, strict) {
  13356. var i, ii, mom, llc = monthName.toLocaleLowerCase();
  13357. if (!this._monthsParse) {
  13358. // this is not used
  13359. this._monthsParse = [];
  13360. this._longMonthsParse = [];
  13361. this._shortMonthsParse = [];
  13362. for (i = 0; i < 12; ++i) {
  13363. mom = createUTC([2000, i]);
  13364. this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
  13365. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  13366. }
  13367. }
  13368. if (strict) {
  13369. if (format === 'MMM') {
  13370. ii = indexOf.call(this._shortMonthsParse, llc);
  13371. return ii !== -1 ? ii : null;
  13372. } else {
  13373. ii = indexOf.call(this._longMonthsParse, llc);
  13374. return ii !== -1 ? ii : null;
  13375. }
  13376. } else {
  13377. if (format === 'MMM') {
  13378. ii = indexOf.call(this._shortMonthsParse, llc);
  13379. if (ii !== -1) {
  13380. return ii;
  13381. }
  13382. ii = indexOf.call(this._longMonthsParse, llc);
  13383. return ii !== -1 ? ii : null;
  13384. } else {
  13385. ii = indexOf.call(this._longMonthsParse, llc);
  13386. if (ii !== -1) {
  13387. return ii;
  13388. }
  13389. ii = indexOf.call(this._shortMonthsParse, llc);
  13390. return ii !== -1 ? ii : null;
  13391. }
  13392. }
  13393. }
  13394. function localeMonthsParse (monthName, format, strict) {
  13395. var i, mom, regex;
  13396. if (this._monthsParseExact) {
  13397. return handleStrictParse.call(this, monthName, format, strict);
  13398. }
  13399. if (!this._monthsParse) {
  13400. this._monthsParse = [];
  13401. this._longMonthsParse = [];
  13402. this._shortMonthsParse = [];
  13403. }
  13404. // TODO: add sorting
  13405. // Sorting makes sure if one month (or abbr) is a prefix of another
  13406. // see sorting in computeMonthsParse
  13407. for (i = 0; i < 12; i++) {
  13408. // make the regex if we don't have it already
  13409. mom = createUTC([2000, i]);
  13410. if (strict && !this._longMonthsParse[i]) {
  13411. this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
  13412. this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
  13413. }
  13414. if (!strict && !this._monthsParse[i]) {
  13415. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  13416. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  13417. }
  13418. // test the regex
  13419. if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
  13420. return i;
  13421. } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
  13422. return i;
  13423. } else if (!strict && this._monthsParse[i].test(monthName)) {
  13424. return i;
  13425. }
  13426. }
  13427. }
  13428. // MOMENTS
  13429. function setMonth (mom, value) {
  13430. var dayOfMonth;
  13431. if (!mom.isValid()) {
  13432. // No op
  13433. return mom;
  13434. }
  13435. if (typeof value === 'string') {
  13436. if (/^\d+$/.test(value)) {
  13437. value = toInt(value);
  13438. } else {
  13439. value = mom.localeData().monthsParse(value);
  13440. // TODO: Another silent failure?
  13441. if (!isNumber(value)) {
  13442. return mom;
  13443. }
  13444. }
  13445. }
  13446. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  13447. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  13448. return mom;
  13449. }
  13450. function getSetMonth (value) {
  13451. if (value != null) {
  13452. setMonth(this, value);
  13453. hooks.updateOffset(this, true);
  13454. return this;
  13455. } else {
  13456. return get(this, 'Month');
  13457. }
  13458. }
  13459. function getDaysInMonth () {
  13460. return daysInMonth(this.year(), this.month());
  13461. }
  13462. var defaultMonthsShortRegex = matchWord;
  13463. function monthsShortRegex (isStrict) {
  13464. if (this._monthsParseExact) {
  13465. if (!hasOwnProp(this, '_monthsRegex')) {
  13466. computeMonthsParse.call(this);
  13467. }
  13468. if (isStrict) {
  13469. return this._monthsShortStrictRegex;
  13470. } else {
  13471. return this._monthsShortRegex;
  13472. }
  13473. } else {
  13474. if (!hasOwnProp(this, '_monthsShortRegex')) {
  13475. this._monthsShortRegex = defaultMonthsShortRegex;
  13476. }
  13477. return this._monthsShortStrictRegex && isStrict ?
  13478. this._monthsShortStrictRegex : this._monthsShortRegex;
  13479. }
  13480. }
  13481. var defaultMonthsRegex = matchWord;
  13482. function monthsRegex (isStrict) {
  13483. if (this._monthsParseExact) {
  13484. if (!hasOwnProp(this, '_monthsRegex')) {
  13485. computeMonthsParse.call(this);
  13486. }
  13487. if (isStrict) {
  13488. return this._monthsStrictRegex;
  13489. } else {
  13490. return this._monthsRegex;
  13491. }
  13492. } else {
  13493. if (!hasOwnProp(this, '_monthsRegex')) {
  13494. this._monthsRegex = defaultMonthsRegex;
  13495. }
  13496. return this._monthsStrictRegex && isStrict ?
  13497. this._monthsStrictRegex : this._monthsRegex;
  13498. }
  13499. }
  13500. function computeMonthsParse () {
  13501. function cmpLenRev(a, b) {
  13502. return b.length - a.length;
  13503. }
  13504. var shortPieces = [], longPieces = [], mixedPieces = [],
  13505. i, mom;
  13506. for (i = 0; i < 12; i++) {
  13507. // make the regex if we don't have it already
  13508. mom = createUTC([2000, i]);
  13509. shortPieces.push(this.monthsShort(mom, ''));
  13510. longPieces.push(this.months(mom, ''));
  13511. mixedPieces.push(this.months(mom, ''));
  13512. mixedPieces.push(this.monthsShort(mom, ''));
  13513. }
  13514. // Sorting makes sure if one month (or abbr) is a prefix of another it
  13515. // will match the longer piece.
  13516. shortPieces.sort(cmpLenRev);
  13517. longPieces.sort(cmpLenRev);
  13518. mixedPieces.sort(cmpLenRev);
  13519. for (i = 0; i < 12; i++) {
  13520. shortPieces[i] = regexEscape(shortPieces[i]);
  13521. longPieces[i] = regexEscape(longPieces[i]);
  13522. }
  13523. for (i = 0; i < 24; i++) {
  13524. mixedPieces[i] = regexEscape(mixedPieces[i]);
  13525. }
  13526. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  13527. this._monthsShortRegex = this._monthsRegex;
  13528. this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  13529. this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  13530. }
  13531. function createDate (y, m, d, h, M, s, ms) {
  13532. // can't just apply() to create a date:
  13533. // https://stackoverflow.com/q/181348
  13534. var date;
  13535. // the date constructor remaps years 0-99 to 1900-1999
  13536. if (y < 100 && y >= 0) {
  13537. // preserve leap years using a full 400 year cycle, then reset
  13538. date = new Date(y + 400, m, d, h, M, s, ms);
  13539. if (isFinite(date.getFullYear())) {
  13540. date.setFullYear(y);
  13541. }
  13542. } else {
  13543. date = new Date(y, m, d, h, M, s, ms);
  13544. }
  13545. return date;
  13546. }
  13547. function createUTCDate (y) {
  13548. var date;
  13549. // the Date.UTC function remaps years 0-99 to 1900-1999
  13550. if (y < 100 && y >= 0) {
  13551. var args = Array.prototype.slice.call(arguments);
  13552. // preserve leap years using a full 400 year cycle, then reset
  13553. args[0] = y + 400;
  13554. date = new Date(Date.UTC.apply(null, args));
  13555. if (isFinite(date.getUTCFullYear())) {
  13556. date.setUTCFullYear(y);
  13557. }
  13558. } else {
  13559. date = new Date(Date.UTC.apply(null, arguments));
  13560. }
  13561. return date;
  13562. }
  13563. // start-of-first-week - start-of-year
  13564. function firstWeekOffset(year, dow, doy) {
  13565. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  13566. fwd = 7 + dow - doy,
  13567. // first-week day local weekday -- which local weekday is fwd
  13568. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  13569. return -fwdlw + fwd - 1;
  13570. }
  13571. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  13572. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  13573. var localWeekday = (7 + weekday - dow) % 7,
  13574. weekOffset = firstWeekOffset(year, dow, doy),
  13575. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  13576. resYear, resDayOfYear;
  13577. if (dayOfYear <= 0) {
  13578. resYear = year - 1;
  13579. resDayOfYear = daysInYear(resYear) + dayOfYear;
  13580. } else if (dayOfYear > daysInYear(year)) {
  13581. resYear = year + 1;
  13582. resDayOfYear = dayOfYear - daysInYear(year);
  13583. } else {
  13584. resYear = year;
  13585. resDayOfYear = dayOfYear;
  13586. }
  13587. return {
  13588. year: resYear,
  13589. dayOfYear: resDayOfYear
  13590. };
  13591. }
  13592. function weekOfYear(mom, dow, doy) {
  13593. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  13594. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  13595. resWeek, resYear;
  13596. if (week < 1) {
  13597. resYear = mom.year() - 1;
  13598. resWeek = week + weeksInYear(resYear, dow, doy);
  13599. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  13600. resWeek = week - weeksInYear(mom.year(), dow, doy);
  13601. resYear = mom.year() + 1;
  13602. } else {
  13603. resYear = mom.year();
  13604. resWeek = week;
  13605. }
  13606. return {
  13607. week: resWeek,
  13608. year: resYear
  13609. };
  13610. }
  13611. function weeksInYear(year, dow, doy) {
  13612. var weekOffset = firstWeekOffset(year, dow, doy),
  13613. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  13614. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  13615. }
  13616. // FORMATTING
  13617. addFormatToken('w', ['ww', 2], 'wo', 'week');
  13618. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  13619. // ALIASES
  13620. addUnitAlias('week', 'w');
  13621. addUnitAlias('isoWeek', 'W');
  13622. // PRIORITIES
  13623. addUnitPriority('week', 5);
  13624. addUnitPriority('isoWeek', 5);
  13625. // PARSING
  13626. addRegexToken('w', match1to2);
  13627. addRegexToken('ww', match1to2, match2);
  13628. addRegexToken('W', match1to2);
  13629. addRegexToken('WW', match1to2, match2);
  13630. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
  13631. week[token.substr(0, 1)] = toInt(input);
  13632. });
  13633. // HELPERS
  13634. // LOCALES
  13635. function localeWeek (mom) {
  13636. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  13637. }
  13638. var defaultLocaleWeek = {
  13639. dow : 0, // Sunday is the first day of the week.
  13640. doy : 6 // The week that contains Jan 6th is the first week of the year.
  13641. };
  13642. function localeFirstDayOfWeek () {
  13643. return this._week.dow;
  13644. }
  13645. function localeFirstDayOfYear () {
  13646. return this._week.doy;
  13647. }
  13648. // MOMENTS
  13649. function getSetWeek (input) {
  13650. var week = this.localeData().week(this);
  13651. return input == null ? week : this.add((input - week) * 7, 'd');
  13652. }
  13653. function getSetISOWeek (input) {
  13654. var week = weekOfYear(this, 1, 4).week;
  13655. return input == null ? week : this.add((input - week) * 7, 'd');
  13656. }
  13657. // FORMATTING
  13658. addFormatToken('d', 0, 'do', 'day');
  13659. addFormatToken('dd', 0, 0, function (format) {
  13660. return this.localeData().weekdaysMin(this, format);
  13661. });
  13662. addFormatToken('ddd', 0, 0, function (format) {
  13663. return this.localeData().weekdaysShort(this, format);
  13664. });
  13665. addFormatToken('dddd', 0, 0, function (format) {
  13666. return this.localeData().weekdays(this, format);
  13667. });
  13668. addFormatToken('e', 0, 0, 'weekday');
  13669. addFormatToken('E', 0, 0, 'isoWeekday');
  13670. // ALIASES
  13671. addUnitAlias('day', 'd');
  13672. addUnitAlias('weekday', 'e');
  13673. addUnitAlias('isoWeekday', 'E');
  13674. // PRIORITY
  13675. addUnitPriority('day', 11);
  13676. addUnitPriority('weekday', 11);
  13677. addUnitPriority('isoWeekday', 11);
  13678. // PARSING
  13679. addRegexToken('d', match1to2);
  13680. addRegexToken('e', match1to2);
  13681. addRegexToken('E', match1to2);
  13682. addRegexToken('dd', function (isStrict, locale) {
  13683. return locale.weekdaysMinRegex(isStrict);
  13684. });
  13685. addRegexToken('ddd', function (isStrict, locale) {
  13686. return locale.weekdaysShortRegex(isStrict);
  13687. });
  13688. addRegexToken('dddd', function (isStrict, locale) {
  13689. return locale.weekdaysRegex(isStrict);
  13690. });
  13691. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  13692. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  13693. // if we didn't get a weekday name, mark the date as invalid
  13694. if (weekday != null) {
  13695. week.d = weekday;
  13696. } else {
  13697. getParsingFlags(config).invalidWeekday = input;
  13698. }
  13699. });
  13700. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  13701. week[token] = toInt(input);
  13702. });
  13703. // HELPERS
  13704. function parseWeekday(input, locale) {
  13705. if (typeof input !== 'string') {
  13706. return input;
  13707. }
  13708. if (!isNaN(input)) {
  13709. return parseInt(input, 10);
  13710. }
  13711. input = locale.weekdaysParse(input);
  13712. if (typeof input === 'number') {
  13713. return input;
  13714. }
  13715. return null;
  13716. }
  13717. function parseIsoWeekday(input, locale) {
  13718. if (typeof input === 'string') {
  13719. return locale.weekdaysParse(input) % 7 || 7;
  13720. }
  13721. return isNaN(input) ? null : input;
  13722. }
  13723. // LOCALES
  13724. function shiftWeekdays (ws, n) {
  13725. return ws.slice(n, 7).concat(ws.slice(0, n));
  13726. }
  13727. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
  13728. function localeWeekdays (m, format) {
  13729. var weekdays = isArray(this._weekdays) ? this._weekdays :
  13730. this._weekdays[(m && m !== true && this._weekdays.isFormat.test(format)) ? 'format' : 'standalone'];
  13731. return (m === true) ? shiftWeekdays(weekdays, this._week.dow)
  13732. : (m) ? weekdays[m.day()] : weekdays;
  13733. }
  13734. var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
  13735. function localeWeekdaysShort (m) {
  13736. return (m === true) ? shiftWeekdays(this._weekdaysShort, this._week.dow)
  13737. : (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
  13738. }
  13739. var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
  13740. function localeWeekdaysMin (m) {
  13741. return (m === true) ? shiftWeekdays(this._weekdaysMin, this._week.dow)
  13742. : (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
  13743. }
  13744. function handleStrictParse$1(weekdayName, format, strict) {
  13745. var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
  13746. if (!this._weekdaysParse) {
  13747. this._weekdaysParse = [];
  13748. this._shortWeekdaysParse = [];
  13749. this._minWeekdaysParse = [];
  13750. for (i = 0; i < 7; ++i) {
  13751. mom = createUTC([2000, 1]).day(i);
  13752. this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
  13753. this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
  13754. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  13755. }
  13756. }
  13757. if (strict) {
  13758. if (format === 'dddd') {
  13759. ii = indexOf.call(this._weekdaysParse, llc);
  13760. return ii !== -1 ? ii : null;
  13761. } else if (format === 'ddd') {
  13762. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13763. return ii !== -1 ? ii : null;
  13764. } else {
  13765. ii = indexOf.call(this._minWeekdaysParse, llc);
  13766. return ii !== -1 ? ii : null;
  13767. }
  13768. } else {
  13769. if (format === 'dddd') {
  13770. ii = indexOf.call(this._weekdaysParse, llc);
  13771. if (ii !== -1) {
  13772. return ii;
  13773. }
  13774. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13775. if (ii !== -1) {
  13776. return ii;
  13777. }
  13778. ii = indexOf.call(this._minWeekdaysParse, llc);
  13779. return ii !== -1 ? ii : null;
  13780. } else if (format === 'ddd') {
  13781. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13782. if (ii !== -1) {
  13783. return ii;
  13784. }
  13785. ii = indexOf.call(this._weekdaysParse, llc);
  13786. if (ii !== -1) {
  13787. return ii;
  13788. }
  13789. ii = indexOf.call(this._minWeekdaysParse, llc);
  13790. return ii !== -1 ? ii : null;
  13791. } else {
  13792. ii = indexOf.call(this._minWeekdaysParse, llc);
  13793. if (ii !== -1) {
  13794. return ii;
  13795. }
  13796. ii = indexOf.call(this._weekdaysParse, llc);
  13797. if (ii !== -1) {
  13798. return ii;
  13799. }
  13800. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13801. return ii !== -1 ? ii : null;
  13802. }
  13803. }
  13804. }
  13805. function localeWeekdaysParse (weekdayName, format, strict) {
  13806. var i, mom, regex;
  13807. if (this._weekdaysParseExact) {
  13808. return handleStrictParse$1.call(this, weekdayName, format, strict);
  13809. }
  13810. if (!this._weekdaysParse) {
  13811. this._weekdaysParse = [];
  13812. this._minWeekdaysParse = [];
  13813. this._shortWeekdaysParse = [];
  13814. this._fullWeekdaysParse = [];
  13815. }
  13816. for (i = 0; i < 7; i++) {
  13817. // make the regex if we don't have it already
  13818. mom = createUTC([2000, 1]).day(i);
  13819. if (strict && !this._fullWeekdaysParse[i]) {
  13820. this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i');
  13821. this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i');
  13822. this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i');
  13823. }
  13824. if (!this._weekdaysParse[i]) {
  13825. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  13826. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  13827. }
  13828. // test the regex
  13829. if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
  13830. return i;
  13831. } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
  13832. return i;
  13833. } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
  13834. return i;
  13835. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  13836. return i;
  13837. }
  13838. }
  13839. }
  13840. // MOMENTS
  13841. function getSetDayOfWeek (input) {
  13842. if (!this.isValid()) {
  13843. return input != null ? this : NaN;
  13844. }
  13845. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  13846. if (input != null) {
  13847. input = parseWeekday(input, this.localeData());
  13848. return this.add(input - day, 'd');
  13849. } else {
  13850. return day;
  13851. }
  13852. }
  13853. function getSetLocaleDayOfWeek (input) {
  13854. if (!this.isValid()) {
  13855. return input != null ? this : NaN;
  13856. }
  13857. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  13858. return input == null ? weekday : this.add(input - weekday, 'd');
  13859. }
  13860. function getSetISODayOfWeek (input) {
  13861. if (!this.isValid()) {
  13862. return input != null ? this : NaN;
  13863. }
  13864. // behaves the same as moment#day except
  13865. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  13866. // as a setter, sunday should belong to the previous week.
  13867. if (input != null) {
  13868. var weekday = parseIsoWeekday(input, this.localeData());
  13869. return this.day(this.day() % 7 ? weekday : weekday - 7);
  13870. } else {
  13871. return this.day() || 7;
  13872. }
  13873. }
  13874. var defaultWeekdaysRegex = matchWord;
  13875. function weekdaysRegex (isStrict) {
  13876. if (this._weekdaysParseExact) {
  13877. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13878. computeWeekdaysParse.call(this);
  13879. }
  13880. if (isStrict) {
  13881. return this._weekdaysStrictRegex;
  13882. } else {
  13883. return this._weekdaysRegex;
  13884. }
  13885. } else {
  13886. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13887. this._weekdaysRegex = defaultWeekdaysRegex;
  13888. }
  13889. return this._weekdaysStrictRegex && isStrict ?
  13890. this._weekdaysStrictRegex : this._weekdaysRegex;
  13891. }
  13892. }
  13893. var defaultWeekdaysShortRegex = matchWord;
  13894. function weekdaysShortRegex (isStrict) {
  13895. if (this._weekdaysParseExact) {
  13896. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13897. computeWeekdaysParse.call(this);
  13898. }
  13899. if (isStrict) {
  13900. return this._weekdaysShortStrictRegex;
  13901. } else {
  13902. return this._weekdaysShortRegex;
  13903. }
  13904. } else {
  13905. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  13906. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  13907. }
  13908. return this._weekdaysShortStrictRegex && isStrict ?
  13909. this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
  13910. }
  13911. }
  13912. var defaultWeekdaysMinRegex = matchWord;
  13913. function weekdaysMinRegex (isStrict) {
  13914. if (this._weekdaysParseExact) {
  13915. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13916. computeWeekdaysParse.call(this);
  13917. }
  13918. if (isStrict) {
  13919. return this._weekdaysMinStrictRegex;
  13920. } else {
  13921. return this._weekdaysMinRegex;
  13922. }
  13923. } else {
  13924. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  13925. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  13926. }
  13927. return this._weekdaysMinStrictRegex && isStrict ?
  13928. this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
  13929. }
  13930. }
  13931. function computeWeekdaysParse () {
  13932. function cmpLenRev(a, b) {
  13933. return b.length - a.length;
  13934. }
  13935. var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
  13936. i, mom, minp, shortp, longp;
  13937. for (i = 0; i < 7; i++) {
  13938. // make the regex if we don't have it already
  13939. mom = createUTC([2000, 1]).day(i);
  13940. minp = this.weekdaysMin(mom, '');
  13941. shortp = this.weekdaysShort(mom, '');
  13942. longp = this.weekdays(mom, '');
  13943. minPieces.push(minp);
  13944. shortPieces.push(shortp);
  13945. longPieces.push(longp);
  13946. mixedPieces.push(minp);
  13947. mixedPieces.push(shortp);
  13948. mixedPieces.push(longp);
  13949. }
  13950. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  13951. // will match the longer piece.
  13952. minPieces.sort(cmpLenRev);
  13953. shortPieces.sort(cmpLenRev);
  13954. longPieces.sort(cmpLenRev);
  13955. mixedPieces.sort(cmpLenRev);
  13956. for (i = 0; i < 7; i++) {
  13957. shortPieces[i] = regexEscape(shortPieces[i]);
  13958. longPieces[i] = regexEscape(longPieces[i]);
  13959. mixedPieces[i] = regexEscape(mixedPieces[i]);
  13960. }
  13961. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  13962. this._weekdaysShortRegex = this._weekdaysRegex;
  13963. this._weekdaysMinRegex = this._weekdaysRegex;
  13964. this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  13965. this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  13966. this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
  13967. }
  13968. // FORMATTING
  13969. function hFormat() {
  13970. return this.hours() % 12 || 12;
  13971. }
  13972. function kFormat() {
  13973. return this.hours() || 24;
  13974. }
  13975. addFormatToken('H', ['HH', 2], 0, 'hour');
  13976. addFormatToken('h', ['hh', 2], 0, hFormat);
  13977. addFormatToken('k', ['kk', 2], 0, kFormat);
  13978. addFormatToken('hmm', 0, 0, function () {
  13979. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  13980. });
  13981. addFormatToken('hmmss', 0, 0, function () {
  13982. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
  13983. zeroFill(this.seconds(), 2);
  13984. });
  13985. addFormatToken('Hmm', 0, 0, function () {
  13986. return '' + this.hours() + zeroFill(this.minutes(), 2);
  13987. });
  13988. addFormatToken('Hmmss', 0, 0, function () {
  13989. return '' + this.hours() + zeroFill(this.minutes(), 2) +
  13990. zeroFill(this.seconds(), 2);
  13991. });
  13992. function meridiem (token, lowercase) {
  13993. addFormatToken(token, 0, 0, function () {
  13994. return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
  13995. });
  13996. }
  13997. meridiem('a', true);
  13998. meridiem('A', false);
  13999. // ALIASES
  14000. addUnitAlias('hour', 'h');
  14001. // PRIORITY
  14002. addUnitPriority('hour', 13);
  14003. // PARSING
  14004. function matchMeridiem (isStrict, locale) {
  14005. return locale._meridiemParse;
  14006. }
  14007. addRegexToken('a', matchMeridiem);
  14008. addRegexToken('A', matchMeridiem);
  14009. addRegexToken('H', match1to2);
  14010. addRegexToken('h', match1to2);
  14011. addRegexToken('k', match1to2);
  14012. addRegexToken('HH', match1to2, match2);
  14013. addRegexToken('hh', match1to2, match2);
  14014. addRegexToken('kk', match1to2, match2);
  14015. addRegexToken('hmm', match3to4);
  14016. addRegexToken('hmmss', match5to6);
  14017. addRegexToken('Hmm', match3to4);
  14018. addRegexToken('Hmmss', match5to6);
  14019. addParseToken(['H', 'HH'], HOUR);
  14020. addParseToken(['k', 'kk'], function (input, array, config) {
  14021. var kInput = toInt(input);
  14022. array[HOUR] = kInput === 24 ? 0 : kInput;
  14023. });
  14024. addParseToken(['a', 'A'], function (input, array, config) {
  14025. config._isPm = config._locale.isPM(input);
  14026. config._meridiem = input;
  14027. });
  14028. addParseToken(['h', 'hh'], function (input, array, config) {
  14029. array[HOUR] = toInt(input);
  14030. getParsingFlags(config).bigHour = true;
  14031. });
  14032. addParseToken('hmm', function (input, array, config) {
  14033. var pos = input.length - 2;
  14034. array[HOUR] = toInt(input.substr(0, pos));
  14035. array[MINUTE] = toInt(input.substr(pos));
  14036. getParsingFlags(config).bigHour = true;
  14037. });
  14038. addParseToken('hmmss', function (input, array, config) {
  14039. var pos1 = input.length - 4;
  14040. var pos2 = input.length - 2;
  14041. array[HOUR] = toInt(input.substr(0, pos1));
  14042. array[MINUTE] = toInt(input.substr(pos1, 2));
  14043. array[SECOND] = toInt(input.substr(pos2));
  14044. getParsingFlags(config).bigHour = true;
  14045. });
  14046. addParseToken('Hmm', function (input, array, config) {
  14047. var pos = input.length - 2;
  14048. array[HOUR] = toInt(input.substr(0, pos));
  14049. array[MINUTE] = toInt(input.substr(pos));
  14050. });
  14051. addParseToken('Hmmss', function (input, array, config) {
  14052. var pos1 = input.length - 4;
  14053. var pos2 = input.length - 2;
  14054. array[HOUR] = toInt(input.substr(0, pos1));
  14055. array[MINUTE] = toInt(input.substr(pos1, 2));
  14056. array[SECOND] = toInt(input.substr(pos2));
  14057. });
  14058. // LOCALES
  14059. function localeIsPM (input) {
  14060. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  14061. // Using charAt should be more compatible.
  14062. return ((input + '').toLowerCase().charAt(0) === 'p');
  14063. }
  14064. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
  14065. function localeMeridiem (hours, minutes, isLower) {
  14066. if (hours > 11) {
  14067. return isLower ? 'pm' : 'PM';
  14068. } else {
  14069. return isLower ? 'am' : 'AM';
  14070. }
  14071. }
  14072. // MOMENTS
  14073. // Setting the hour should keep the time, because the user explicitly
  14074. // specified which hour they want. So trying to maintain the same hour (in
  14075. // a new timezone) makes sense. Adding/subtracting hours does not follow
  14076. // this rule.
  14077. var getSetHour = makeGetSet('Hours', true);
  14078. var baseConfig = {
  14079. calendar: defaultCalendar,
  14080. longDateFormat: defaultLongDateFormat,
  14081. invalidDate: defaultInvalidDate,
  14082. ordinal: defaultOrdinal,
  14083. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  14084. relativeTime: defaultRelativeTime,
  14085. months: defaultLocaleMonths,
  14086. monthsShort: defaultLocaleMonthsShort,
  14087. week: defaultLocaleWeek,
  14088. weekdays: defaultLocaleWeekdays,
  14089. weekdaysMin: defaultLocaleWeekdaysMin,
  14090. weekdaysShort: defaultLocaleWeekdaysShort,
  14091. meridiemParse: defaultLocaleMeridiemParse
  14092. };
  14093. // internal storage for locale config files
  14094. var locales = {};
  14095. var localeFamilies = {};
  14096. var globalLocale;
  14097. function normalizeLocale(key) {
  14098. return key ? key.toLowerCase().replace('_', '-') : key;
  14099. }
  14100. // pick the locale from the array
  14101. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  14102. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  14103. function chooseLocale(names) {
  14104. var i = 0, j, next, locale, split;
  14105. while (i < names.length) {
  14106. split = normalizeLocale(names[i]).split('-');
  14107. j = split.length;
  14108. next = normalizeLocale(names[i + 1]);
  14109. next = next ? next.split('-') : null;
  14110. while (j > 0) {
  14111. locale = loadLocale(split.slice(0, j).join('-'));
  14112. if (locale) {
  14113. return locale;
  14114. }
  14115. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  14116. //the next array item is better than a shallower substring of this one
  14117. break;
  14118. }
  14119. j--;
  14120. }
  14121. i++;
  14122. }
  14123. return globalLocale;
  14124. }
  14125. function loadLocale(name) {
  14126. var oldLocale = null;
  14127. // TODO: Find a better way to register and load all the locales in Node
  14128. if (!locales[name] && ('object' !== 'undefined') &&
  14129. module && module.exports) {
  14130. try {
  14131. oldLocale = globalLocale._abbr;
  14132. var aliasedRequire = commonjsRequire;
  14133. aliasedRequire('./locale/' + name);
  14134. getSetGlobalLocale(oldLocale);
  14135. } catch (e) {}
  14136. }
  14137. return locales[name];
  14138. }
  14139. // This function will load locale and then set the global locale. If
  14140. // no arguments are passed in, it will simply return the current global
  14141. // locale key.
  14142. function getSetGlobalLocale (key, values) {
  14143. var data;
  14144. if (key) {
  14145. if (isUndefined(values)) {
  14146. data = getLocale(key);
  14147. }
  14148. else {
  14149. data = defineLocale(key, values);
  14150. }
  14151. if (data) {
  14152. // moment.duration._locale = moment._locale = data;
  14153. globalLocale = data;
  14154. }
  14155. else {
  14156. if ((typeof console !== 'undefined') && console.warn) {
  14157. //warn user if arguments are passed but the locale could not be set
  14158. console.warn('Locale ' + key + ' not found. Did you forget to load it?');
  14159. }
  14160. }
  14161. }
  14162. return globalLocale._abbr;
  14163. }
  14164. function defineLocale (name, config) {
  14165. if (config !== null) {
  14166. var locale, parentConfig = baseConfig;
  14167. config.abbr = name;
  14168. if (locales[name] != null) {
  14169. deprecateSimple('defineLocaleOverride',
  14170. 'use moment.updateLocale(localeName, config) to change ' +
  14171. 'an existing locale. moment.defineLocale(localeName, ' +
  14172. 'config) should only be used for creating a new locale ' +
  14173. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
  14174. parentConfig = locales[name]._config;
  14175. } else if (config.parentLocale != null) {
  14176. if (locales[config.parentLocale] != null) {
  14177. parentConfig = locales[config.parentLocale]._config;
  14178. } else {
  14179. locale = loadLocale(config.parentLocale);
  14180. if (locale != null) {
  14181. parentConfig = locale._config;
  14182. } else {
  14183. if (!localeFamilies[config.parentLocale]) {
  14184. localeFamilies[config.parentLocale] = [];
  14185. }
  14186. localeFamilies[config.parentLocale].push({
  14187. name: name,
  14188. config: config
  14189. });
  14190. return null;
  14191. }
  14192. }
  14193. }
  14194. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  14195. if (localeFamilies[name]) {
  14196. localeFamilies[name].forEach(function (x) {
  14197. defineLocale(x.name, x.config);
  14198. });
  14199. }
  14200. // backwards compat for now: also set the locale
  14201. // make sure we set the locale AFTER all child locales have been
  14202. // created, so we won't end up with the child locale set.
  14203. getSetGlobalLocale(name);
  14204. return locales[name];
  14205. } else {
  14206. // useful for testing
  14207. delete locales[name];
  14208. return null;
  14209. }
  14210. }
  14211. function updateLocale(name, config) {
  14212. if (config != null) {
  14213. var locale, tmpLocale, parentConfig = baseConfig;
  14214. // MERGE
  14215. tmpLocale = loadLocale(name);
  14216. if (tmpLocale != null) {
  14217. parentConfig = tmpLocale._config;
  14218. }
  14219. config = mergeConfigs(parentConfig, config);
  14220. locale = new Locale(config);
  14221. locale.parentLocale = locales[name];
  14222. locales[name] = locale;
  14223. // backwards compat for now: also set the locale
  14224. getSetGlobalLocale(name);
  14225. } else {
  14226. // pass null for config to unupdate, useful for tests
  14227. if (locales[name] != null) {
  14228. if (locales[name].parentLocale != null) {
  14229. locales[name] = locales[name].parentLocale;
  14230. } else if (locales[name] != null) {
  14231. delete locales[name];
  14232. }
  14233. }
  14234. }
  14235. return locales[name];
  14236. }
  14237. // returns locale data
  14238. function getLocale (key) {
  14239. var locale;
  14240. if (key && key._locale && key._locale._abbr) {
  14241. key = key._locale._abbr;
  14242. }
  14243. if (!key) {
  14244. return globalLocale;
  14245. }
  14246. if (!isArray(key)) {
  14247. //short-circuit everything else
  14248. locale = loadLocale(key);
  14249. if (locale) {
  14250. return locale;
  14251. }
  14252. key = [key];
  14253. }
  14254. return chooseLocale(key);
  14255. }
  14256. function listLocales() {
  14257. return keys(locales);
  14258. }
  14259. function checkOverflow (m) {
  14260. var overflow;
  14261. var a = m._a;
  14262. if (a && getParsingFlags(m).overflow === -2) {
  14263. overflow =
  14264. a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
  14265. a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
  14266. a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
  14267. a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
  14268. a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
  14269. a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
  14270. -1;
  14271. if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  14272. overflow = DATE;
  14273. }
  14274. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  14275. overflow = WEEK;
  14276. }
  14277. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  14278. overflow = WEEKDAY;
  14279. }
  14280. getParsingFlags(m).overflow = overflow;
  14281. }
  14282. return m;
  14283. }
  14284. // Pick the first defined of two or three arguments.
  14285. function defaults(a, b, c) {
  14286. if (a != null) {
  14287. return a;
  14288. }
  14289. if (b != null) {
  14290. return b;
  14291. }
  14292. return c;
  14293. }
  14294. function currentDateArray(config) {
  14295. // hooks is actually the exported moment object
  14296. var nowValue = new Date(hooks.now());
  14297. if (config._useUTC) {
  14298. return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
  14299. }
  14300. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  14301. }
  14302. // convert an array to a date.
  14303. // the array should mirror the parameters below
  14304. // note: all values past the year are optional and will default to the lowest possible value.
  14305. // [year, month, day , hour, minute, second, millisecond]
  14306. function configFromArray (config) {
  14307. var i, date, input = [], currentDate, expectedWeekday, yearToUse;
  14308. if (config._d) {
  14309. return;
  14310. }
  14311. currentDate = currentDateArray(config);
  14312. //compute day of the year from weeks and weekdays
  14313. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  14314. dayOfYearFromWeekInfo(config);
  14315. }
  14316. //if the day of the year is set, figure out what it is
  14317. if (config._dayOfYear != null) {
  14318. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  14319. if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
  14320. getParsingFlags(config)._overflowDayOfYear = true;
  14321. }
  14322. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  14323. config._a[MONTH] = date.getUTCMonth();
  14324. config._a[DATE] = date.getUTCDate();
  14325. }
  14326. // Default to current date.
  14327. // * if no year, month, day of month are given, default to today
  14328. // * if day of month is given, default month and year
  14329. // * if month is given, default only year
  14330. // * if year is given, don't default anything
  14331. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  14332. config._a[i] = input[i] = currentDate[i];
  14333. }
  14334. // Zero out whatever was not defaulted, including time
  14335. for (; i < 7; i++) {
  14336. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  14337. }
  14338. // Check for 24:00:00.000
  14339. if (config._a[HOUR] === 24 &&
  14340. config._a[MINUTE] === 0 &&
  14341. config._a[SECOND] === 0 &&
  14342. config._a[MILLISECOND] === 0) {
  14343. config._nextDay = true;
  14344. config._a[HOUR] = 0;
  14345. }
  14346. config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
  14347. expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();
  14348. // Apply timezone offset from input. The actual utcOffset can be changed
  14349. // with parseZone.
  14350. if (config._tzm != null) {
  14351. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  14352. }
  14353. if (config._nextDay) {
  14354. config._a[HOUR] = 24;
  14355. }
  14356. // check for mismatching day of week
  14357. if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
  14358. getParsingFlags(config).weekdayMismatch = true;
  14359. }
  14360. }
  14361. function dayOfYearFromWeekInfo(config) {
  14362. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
  14363. w = config._w;
  14364. if (w.GG != null || w.W != null || w.E != null) {
  14365. dow = 1;
  14366. doy = 4;
  14367. // TODO: We need to take the current isoWeekYear, but that depends on
  14368. // how we interpret now (local, utc, fixed offset). So create
  14369. // a now version of current config (take local/utc/offset flags, and
  14370. // create now).
  14371. weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
  14372. week = defaults(w.W, 1);
  14373. weekday = defaults(w.E, 1);
  14374. if (weekday < 1 || weekday > 7) {
  14375. weekdayOverflow = true;
  14376. }
  14377. } else {
  14378. dow = config._locale._week.dow;
  14379. doy = config._locale._week.doy;
  14380. var curWeek = weekOfYear(createLocal(), dow, doy);
  14381. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  14382. // Default to current week.
  14383. week = defaults(w.w, curWeek.week);
  14384. if (w.d != null) {
  14385. // weekday -- low day numbers are considered next week
  14386. weekday = w.d;
  14387. if (weekday < 0 || weekday > 6) {
  14388. weekdayOverflow = true;
  14389. }
  14390. } else if (w.e != null) {
  14391. // local weekday -- counting starts from beginning of week
  14392. weekday = w.e + dow;
  14393. if (w.e < 0 || w.e > 6) {
  14394. weekdayOverflow = true;
  14395. }
  14396. } else {
  14397. // default to beginning of week
  14398. weekday = dow;
  14399. }
  14400. }
  14401. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  14402. getParsingFlags(config)._overflowWeeks = true;
  14403. } else if (weekdayOverflow != null) {
  14404. getParsingFlags(config)._overflowWeekday = true;
  14405. } else {
  14406. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  14407. config._a[YEAR] = temp.year;
  14408. config._dayOfYear = temp.dayOfYear;
  14409. }
  14410. }
  14411. // iso 8601 regex
  14412. // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
  14413. var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
  14414. var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
  14415. var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
  14416. var isoDates = [
  14417. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  14418. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  14419. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  14420. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  14421. ['YYYY-DDD', /\d{4}-\d{3}/],
  14422. ['YYYY-MM', /\d{4}-\d\d/, false],
  14423. ['YYYYYYMMDD', /[+-]\d{10}/],
  14424. ['YYYYMMDD', /\d{8}/],
  14425. // YYYYMM is NOT allowed by the standard
  14426. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  14427. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  14428. ['YYYYDDD', /\d{7}/]
  14429. ];
  14430. // iso time formats and regexes
  14431. var isoTimes = [
  14432. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  14433. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  14434. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  14435. ['HH:mm', /\d\d:\d\d/],
  14436. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  14437. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  14438. ['HHmmss', /\d\d\d\d\d\d/],
  14439. ['HHmm', /\d\d\d\d/],
  14440. ['HH', /\d\d/]
  14441. ];
  14442. var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
  14443. // date from iso format
  14444. function configFromISO(config) {
  14445. var i, l,
  14446. string = config._i,
  14447. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  14448. allowTime, dateFormat, timeFormat, tzFormat;
  14449. if (match) {
  14450. getParsingFlags(config).iso = true;
  14451. for (i = 0, l = isoDates.length; i < l; i++) {
  14452. if (isoDates[i][1].exec(match[1])) {
  14453. dateFormat = isoDates[i][0];
  14454. allowTime = isoDates[i][2] !== false;
  14455. break;
  14456. }
  14457. }
  14458. if (dateFormat == null) {
  14459. config._isValid = false;
  14460. return;
  14461. }
  14462. if (match[3]) {
  14463. for (i = 0, l = isoTimes.length; i < l; i++) {
  14464. if (isoTimes[i][1].exec(match[3])) {
  14465. // match[2] should be 'T' or space
  14466. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  14467. break;
  14468. }
  14469. }
  14470. if (timeFormat == null) {
  14471. config._isValid = false;
  14472. return;
  14473. }
  14474. }
  14475. if (!allowTime && timeFormat != null) {
  14476. config._isValid = false;
  14477. return;
  14478. }
  14479. if (match[4]) {
  14480. if (tzRegex.exec(match[4])) {
  14481. tzFormat = 'Z';
  14482. } else {
  14483. config._isValid = false;
  14484. return;
  14485. }
  14486. }
  14487. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  14488. configFromStringAndFormat(config);
  14489. } else {
  14490. config._isValid = false;
  14491. }
  14492. }
  14493. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  14494. var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;
  14495. function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
  14496. var result = [
  14497. untruncateYear(yearStr),
  14498. defaultLocaleMonthsShort.indexOf(monthStr),
  14499. parseInt(dayStr, 10),
  14500. parseInt(hourStr, 10),
  14501. parseInt(minuteStr, 10)
  14502. ];
  14503. if (secondStr) {
  14504. result.push(parseInt(secondStr, 10));
  14505. }
  14506. return result;
  14507. }
  14508. function untruncateYear(yearStr) {
  14509. var year = parseInt(yearStr, 10);
  14510. if (year <= 49) {
  14511. return 2000 + year;
  14512. } else if (year <= 999) {
  14513. return 1900 + year;
  14514. }
  14515. return year;
  14516. }
  14517. function preprocessRFC2822(s) {
  14518. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  14519. return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  14520. }
  14521. function checkWeekday(weekdayStr, parsedInput, config) {
  14522. if (weekdayStr) {
  14523. // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
  14524. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  14525. weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
  14526. if (weekdayProvided !== weekdayActual) {
  14527. getParsingFlags(config).weekdayMismatch = true;
  14528. config._isValid = false;
  14529. return false;
  14530. }
  14531. }
  14532. return true;
  14533. }
  14534. var obsOffsets = {
  14535. UT: 0,
  14536. GMT: 0,
  14537. EDT: -4 * 60,
  14538. EST: -5 * 60,
  14539. CDT: -5 * 60,
  14540. CST: -6 * 60,
  14541. MDT: -6 * 60,
  14542. MST: -7 * 60,
  14543. PDT: -7 * 60,
  14544. PST: -8 * 60
  14545. };
  14546. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  14547. if (obsOffset) {
  14548. return obsOffsets[obsOffset];
  14549. } else if (militaryOffset) {
  14550. // the only allowed military tz is Z
  14551. return 0;
  14552. } else {
  14553. var hm = parseInt(numOffset, 10);
  14554. var m = hm % 100, h = (hm - m) / 100;
  14555. return h * 60 + m;
  14556. }
  14557. }
  14558. // date and time from ref 2822 format
  14559. function configFromRFC2822(config) {
  14560. var match = rfc2822.exec(preprocessRFC2822(config._i));
  14561. if (match) {
  14562. var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
  14563. if (!checkWeekday(match[1], parsedArray, config)) {
  14564. return;
  14565. }
  14566. config._a = parsedArray;
  14567. config._tzm = calculateOffset(match[8], match[9], match[10]);
  14568. config._d = createUTCDate.apply(null, config._a);
  14569. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  14570. getParsingFlags(config).rfc2822 = true;
  14571. } else {
  14572. config._isValid = false;
  14573. }
  14574. }
  14575. // date from iso format or fallback
  14576. function configFromString(config) {
  14577. var matched = aspNetJsonRegex.exec(config._i);
  14578. if (matched !== null) {
  14579. config._d = new Date(+matched[1]);
  14580. return;
  14581. }
  14582. configFromISO(config);
  14583. if (config._isValid === false) {
  14584. delete config._isValid;
  14585. } else {
  14586. return;
  14587. }
  14588. configFromRFC2822(config);
  14589. if (config._isValid === false) {
  14590. delete config._isValid;
  14591. } else {
  14592. return;
  14593. }
  14594. // Final attempt, use Input Fallback
  14595. hooks.createFromInputFallback(config);
  14596. }
  14597. hooks.createFromInputFallback = deprecate(
  14598. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  14599. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  14600. 'discouraged and will be removed in an upcoming major release. Please refer to ' +
  14601. 'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  14602. function (config) {
  14603. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  14604. }
  14605. );
  14606. // constant that refers to the ISO standard
  14607. hooks.ISO_8601 = function () {};
  14608. // constant that refers to the RFC 2822 form
  14609. hooks.RFC_2822 = function () {};
  14610. // date from string and format string
  14611. function configFromStringAndFormat(config) {
  14612. // TODO: Move this to another part of the creation flow to prevent circular deps
  14613. if (config._f === hooks.ISO_8601) {
  14614. configFromISO(config);
  14615. return;
  14616. }
  14617. if (config._f === hooks.RFC_2822) {
  14618. configFromRFC2822(config);
  14619. return;
  14620. }
  14621. config._a = [];
  14622. getParsingFlags(config).empty = true;
  14623. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  14624. var string = '' + config._i,
  14625. i, parsedInput, tokens, token, skipped,
  14626. stringLength = string.length,
  14627. totalParsedInputLength = 0;
  14628. tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
  14629. for (i = 0; i < tokens.length; i++) {
  14630. token = tokens[i];
  14631. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  14632. // console.log('token', token, 'parsedInput', parsedInput,
  14633. // 'regex', getParseRegexForToken(token, config));
  14634. if (parsedInput) {
  14635. skipped = string.substr(0, string.indexOf(parsedInput));
  14636. if (skipped.length > 0) {
  14637. getParsingFlags(config).unusedInput.push(skipped);
  14638. }
  14639. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  14640. totalParsedInputLength += parsedInput.length;
  14641. }
  14642. // don't parse if it's not a known token
  14643. if (formatTokenFunctions[token]) {
  14644. if (parsedInput) {
  14645. getParsingFlags(config).empty = false;
  14646. }
  14647. else {
  14648. getParsingFlags(config).unusedTokens.push(token);
  14649. }
  14650. addTimeToArrayFromToken(token, parsedInput, config);
  14651. }
  14652. else if (config._strict && !parsedInput) {
  14653. getParsingFlags(config).unusedTokens.push(token);
  14654. }
  14655. }
  14656. // add remaining unparsed input length to the string
  14657. getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
  14658. if (string.length > 0) {
  14659. getParsingFlags(config).unusedInput.push(string);
  14660. }
  14661. // clear _12h flag if hour is <= 12
  14662. if (config._a[HOUR] <= 12 &&
  14663. getParsingFlags(config).bigHour === true &&
  14664. config._a[HOUR] > 0) {
  14665. getParsingFlags(config).bigHour = undefined;
  14666. }
  14667. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  14668. getParsingFlags(config).meridiem = config._meridiem;
  14669. // handle meridiem
  14670. config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
  14671. configFromArray(config);
  14672. checkOverflow(config);
  14673. }
  14674. function meridiemFixWrap (locale, hour, meridiem) {
  14675. var isPm;
  14676. if (meridiem == null) {
  14677. // nothing to do
  14678. return hour;
  14679. }
  14680. if (locale.meridiemHour != null) {
  14681. return locale.meridiemHour(hour, meridiem);
  14682. } else if (locale.isPM != null) {
  14683. // Fallback
  14684. isPm = locale.isPM(meridiem);
  14685. if (isPm && hour < 12) {
  14686. hour += 12;
  14687. }
  14688. if (!isPm && hour === 12) {
  14689. hour = 0;
  14690. }
  14691. return hour;
  14692. } else {
  14693. // this is not supposed to happen
  14694. return hour;
  14695. }
  14696. }
  14697. // date from string and array of format strings
  14698. function configFromStringAndArray(config) {
  14699. var tempConfig,
  14700. bestMoment,
  14701. scoreToBeat,
  14702. i,
  14703. currentScore;
  14704. if (config._f.length === 0) {
  14705. getParsingFlags(config).invalidFormat = true;
  14706. config._d = new Date(NaN);
  14707. return;
  14708. }
  14709. for (i = 0; i < config._f.length; i++) {
  14710. currentScore = 0;
  14711. tempConfig = copyConfig({}, config);
  14712. if (config._useUTC != null) {
  14713. tempConfig._useUTC = config._useUTC;
  14714. }
  14715. tempConfig._f = config._f[i];
  14716. configFromStringAndFormat(tempConfig);
  14717. if (!isValid(tempConfig)) {
  14718. continue;
  14719. }
  14720. // if there is any input that was not parsed add a penalty for that format
  14721. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  14722. //or tokens
  14723. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  14724. getParsingFlags(tempConfig).score = currentScore;
  14725. if (scoreToBeat == null || currentScore < scoreToBeat) {
  14726. scoreToBeat = currentScore;
  14727. bestMoment = tempConfig;
  14728. }
  14729. }
  14730. extend(config, bestMoment || tempConfig);
  14731. }
  14732. function configFromObject(config) {
  14733. if (config._d) {
  14734. return;
  14735. }
  14736. var i = normalizeObjectUnits(config._i);
  14737. config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
  14738. return obj && parseInt(obj, 10);
  14739. });
  14740. configFromArray(config);
  14741. }
  14742. function createFromConfig (config) {
  14743. var res = new Moment(checkOverflow(prepareConfig(config)));
  14744. if (res._nextDay) {
  14745. // Adding is smart enough around DST
  14746. res.add(1, 'd');
  14747. res._nextDay = undefined;
  14748. }
  14749. return res;
  14750. }
  14751. function prepareConfig (config) {
  14752. var input = config._i,
  14753. format = config._f;
  14754. config._locale = config._locale || getLocale(config._l);
  14755. if (input === null || (format === undefined && input === '')) {
  14756. return createInvalid({nullInput: true});
  14757. }
  14758. if (typeof input === 'string') {
  14759. config._i = input = config._locale.preparse(input);
  14760. }
  14761. if (isMoment(input)) {
  14762. return new Moment(checkOverflow(input));
  14763. } else if (isDate(input)) {
  14764. config._d = input;
  14765. } else if (isArray(format)) {
  14766. configFromStringAndArray(config);
  14767. } else if (format) {
  14768. configFromStringAndFormat(config);
  14769. } else {
  14770. configFromInput(config);
  14771. }
  14772. if (!isValid(config)) {
  14773. config._d = null;
  14774. }
  14775. return config;
  14776. }
  14777. function configFromInput(config) {
  14778. var input = config._i;
  14779. if (isUndefined(input)) {
  14780. config._d = new Date(hooks.now());
  14781. } else if (isDate(input)) {
  14782. config._d = new Date(input.valueOf());
  14783. } else if (typeof input === 'string') {
  14784. configFromString(config);
  14785. } else if (isArray(input)) {
  14786. config._a = map(input.slice(0), function (obj) {
  14787. return parseInt(obj, 10);
  14788. });
  14789. configFromArray(config);
  14790. } else if (isObject(input)) {
  14791. configFromObject(config);
  14792. } else if (isNumber(input)) {
  14793. // from milliseconds
  14794. config._d = new Date(input);
  14795. } else {
  14796. hooks.createFromInputFallback(config);
  14797. }
  14798. }
  14799. function createLocalOrUTC (input, format, locale, strict, isUTC) {
  14800. var c = {};
  14801. if (locale === true || locale === false) {
  14802. strict = locale;
  14803. locale = undefined;
  14804. }
  14805. if ((isObject(input) && isObjectEmpty(input)) ||
  14806. (isArray(input) && input.length === 0)) {
  14807. input = undefined;
  14808. }
  14809. // object construction must be done this way.
  14810. // https://github.com/moment/moment/issues/1423
  14811. c._isAMomentObject = true;
  14812. c._useUTC = c._isUTC = isUTC;
  14813. c._l = locale;
  14814. c._i = input;
  14815. c._f = format;
  14816. c._strict = strict;
  14817. return createFromConfig(c);
  14818. }
  14819. function createLocal (input, format, locale, strict) {
  14820. return createLocalOrUTC(input, format, locale, strict, false);
  14821. }
  14822. var prototypeMin = deprecate(
  14823. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  14824. function () {
  14825. var other = createLocal.apply(null, arguments);
  14826. if (this.isValid() && other.isValid()) {
  14827. return other < this ? this : other;
  14828. } else {
  14829. return createInvalid();
  14830. }
  14831. }
  14832. );
  14833. var prototypeMax = deprecate(
  14834. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  14835. function () {
  14836. var other = createLocal.apply(null, arguments);
  14837. if (this.isValid() && other.isValid()) {
  14838. return other > this ? this : other;
  14839. } else {
  14840. return createInvalid();
  14841. }
  14842. }
  14843. );
  14844. // Pick a moment m from moments so that m[fn](other) is true for all
  14845. // other. This relies on the function fn to be transitive.
  14846. //
  14847. // moments should either be an array of moment objects or an array, whose
  14848. // first element is an array of moment objects.
  14849. function pickBy(fn, moments) {
  14850. var res, i;
  14851. if (moments.length === 1 && isArray(moments[0])) {
  14852. moments = moments[0];
  14853. }
  14854. if (!moments.length) {
  14855. return createLocal();
  14856. }
  14857. res = moments[0];
  14858. for (i = 1; i < moments.length; ++i) {
  14859. if (!moments[i].isValid() || moments[i][fn](res)) {
  14860. res = moments[i];
  14861. }
  14862. }
  14863. return res;
  14864. }
  14865. // TODO: Use [].sort instead?
  14866. function min () {
  14867. var args = [].slice.call(arguments, 0);
  14868. return pickBy('isBefore', args);
  14869. }
  14870. function max () {
  14871. var args = [].slice.call(arguments, 0);
  14872. return pickBy('isAfter', args);
  14873. }
  14874. var now = function () {
  14875. return Date.now ? Date.now() : +(new Date());
  14876. };
  14877. var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
  14878. function isDurationValid(m) {
  14879. for (var key in m) {
  14880. if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
  14881. return false;
  14882. }
  14883. }
  14884. var unitHasDecimal = false;
  14885. for (var i = 0; i < ordering.length; ++i) {
  14886. if (m[ordering[i]]) {
  14887. if (unitHasDecimal) {
  14888. return false; // only allow non-integers for smallest unit
  14889. }
  14890. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  14891. unitHasDecimal = true;
  14892. }
  14893. }
  14894. }
  14895. return true;
  14896. }
  14897. function isValid$1() {
  14898. return this._isValid;
  14899. }
  14900. function createInvalid$1() {
  14901. return createDuration(NaN);
  14902. }
  14903. function Duration (duration) {
  14904. var normalizedInput = normalizeObjectUnits(duration),
  14905. years = normalizedInput.year || 0,
  14906. quarters = normalizedInput.quarter || 0,
  14907. months = normalizedInput.month || 0,
  14908. weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
  14909. days = normalizedInput.day || 0,
  14910. hours = normalizedInput.hour || 0,
  14911. minutes = normalizedInput.minute || 0,
  14912. seconds = normalizedInput.second || 0,
  14913. milliseconds = normalizedInput.millisecond || 0;
  14914. this._isValid = isDurationValid(normalizedInput);
  14915. // representation for dateAddRemove
  14916. this._milliseconds = +milliseconds +
  14917. seconds * 1e3 + // 1000
  14918. minutes * 6e4 + // 1000 * 60
  14919. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  14920. // Because of dateAddRemove treats 24 hours as different from a
  14921. // day when working around DST, we need to store them separately
  14922. this._days = +days +
  14923. weeks * 7;
  14924. // It is impossible to translate months into days without knowing
  14925. // which months you are are talking about, so we have to store
  14926. // it separately.
  14927. this._months = +months +
  14928. quarters * 3 +
  14929. years * 12;
  14930. this._data = {};
  14931. this._locale = getLocale();
  14932. this._bubble();
  14933. }
  14934. function isDuration (obj) {
  14935. return obj instanceof Duration;
  14936. }
  14937. function absRound (number) {
  14938. if (number < 0) {
  14939. return Math.round(-1 * number) * -1;
  14940. } else {
  14941. return Math.round(number);
  14942. }
  14943. }
  14944. // FORMATTING
  14945. function offset (token, separator) {
  14946. addFormatToken(token, 0, 0, function () {
  14947. var offset = this.utcOffset();
  14948. var sign = '+';
  14949. if (offset < 0) {
  14950. offset = -offset;
  14951. sign = '-';
  14952. }
  14953. return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
  14954. });
  14955. }
  14956. offset('Z', ':');
  14957. offset('ZZ', '');
  14958. // PARSING
  14959. addRegexToken('Z', matchShortOffset);
  14960. addRegexToken('ZZ', matchShortOffset);
  14961. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  14962. config._useUTC = true;
  14963. config._tzm = offsetFromString(matchShortOffset, input);
  14964. });
  14965. // HELPERS
  14966. // timezone chunker
  14967. // '+10:00' > ['10', '00']
  14968. // '-1530' > ['-15', '30']
  14969. var chunkOffset = /([\+\-]|\d\d)/gi;
  14970. function offsetFromString(matcher, string) {
  14971. var matches = (string || '').match(matcher);
  14972. if (matches === null) {
  14973. return null;
  14974. }
  14975. var chunk = matches[matches.length - 1] || [];
  14976. var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  14977. var minutes = +(parts[1] * 60) + toInt(parts[2]);
  14978. return minutes === 0 ?
  14979. 0 :
  14980. parts[0] === '+' ? minutes : -minutes;
  14981. }
  14982. // Return a moment from input, that is local/utc/zone equivalent to model.
  14983. function cloneWithOffset(input, model) {
  14984. var res, diff;
  14985. if (model._isUTC) {
  14986. res = model.clone();
  14987. diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
  14988. // Use low-level api, because this fn is low-level api.
  14989. res._d.setTime(res._d.valueOf() + diff);
  14990. hooks.updateOffset(res, false);
  14991. return res;
  14992. } else {
  14993. return createLocal(input).local();
  14994. }
  14995. }
  14996. function getDateOffset (m) {
  14997. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  14998. // https://github.com/moment/moment/pull/1871
  14999. return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
  15000. }
  15001. // HOOKS
  15002. // This function will be called whenever a moment is mutated.
  15003. // It is intended to keep the offset in sync with the timezone.
  15004. hooks.updateOffset = function () {};
  15005. // MOMENTS
  15006. // keepLocalTime = true means only change the timezone, without
  15007. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  15008. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  15009. // +0200, so we adjust the time as needed, to be valid.
  15010. //
  15011. // Keeping the time actually adds/subtracts (one hour)
  15012. // from the actual represented time. That is why we call updateOffset
  15013. // a second time. In case it wants us to change the offset again
  15014. // _changeInProgress == true case, then we have to adjust, because
  15015. // there is no such time in the given timezone.
  15016. function getSetOffset (input, keepLocalTime, keepMinutes) {
  15017. var offset = this._offset || 0,
  15018. localAdjust;
  15019. if (!this.isValid()) {
  15020. return input != null ? this : NaN;
  15021. }
  15022. if (input != null) {
  15023. if (typeof input === 'string') {
  15024. input = offsetFromString(matchShortOffset, input);
  15025. if (input === null) {
  15026. return this;
  15027. }
  15028. } else if (Math.abs(input) < 16 && !keepMinutes) {
  15029. input = input * 60;
  15030. }
  15031. if (!this._isUTC && keepLocalTime) {
  15032. localAdjust = getDateOffset(this);
  15033. }
  15034. this._offset = input;
  15035. this._isUTC = true;
  15036. if (localAdjust != null) {
  15037. this.add(localAdjust, 'm');
  15038. }
  15039. if (offset !== input) {
  15040. if (!keepLocalTime || this._changeInProgress) {
  15041. addSubtract(this, createDuration(input - offset, 'm'), 1, false);
  15042. } else if (!this._changeInProgress) {
  15043. this._changeInProgress = true;
  15044. hooks.updateOffset(this, true);
  15045. this._changeInProgress = null;
  15046. }
  15047. }
  15048. return this;
  15049. } else {
  15050. return this._isUTC ? offset : getDateOffset(this);
  15051. }
  15052. }
  15053. function getSetZone (input, keepLocalTime) {
  15054. if (input != null) {
  15055. if (typeof input !== 'string') {
  15056. input = -input;
  15057. }
  15058. this.utcOffset(input, keepLocalTime);
  15059. return this;
  15060. } else {
  15061. return -this.utcOffset();
  15062. }
  15063. }
  15064. function setOffsetToUTC (keepLocalTime) {
  15065. return this.utcOffset(0, keepLocalTime);
  15066. }
  15067. function setOffsetToLocal (keepLocalTime) {
  15068. if (this._isUTC) {
  15069. this.utcOffset(0, keepLocalTime);
  15070. this._isUTC = false;
  15071. if (keepLocalTime) {
  15072. this.subtract(getDateOffset(this), 'm');
  15073. }
  15074. }
  15075. return this;
  15076. }
  15077. function setOffsetToParsedOffset () {
  15078. if (this._tzm != null) {
  15079. this.utcOffset(this._tzm, false, true);
  15080. } else if (typeof this._i === 'string') {
  15081. var tZone = offsetFromString(matchOffset, this._i);
  15082. if (tZone != null) {
  15083. this.utcOffset(tZone);
  15084. }
  15085. else {
  15086. this.utcOffset(0, true);
  15087. }
  15088. }
  15089. return this;
  15090. }
  15091. function hasAlignedHourOffset (input) {
  15092. if (!this.isValid()) {
  15093. return false;
  15094. }
  15095. input = input ? createLocal(input).utcOffset() : 0;
  15096. return (this.utcOffset() - input) % 60 === 0;
  15097. }
  15098. function isDaylightSavingTime () {
  15099. return (
  15100. this.utcOffset() > this.clone().month(0).utcOffset() ||
  15101. this.utcOffset() > this.clone().month(5).utcOffset()
  15102. );
  15103. }
  15104. function isDaylightSavingTimeShifted () {
  15105. if (!isUndefined(this._isDSTShifted)) {
  15106. return this._isDSTShifted;
  15107. }
  15108. var c = {};
  15109. copyConfig(c, this);
  15110. c = prepareConfig(c);
  15111. if (c._a) {
  15112. var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  15113. this._isDSTShifted = this.isValid() &&
  15114. compareArrays(c._a, other.toArray()) > 0;
  15115. } else {
  15116. this._isDSTShifted = false;
  15117. }
  15118. return this._isDSTShifted;
  15119. }
  15120. function isLocal () {
  15121. return this.isValid() ? !this._isUTC : false;
  15122. }
  15123. function isUtcOffset () {
  15124. return this.isValid() ? this._isUTC : false;
  15125. }
  15126. function isUtc () {
  15127. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  15128. }
  15129. // ASP.NET json date format regex
  15130. var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;
  15131. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  15132. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  15133. // and further modified to allow for strings containing both week and day
  15134. var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  15135. function createDuration (input, key) {
  15136. var duration = input,
  15137. // matching against regexp is expensive, do it on demand
  15138. match = null,
  15139. sign,
  15140. ret,
  15141. diffRes;
  15142. if (isDuration(input)) {
  15143. duration = {
  15144. ms : input._milliseconds,
  15145. d : input._days,
  15146. M : input._months
  15147. };
  15148. } else if (isNumber(input)) {
  15149. duration = {};
  15150. if (key) {
  15151. duration[key] = input;
  15152. } else {
  15153. duration.milliseconds = input;
  15154. }
  15155. } else if (!!(match = aspNetRegex.exec(input))) {
  15156. sign = (match[1] === '-') ? -1 : 1;
  15157. duration = {
  15158. y : 0,
  15159. d : toInt(match[DATE]) * sign,
  15160. h : toInt(match[HOUR]) * sign,
  15161. m : toInt(match[MINUTE]) * sign,
  15162. s : toInt(match[SECOND]) * sign,
  15163. ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
  15164. };
  15165. } else if (!!(match = isoRegex.exec(input))) {
  15166. sign = (match[1] === '-') ? -1 : 1;
  15167. duration = {
  15168. y : parseIso(match[2], sign),
  15169. M : parseIso(match[3], sign),
  15170. w : parseIso(match[4], sign),
  15171. d : parseIso(match[5], sign),
  15172. h : parseIso(match[6], sign),
  15173. m : parseIso(match[7], sign),
  15174. s : parseIso(match[8], sign)
  15175. };
  15176. } else if (duration == null) {// checks for null or undefined
  15177. duration = {};
  15178. } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
  15179. diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
  15180. duration = {};
  15181. duration.ms = diffRes.milliseconds;
  15182. duration.M = diffRes.months;
  15183. }
  15184. ret = new Duration(duration);
  15185. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  15186. ret._locale = input._locale;
  15187. }
  15188. return ret;
  15189. }
  15190. createDuration.fn = Duration.prototype;
  15191. createDuration.invalid = createInvalid$1;
  15192. function parseIso (inp, sign) {
  15193. // We'd normally use ~~inp for this, but unfortunately it also
  15194. // converts floats to ints.
  15195. // inp may be undefined, so careful calling replace on it.
  15196. var res = inp && parseFloat(inp.replace(',', '.'));
  15197. // apply sign while we're at it
  15198. return (isNaN(res) ? 0 : res) * sign;
  15199. }
  15200. function positiveMomentsDifference(base, other) {
  15201. var res = {};
  15202. res.months = other.month() - base.month() +
  15203. (other.year() - base.year()) * 12;
  15204. if (base.clone().add(res.months, 'M').isAfter(other)) {
  15205. --res.months;
  15206. }
  15207. res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
  15208. return res;
  15209. }
  15210. function momentsDifference(base, other) {
  15211. var res;
  15212. if (!(base.isValid() && other.isValid())) {
  15213. return {milliseconds: 0, months: 0};
  15214. }
  15215. other = cloneWithOffset(other, base);
  15216. if (base.isBefore(other)) {
  15217. res = positiveMomentsDifference(base, other);
  15218. } else {
  15219. res = positiveMomentsDifference(other, base);
  15220. res.milliseconds = -res.milliseconds;
  15221. res.months = -res.months;
  15222. }
  15223. return res;
  15224. }
  15225. // TODO: remove 'name' arg after deprecation is removed
  15226. function createAdder(direction, name) {
  15227. return function (val, period) {
  15228. var dur, tmp;
  15229. //invert the arguments, but complain about it
  15230. if (period !== null && !isNaN(+period)) {
  15231. deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
  15232. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
  15233. tmp = val; val = period; period = tmp;
  15234. }
  15235. val = typeof val === 'string' ? +val : val;
  15236. dur = createDuration(val, period);
  15237. addSubtract(this, dur, direction);
  15238. return this;
  15239. };
  15240. }
  15241. function addSubtract (mom, duration, isAdding, updateOffset) {
  15242. var milliseconds = duration._milliseconds,
  15243. days = absRound(duration._days),
  15244. months = absRound(duration._months);
  15245. if (!mom.isValid()) {
  15246. // No op
  15247. return;
  15248. }
  15249. updateOffset = updateOffset == null ? true : updateOffset;
  15250. if (months) {
  15251. setMonth(mom, get(mom, 'Month') + months * isAdding);
  15252. }
  15253. if (days) {
  15254. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  15255. }
  15256. if (milliseconds) {
  15257. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  15258. }
  15259. if (updateOffset) {
  15260. hooks.updateOffset(mom, days || months);
  15261. }
  15262. }
  15263. var add = createAdder(1, 'add');
  15264. var subtract = createAdder(-1, 'subtract');
  15265. function getCalendarFormat(myMoment, now) {
  15266. var diff = myMoment.diff(now, 'days', true);
  15267. return diff < -6 ? 'sameElse' :
  15268. diff < -1 ? 'lastWeek' :
  15269. diff < 0 ? 'lastDay' :
  15270. diff < 1 ? 'sameDay' :
  15271. diff < 2 ? 'nextDay' :
  15272. diff < 7 ? 'nextWeek' : 'sameElse';
  15273. }
  15274. function calendar$1 (time, formats) {
  15275. // We want to compare the start of today, vs this.
  15276. // Getting start-of-today depends on whether we're local/utc/offset or not.
  15277. var now = time || createLocal(),
  15278. sod = cloneWithOffset(now, this).startOf('day'),
  15279. format = hooks.calendarFormat(this, sod) || 'sameElse';
  15280. var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
  15281. return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
  15282. }
  15283. function clone () {
  15284. return new Moment(this);
  15285. }
  15286. function isAfter (input, units) {
  15287. var localInput = isMoment(input) ? input : createLocal(input);
  15288. if (!(this.isValid() && localInput.isValid())) {
  15289. return false;
  15290. }
  15291. units = normalizeUnits(units) || 'millisecond';
  15292. if (units === 'millisecond') {
  15293. return this.valueOf() > localInput.valueOf();
  15294. } else {
  15295. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  15296. }
  15297. }
  15298. function isBefore (input, units) {
  15299. var localInput = isMoment(input) ? input : createLocal(input);
  15300. if (!(this.isValid() && localInput.isValid())) {
  15301. return false;
  15302. }
  15303. units = normalizeUnits(units) || 'millisecond';
  15304. if (units === 'millisecond') {
  15305. return this.valueOf() < localInput.valueOf();
  15306. } else {
  15307. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  15308. }
  15309. }
  15310. function isBetween (from, to, units, inclusivity) {
  15311. var localFrom = isMoment(from) ? from : createLocal(from),
  15312. localTo = isMoment(to) ? to : createLocal(to);
  15313. if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
  15314. return false;
  15315. }
  15316. inclusivity = inclusivity || '()';
  15317. return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) &&
  15318. (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
  15319. }
  15320. function isSame (input, units) {
  15321. var localInput = isMoment(input) ? input : createLocal(input),
  15322. inputMs;
  15323. if (!(this.isValid() && localInput.isValid())) {
  15324. return false;
  15325. }
  15326. units = normalizeUnits(units) || 'millisecond';
  15327. if (units === 'millisecond') {
  15328. return this.valueOf() === localInput.valueOf();
  15329. } else {
  15330. inputMs = localInput.valueOf();
  15331. return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
  15332. }
  15333. }
  15334. function isSameOrAfter (input, units) {
  15335. return this.isSame(input, units) || this.isAfter(input, units);
  15336. }
  15337. function isSameOrBefore (input, units) {
  15338. return this.isSame(input, units) || this.isBefore(input, units);
  15339. }
  15340. function diff (input, units, asFloat) {
  15341. var that,
  15342. zoneDelta,
  15343. output;
  15344. if (!this.isValid()) {
  15345. return NaN;
  15346. }
  15347. that = cloneWithOffset(input, this);
  15348. if (!that.isValid()) {
  15349. return NaN;
  15350. }
  15351. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  15352. units = normalizeUnits(units);
  15353. switch (units) {
  15354. case 'year': output = monthDiff(this, that) / 12; break;
  15355. case 'month': output = monthDiff(this, that); break;
  15356. case 'quarter': output = monthDiff(this, that) / 3; break;
  15357. case 'second': output = (this - that) / 1e3; break; // 1000
  15358. case 'minute': output = (this - that) / 6e4; break; // 1000 * 60
  15359. case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60
  15360. case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst
  15361. case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst
  15362. default: output = this - that;
  15363. }
  15364. return asFloat ? output : absFloor(output);
  15365. }
  15366. function monthDiff (a, b) {
  15367. // difference in months
  15368. var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
  15369. // b is in (anchor - 1 month, anchor + 1 month)
  15370. anchor = a.clone().add(wholeMonthDiff, 'months'),
  15371. anchor2, adjust;
  15372. if (b - anchor < 0) {
  15373. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  15374. // linear across the month
  15375. adjust = (b - anchor) / (anchor - anchor2);
  15376. } else {
  15377. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  15378. // linear across the month
  15379. adjust = (b - anchor) / (anchor2 - anchor);
  15380. }
  15381. //check for negative zero, return zero if negative zero
  15382. return -(wholeMonthDiff + adjust) || 0;
  15383. }
  15384. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  15385. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  15386. function toString () {
  15387. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  15388. }
  15389. function toISOString(keepOffset) {
  15390. if (!this.isValid()) {
  15391. return null;
  15392. }
  15393. var utc = keepOffset !== true;
  15394. var m = utc ? this.clone().utc() : this;
  15395. if (m.year() < 0 || m.year() > 9999) {
  15396. return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
  15397. }
  15398. if (isFunction(Date.prototype.toISOString)) {
  15399. // native implementation is ~50x faster, use it when we can
  15400. if (utc) {
  15401. return this.toDate().toISOString();
  15402. } else {
  15403. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
  15404. }
  15405. }
  15406. return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
  15407. }
  15408. /**
  15409. * Return a human readable representation of a moment that can
  15410. * also be evaluated to get a new moment which is the same
  15411. *
  15412. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  15413. */
  15414. function inspect () {
  15415. if (!this.isValid()) {
  15416. return 'moment.invalid(/* ' + this._i + ' */)';
  15417. }
  15418. var func = 'moment';
  15419. var zone = '';
  15420. if (!this.isLocal()) {
  15421. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  15422. zone = 'Z';
  15423. }
  15424. var prefix = '[' + func + '("]';
  15425. var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
  15426. var datetime = '-MM-DD[T]HH:mm:ss.SSS';
  15427. var suffix = zone + '[")]';
  15428. return this.format(prefix + year + datetime + suffix);
  15429. }
  15430. function format (inputString) {
  15431. if (!inputString) {
  15432. inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
  15433. }
  15434. var output = formatMoment(this, inputString);
  15435. return this.localeData().postformat(output);
  15436. }
  15437. function from (time, withoutSuffix) {
  15438. if (this.isValid() &&
  15439. ((isMoment(time) && time.isValid()) ||
  15440. createLocal(time).isValid())) {
  15441. return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
  15442. } else {
  15443. return this.localeData().invalidDate();
  15444. }
  15445. }
  15446. function fromNow (withoutSuffix) {
  15447. return this.from(createLocal(), withoutSuffix);
  15448. }
  15449. function to (time, withoutSuffix) {
  15450. if (this.isValid() &&
  15451. ((isMoment(time) && time.isValid()) ||
  15452. createLocal(time).isValid())) {
  15453. return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
  15454. } else {
  15455. return this.localeData().invalidDate();
  15456. }
  15457. }
  15458. function toNow (withoutSuffix) {
  15459. return this.to(createLocal(), withoutSuffix);
  15460. }
  15461. // If passed a locale key, it will set the locale for this
  15462. // instance. Otherwise, it will return the locale configuration
  15463. // variables for this instance.
  15464. function locale (key) {
  15465. var newLocaleData;
  15466. if (key === undefined) {
  15467. return this._locale._abbr;
  15468. } else {
  15469. newLocaleData = getLocale(key);
  15470. if (newLocaleData != null) {
  15471. this._locale = newLocaleData;
  15472. }
  15473. return this;
  15474. }
  15475. }
  15476. var lang = deprecate(
  15477. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  15478. function (key) {
  15479. if (key === undefined) {
  15480. return this.localeData();
  15481. } else {
  15482. return this.locale(key);
  15483. }
  15484. }
  15485. );
  15486. function localeData () {
  15487. return this._locale;
  15488. }
  15489. var MS_PER_SECOND = 1000;
  15490. var MS_PER_MINUTE = 60 * MS_PER_SECOND;
  15491. var MS_PER_HOUR = 60 * MS_PER_MINUTE;
  15492. var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  15493. // actual modulo - handles negative numbers (for dates before 1970):
  15494. function mod$1(dividend, divisor) {
  15495. return (dividend % divisor + divisor) % divisor;
  15496. }
  15497. function localStartOfDate(y, m, d) {
  15498. // the date constructor remaps years 0-99 to 1900-1999
  15499. if (y < 100 && y >= 0) {
  15500. // preserve leap years using a full 400 year cycle, then reset
  15501. return new Date(y + 400, m, d) - MS_PER_400_YEARS;
  15502. } else {
  15503. return new Date(y, m, d).valueOf();
  15504. }
  15505. }
  15506. function utcStartOfDate(y, m, d) {
  15507. // Date.UTC remaps years 0-99 to 1900-1999
  15508. if (y < 100 && y >= 0) {
  15509. // preserve leap years using a full 400 year cycle, then reset
  15510. return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
  15511. } else {
  15512. return Date.UTC(y, m, d);
  15513. }
  15514. }
  15515. function startOf (units) {
  15516. var time;
  15517. units = normalizeUnits(units);
  15518. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  15519. return this;
  15520. }
  15521. var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  15522. switch (units) {
  15523. case 'year':
  15524. time = startOfDate(this.year(), 0, 1);
  15525. break;
  15526. case 'quarter':
  15527. time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
  15528. break;
  15529. case 'month':
  15530. time = startOfDate(this.year(), this.month(), 1);
  15531. break;
  15532. case 'week':
  15533. time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
  15534. break;
  15535. case 'isoWeek':
  15536. time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
  15537. break;
  15538. case 'day':
  15539. case 'date':
  15540. time = startOfDate(this.year(), this.month(), this.date());
  15541. break;
  15542. case 'hour':
  15543. time = this._d.valueOf();
  15544. time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR);
  15545. break;
  15546. case 'minute':
  15547. time = this._d.valueOf();
  15548. time -= mod$1(time, MS_PER_MINUTE);
  15549. break;
  15550. case 'second':
  15551. time = this._d.valueOf();
  15552. time -= mod$1(time, MS_PER_SECOND);
  15553. break;
  15554. }
  15555. this._d.setTime(time);
  15556. hooks.updateOffset(this, true);
  15557. return this;
  15558. }
  15559. function endOf (units) {
  15560. var time;
  15561. units = normalizeUnits(units);
  15562. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  15563. return this;
  15564. }
  15565. var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  15566. switch (units) {
  15567. case 'year':
  15568. time = startOfDate(this.year() + 1, 0, 1) - 1;
  15569. break;
  15570. case 'quarter':
  15571. time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
  15572. break;
  15573. case 'month':
  15574. time = startOfDate(this.year(), this.month() + 1, 1) - 1;
  15575. break;
  15576. case 'week':
  15577. time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
  15578. break;
  15579. case 'isoWeek':
  15580. time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
  15581. break;
  15582. case 'day':
  15583. case 'date':
  15584. time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
  15585. break;
  15586. case 'hour':
  15587. time = this._d.valueOf();
  15588. time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1;
  15589. break;
  15590. case 'minute':
  15591. time = this._d.valueOf();
  15592. time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
  15593. break;
  15594. case 'second':
  15595. time = this._d.valueOf();
  15596. time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
  15597. break;
  15598. }
  15599. this._d.setTime(time);
  15600. hooks.updateOffset(this, true);
  15601. return this;
  15602. }
  15603. function valueOf () {
  15604. return this._d.valueOf() - ((this._offset || 0) * 60000);
  15605. }
  15606. function unix () {
  15607. return Math.floor(this.valueOf() / 1000);
  15608. }
  15609. function toDate () {
  15610. return new Date(this.valueOf());
  15611. }
  15612. function toArray () {
  15613. var m = this;
  15614. return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
  15615. }
  15616. function toObject () {
  15617. var m = this;
  15618. return {
  15619. years: m.year(),
  15620. months: m.month(),
  15621. date: m.date(),
  15622. hours: m.hours(),
  15623. minutes: m.minutes(),
  15624. seconds: m.seconds(),
  15625. milliseconds: m.milliseconds()
  15626. };
  15627. }
  15628. function toJSON () {
  15629. // new Date(NaN).toJSON() === null
  15630. return this.isValid() ? this.toISOString() : null;
  15631. }
  15632. function isValid$2 () {
  15633. return isValid(this);
  15634. }
  15635. function parsingFlags () {
  15636. return extend({}, getParsingFlags(this));
  15637. }
  15638. function invalidAt () {
  15639. return getParsingFlags(this).overflow;
  15640. }
  15641. function creationData() {
  15642. return {
  15643. input: this._i,
  15644. format: this._f,
  15645. locale: this._locale,
  15646. isUTC: this._isUTC,
  15647. strict: this._strict
  15648. };
  15649. }
  15650. // FORMATTING
  15651. addFormatToken(0, ['gg', 2], 0, function () {
  15652. return this.weekYear() % 100;
  15653. });
  15654. addFormatToken(0, ['GG', 2], 0, function () {
  15655. return this.isoWeekYear() % 100;
  15656. });
  15657. function addWeekYearFormatToken (token, getter) {
  15658. addFormatToken(0, [token, token.length], 0, getter);
  15659. }
  15660. addWeekYearFormatToken('gggg', 'weekYear');
  15661. addWeekYearFormatToken('ggggg', 'weekYear');
  15662. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  15663. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  15664. // ALIASES
  15665. addUnitAlias('weekYear', 'gg');
  15666. addUnitAlias('isoWeekYear', 'GG');
  15667. // PRIORITY
  15668. addUnitPriority('weekYear', 1);
  15669. addUnitPriority('isoWeekYear', 1);
  15670. // PARSING
  15671. addRegexToken('G', matchSigned);
  15672. addRegexToken('g', matchSigned);
  15673. addRegexToken('GG', match1to2, match2);
  15674. addRegexToken('gg', match1to2, match2);
  15675. addRegexToken('GGGG', match1to4, match4);
  15676. addRegexToken('gggg', match1to4, match4);
  15677. addRegexToken('GGGGG', match1to6, match6);
  15678. addRegexToken('ggggg', match1to6, match6);
  15679. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
  15680. week[token.substr(0, 2)] = toInt(input);
  15681. });
  15682. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  15683. week[token] = hooks.parseTwoDigitYear(input);
  15684. });
  15685. // MOMENTS
  15686. function getSetWeekYear (input) {
  15687. return getSetWeekYearHelper.call(this,
  15688. input,
  15689. this.week(),
  15690. this.weekday(),
  15691. this.localeData()._week.dow,
  15692. this.localeData()._week.doy);
  15693. }
  15694. function getSetISOWeekYear (input) {
  15695. return getSetWeekYearHelper.call(this,
  15696. input, this.isoWeek(), this.isoWeekday(), 1, 4);
  15697. }
  15698. function getISOWeeksInYear () {
  15699. return weeksInYear(this.year(), 1, 4);
  15700. }
  15701. function getWeeksInYear () {
  15702. var weekInfo = this.localeData()._week;
  15703. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  15704. }
  15705. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  15706. var weeksTarget;
  15707. if (input == null) {
  15708. return weekOfYear(this, dow, doy).year;
  15709. } else {
  15710. weeksTarget = weeksInYear(input, dow, doy);
  15711. if (week > weeksTarget) {
  15712. week = weeksTarget;
  15713. }
  15714. return setWeekAll.call(this, input, week, weekday, dow, doy);
  15715. }
  15716. }
  15717. function setWeekAll(weekYear, week, weekday, dow, doy) {
  15718. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  15719. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  15720. this.year(date.getUTCFullYear());
  15721. this.month(date.getUTCMonth());
  15722. this.date(date.getUTCDate());
  15723. return this;
  15724. }
  15725. // FORMATTING
  15726. addFormatToken('Q', 0, 'Qo', 'quarter');
  15727. // ALIASES
  15728. addUnitAlias('quarter', 'Q');
  15729. // PRIORITY
  15730. addUnitPriority('quarter', 7);
  15731. // PARSING
  15732. addRegexToken('Q', match1);
  15733. addParseToken('Q', function (input, array) {
  15734. array[MONTH] = (toInt(input) - 1) * 3;
  15735. });
  15736. // MOMENTS
  15737. function getSetQuarter (input) {
  15738. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  15739. }
  15740. // FORMATTING
  15741. addFormatToken('D', ['DD', 2], 'Do', 'date');
  15742. // ALIASES
  15743. addUnitAlias('date', 'D');
  15744. // PRIORITY
  15745. addUnitPriority('date', 9);
  15746. // PARSING
  15747. addRegexToken('D', match1to2);
  15748. addRegexToken('DD', match1to2, match2);
  15749. addRegexToken('Do', function (isStrict, locale) {
  15750. // TODO: Remove "ordinalParse" fallback in next major release.
  15751. return isStrict ?
  15752. (locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
  15753. locale._dayOfMonthOrdinalParseLenient;
  15754. });
  15755. addParseToken(['D', 'DD'], DATE);
  15756. addParseToken('Do', function (input, array) {
  15757. array[DATE] = toInt(input.match(match1to2)[0]);
  15758. });
  15759. // MOMENTS
  15760. var getSetDayOfMonth = makeGetSet('Date', true);
  15761. // FORMATTING
  15762. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  15763. // ALIASES
  15764. addUnitAlias('dayOfYear', 'DDD');
  15765. // PRIORITY
  15766. addUnitPriority('dayOfYear', 4);
  15767. // PARSING
  15768. addRegexToken('DDD', match1to3);
  15769. addRegexToken('DDDD', match3);
  15770. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  15771. config._dayOfYear = toInt(input);
  15772. });
  15773. // HELPERS
  15774. // MOMENTS
  15775. function getSetDayOfYear (input) {
  15776. var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
  15777. return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
  15778. }
  15779. // FORMATTING
  15780. addFormatToken('m', ['mm', 2], 0, 'minute');
  15781. // ALIASES
  15782. addUnitAlias('minute', 'm');
  15783. // PRIORITY
  15784. addUnitPriority('minute', 14);
  15785. // PARSING
  15786. addRegexToken('m', match1to2);
  15787. addRegexToken('mm', match1to2, match2);
  15788. addParseToken(['m', 'mm'], MINUTE);
  15789. // MOMENTS
  15790. var getSetMinute = makeGetSet('Minutes', false);
  15791. // FORMATTING
  15792. addFormatToken('s', ['ss', 2], 0, 'second');
  15793. // ALIASES
  15794. addUnitAlias('second', 's');
  15795. // PRIORITY
  15796. addUnitPriority('second', 15);
  15797. // PARSING
  15798. addRegexToken('s', match1to2);
  15799. addRegexToken('ss', match1to2, match2);
  15800. addParseToken(['s', 'ss'], SECOND);
  15801. // MOMENTS
  15802. var getSetSecond = makeGetSet('Seconds', false);
  15803. // FORMATTING
  15804. addFormatToken('S', 0, 0, function () {
  15805. return ~~(this.millisecond() / 100);
  15806. });
  15807. addFormatToken(0, ['SS', 2], 0, function () {
  15808. return ~~(this.millisecond() / 10);
  15809. });
  15810. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  15811. addFormatToken(0, ['SSSS', 4], 0, function () {
  15812. return this.millisecond() * 10;
  15813. });
  15814. addFormatToken(0, ['SSSSS', 5], 0, function () {
  15815. return this.millisecond() * 100;
  15816. });
  15817. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  15818. return this.millisecond() * 1000;
  15819. });
  15820. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  15821. return this.millisecond() * 10000;
  15822. });
  15823. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  15824. return this.millisecond() * 100000;
  15825. });
  15826. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  15827. return this.millisecond() * 1000000;
  15828. });
  15829. // ALIASES
  15830. addUnitAlias('millisecond', 'ms');
  15831. // PRIORITY
  15832. addUnitPriority('millisecond', 16);
  15833. // PARSING
  15834. addRegexToken('S', match1to3, match1);
  15835. addRegexToken('SS', match1to3, match2);
  15836. addRegexToken('SSS', match1to3, match3);
  15837. var token;
  15838. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  15839. addRegexToken(token, matchUnsigned);
  15840. }
  15841. function parseMs(input, array) {
  15842. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  15843. }
  15844. for (token = 'S'; token.length <= 9; token += 'S') {
  15845. addParseToken(token, parseMs);
  15846. }
  15847. // MOMENTS
  15848. var getSetMillisecond = makeGetSet('Milliseconds', false);
  15849. // FORMATTING
  15850. addFormatToken('z', 0, 0, 'zoneAbbr');
  15851. addFormatToken('zz', 0, 0, 'zoneName');
  15852. // MOMENTS
  15853. function getZoneAbbr () {
  15854. return this._isUTC ? 'UTC' : '';
  15855. }
  15856. function getZoneName () {
  15857. return this._isUTC ? 'Coordinated Universal Time' : '';
  15858. }
  15859. var proto = Moment.prototype;
  15860. proto.add = add;
  15861. proto.calendar = calendar$1;
  15862. proto.clone = clone;
  15863. proto.diff = diff;
  15864. proto.endOf = endOf;
  15865. proto.format = format;
  15866. proto.from = from;
  15867. proto.fromNow = fromNow;
  15868. proto.to = to;
  15869. proto.toNow = toNow;
  15870. proto.get = stringGet;
  15871. proto.invalidAt = invalidAt;
  15872. proto.isAfter = isAfter;
  15873. proto.isBefore = isBefore;
  15874. proto.isBetween = isBetween;
  15875. proto.isSame = isSame;
  15876. proto.isSameOrAfter = isSameOrAfter;
  15877. proto.isSameOrBefore = isSameOrBefore;
  15878. proto.isValid = isValid$2;
  15879. proto.lang = lang;
  15880. proto.locale = locale;
  15881. proto.localeData = localeData;
  15882. proto.max = prototypeMax;
  15883. proto.min = prototypeMin;
  15884. proto.parsingFlags = parsingFlags;
  15885. proto.set = stringSet;
  15886. proto.startOf = startOf;
  15887. proto.subtract = subtract;
  15888. proto.toArray = toArray;
  15889. proto.toObject = toObject;
  15890. proto.toDate = toDate;
  15891. proto.toISOString = toISOString;
  15892. proto.inspect = inspect;
  15893. proto.toJSON = toJSON;
  15894. proto.toString = toString;
  15895. proto.unix = unix;
  15896. proto.valueOf = valueOf;
  15897. proto.creationData = creationData;
  15898. proto.year = getSetYear;
  15899. proto.isLeapYear = getIsLeapYear;
  15900. proto.weekYear = getSetWeekYear;
  15901. proto.isoWeekYear = getSetISOWeekYear;
  15902. proto.quarter = proto.quarters = getSetQuarter;
  15903. proto.month = getSetMonth;
  15904. proto.daysInMonth = getDaysInMonth;
  15905. proto.week = proto.weeks = getSetWeek;
  15906. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  15907. proto.weeksInYear = getWeeksInYear;
  15908. proto.isoWeeksInYear = getISOWeeksInYear;
  15909. proto.date = getSetDayOfMonth;
  15910. proto.day = proto.days = getSetDayOfWeek;
  15911. proto.weekday = getSetLocaleDayOfWeek;
  15912. proto.isoWeekday = getSetISODayOfWeek;
  15913. proto.dayOfYear = getSetDayOfYear;
  15914. proto.hour = proto.hours = getSetHour;
  15915. proto.minute = proto.minutes = getSetMinute;
  15916. proto.second = proto.seconds = getSetSecond;
  15917. proto.millisecond = proto.milliseconds = getSetMillisecond;
  15918. proto.utcOffset = getSetOffset;
  15919. proto.utc = setOffsetToUTC;
  15920. proto.local = setOffsetToLocal;
  15921. proto.parseZone = setOffsetToParsedOffset;
  15922. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  15923. proto.isDST = isDaylightSavingTime;
  15924. proto.isLocal = isLocal;
  15925. proto.isUtcOffset = isUtcOffset;
  15926. proto.isUtc = isUtc;
  15927. proto.isUTC = isUtc;
  15928. proto.zoneAbbr = getZoneAbbr;
  15929. proto.zoneName = getZoneName;
  15930. proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
  15931. proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
  15932. proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
  15933. proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
  15934. proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
  15935. function createUnix (input) {
  15936. return createLocal(input * 1000);
  15937. }
  15938. function createInZone () {
  15939. return createLocal.apply(null, arguments).parseZone();
  15940. }
  15941. function preParsePostFormat (string) {
  15942. return string;
  15943. }
  15944. var proto$1 = Locale.prototype;
  15945. proto$1.calendar = calendar;
  15946. proto$1.longDateFormat = longDateFormat;
  15947. proto$1.invalidDate = invalidDate;
  15948. proto$1.ordinal = ordinal;
  15949. proto$1.preparse = preParsePostFormat;
  15950. proto$1.postformat = preParsePostFormat;
  15951. proto$1.relativeTime = relativeTime;
  15952. proto$1.pastFuture = pastFuture;
  15953. proto$1.set = set;
  15954. proto$1.months = localeMonths;
  15955. proto$1.monthsShort = localeMonthsShort;
  15956. proto$1.monthsParse = localeMonthsParse;
  15957. proto$1.monthsRegex = monthsRegex;
  15958. proto$1.monthsShortRegex = monthsShortRegex;
  15959. proto$1.week = localeWeek;
  15960. proto$1.firstDayOfYear = localeFirstDayOfYear;
  15961. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  15962. proto$1.weekdays = localeWeekdays;
  15963. proto$1.weekdaysMin = localeWeekdaysMin;
  15964. proto$1.weekdaysShort = localeWeekdaysShort;
  15965. proto$1.weekdaysParse = localeWeekdaysParse;
  15966. proto$1.weekdaysRegex = weekdaysRegex;
  15967. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  15968. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  15969. proto$1.isPM = localeIsPM;
  15970. proto$1.meridiem = localeMeridiem;
  15971. function get$1 (format, index, field, setter) {
  15972. var locale = getLocale();
  15973. var utc = createUTC().set(setter, index);
  15974. return locale[field](utc, format);
  15975. }
  15976. function listMonthsImpl (format, index, field) {
  15977. if (isNumber(format)) {
  15978. index = format;
  15979. format = undefined;
  15980. }
  15981. format = format || '';
  15982. if (index != null) {
  15983. return get$1(format, index, field, 'month');
  15984. }
  15985. var i;
  15986. var out = [];
  15987. for (i = 0; i < 12; i++) {
  15988. out[i] = get$1(format, i, field, 'month');
  15989. }
  15990. return out;
  15991. }
  15992. // ()
  15993. // (5)
  15994. // (fmt, 5)
  15995. // (fmt)
  15996. // (true)
  15997. // (true, 5)
  15998. // (true, fmt, 5)
  15999. // (true, fmt)
  16000. function listWeekdaysImpl (localeSorted, format, index, field) {
  16001. if (typeof localeSorted === 'boolean') {
  16002. if (isNumber(format)) {
  16003. index = format;
  16004. format = undefined;
  16005. }
  16006. format = format || '';
  16007. } else {
  16008. format = localeSorted;
  16009. index = format;
  16010. localeSorted = false;
  16011. if (isNumber(format)) {
  16012. index = format;
  16013. format = undefined;
  16014. }
  16015. format = format || '';
  16016. }
  16017. var locale = getLocale(),
  16018. shift = localeSorted ? locale._week.dow : 0;
  16019. if (index != null) {
  16020. return get$1(format, (index + shift) % 7, field, 'day');
  16021. }
  16022. var i;
  16023. var out = [];
  16024. for (i = 0; i < 7; i++) {
  16025. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  16026. }
  16027. return out;
  16028. }
  16029. function listMonths (format, index) {
  16030. return listMonthsImpl(format, index, 'months');
  16031. }
  16032. function listMonthsShort (format, index) {
  16033. return listMonthsImpl(format, index, 'monthsShort');
  16034. }
  16035. function listWeekdays (localeSorted, format, index) {
  16036. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  16037. }
  16038. function listWeekdaysShort (localeSorted, format, index) {
  16039. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  16040. }
  16041. function listWeekdaysMin (localeSorted, format, index) {
  16042. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  16043. }
  16044. getSetGlobalLocale('en', {
  16045. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  16046. ordinal : function (number) {
  16047. var b = number % 10,
  16048. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  16049. (b === 1) ? 'st' :
  16050. (b === 2) ? 'nd' :
  16051. (b === 3) ? 'rd' : 'th';
  16052. return number + output;
  16053. }
  16054. });
  16055. // Side effect imports
  16056. hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
  16057. hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
  16058. var mathAbs = Math.abs;
  16059. function abs () {
  16060. var data = this._data;
  16061. this._milliseconds = mathAbs(this._milliseconds);
  16062. this._days = mathAbs(this._days);
  16063. this._months = mathAbs(this._months);
  16064. data.milliseconds = mathAbs(data.milliseconds);
  16065. data.seconds = mathAbs(data.seconds);
  16066. data.minutes = mathAbs(data.minutes);
  16067. data.hours = mathAbs(data.hours);
  16068. data.months = mathAbs(data.months);
  16069. data.years = mathAbs(data.years);
  16070. return this;
  16071. }
  16072. function addSubtract$1 (duration, input, value, direction) {
  16073. var other = createDuration(input, value);
  16074. duration._milliseconds += direction * other._milliseconds;
  16075. duration._days += direction * other._days;
  16076. duration._months += direction * other._months;
  16077. return duration._bubble();
  16078. }
  16079. // supports only 2.0-style add(1, 's') or add(duration)
  16080. function add$1 (input, value) {
  16081. return addSubtract$1(this, input, value, 1);
  16082. }
  16083. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  16084. function subtract$1 (input, value) {
  16085. return addSubtract$1(this, input, value, -1);
  16086. }
  16087. function absCeil (number) {
  16088. if (number < 0) {
  16089. return Math.floor(number);
  16090. } else {
  16091. return Math.ceil(number);
  16092. }
  16093. }
  16094. function bubble () {
  16095. var milliseconds = this._milliseconds;
  16096. var days = this._days;
  16097. var months = this._months;
  16098. var data = this._data;
  16099. var seconds, minutes, hours, years, monthsFromDays;
  16100. // if we have a mix of positive and negative values, bubble down first
  16101. // check: https://github.com/moment/moment/issues/2166
  16102. if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
  16103. (milliseconds <= 0 && days <= 0 && months <= 0))) {
  16104. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  16105. days = 0;
  16106. months = 0;
  16107. }
  16108. // The following code bubbles up values, see the tests for
  16109. // examples of what that means.
  16110. data.milliseconds = milliseconds % 1000;
  16111. seconds = absFloor(milliseconds / 1000);
  16112. data.seconds = seconds % 60;
  16113. minutes = absFloor(seconds / 60);
  16114. data.minutes = minutes % 60;
  16115. hours = absFloor(minutes / 60);
  16116. data.hours = hours % 24;
  16117. days += absFloor(hours / 24);
  16118. // convert days to months
  16119. monthsFromDays = absFloor(daysToMonths(days));
  16120. months += monthsFromDays;
  16121. days -= absCeil(monthsToDays(monthsFromDays));
  16122. // 12 months -> 1 year
  16123. years = absFloor(months / 12);
  16124. months %= 12;
  16125. data.days = days;
  16126. data.months = months;
  16127. data.years = years;
  16128. return this;
  16129. }
  16130. function daysToMonths (days) {
  16131. // 400 years have 146097 days (taking into account leap year rules)
  16132. // 400 years have 12 months === 4800
  16133. return days * 4800 / 146097;
  16134. }
  16135. function monthsToDays (months) {
  16136. // the reverse of daysToMonths
  16137. return months * 146097 / 4800;
  16138. }
  16139. function as (units) {
  16140. if (!this.isValid()) {
  16141. return NaN;
  16142. }
  16143. var days;
  16144. var months;
  16145. var milliseconds = this._milliseconds;
  16146. units = normalizeUnits(units);
  16147. if (units === 'month' || units === 'quarter' || units === 'year') {
  16148. days = this._days + milliseconds / 864e5;
  16149. months = this._months + daysToMonths(days);
  16150. switch (units) {
  16151. case 'month': return months;
  16152. case 'quarter': return months / 3;
  16153. case 'year': return months / 12;
  16154. }
  16155. } else {
  16156. // handle milliseconds separately because of floating point math errors (issue #1867)
  16157. days = this._days + Math.round(monthsToDays(this._months));
  16158. switch (units) {
  16159. case 'week' : return days / 7 + milliseconds / 6048e5;
  16160. case 'day' : return days + milliseconds / 864e5;
  16161. case 'hour' : return days * 24 + milliseconds / 36e5;
  16162. case 'minute' : return days * 1440 + milliseconds / 6e4;
  16163. case 'second' : return days * 86400 + milliseconds / 1000;
  16164. // Math.floor prevents floating point math errors here
  16165. case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
  16166. default: throw new Error('Unknown unit ' + units);
  16167. }
  16168. }
  16169. }
  16170. // TODO: Use this.as('ms')?
  16171. function valueOf$1 () {
  16172. if (!this.isValid()) {
  16173. return NaN;
  16174. }
  16175. return (
  16176. this._milliseconds +
  16177. this._days * 864e5 +
  16178. (this._months % 12) * 2592e6 +
  16179. toInt(this._months / 12) * 31536e6
  16180. );
  16181. }
  16182. function makeAs (alias) {
  16183. return function () {
  16184. return this.as(alias);
  16185. };
  16186. }
  16187. var asMilliseconds = makeAs('ms');
  16188. var asSeconds = makeAs('s');
  16189. var asMinutes = makeAs('m');
  16190. var asHours = makeAs('h');
  16191. var asDays = makeAs('d');
  16192. var asWeeks = makeAs('w');
  16193. var asMonths = makeAs('M');
  16194. var asQuarters = makeAs('Q');
  16195. var asYears = makeAs('y');
  16196. function clone$1 () {
  16197. return createDuration(this);
  16198. }
  16199. function get$2 (units) {
  16200. units = normalizeUnits(units);
  16201. return this.isValid() ? this[units + 's']() : NaN;
  16202. }
  16203. function makeGetter(name) {
  16204. return function () {
  16205. return this.isValid() ? this._data[name] : NaN;
  16206. };
  16207. }
  16208. var milliseconds = makeGetter('milliseconds');
  16209. var seconds = makeGetter('seconds');
  16210. var minutes = makeGetter('minutes');
  16211. var hours = makeGetter('hours');
  16212. var days = makeGetter('days');
  16213. var months = makeGetter('months');
  16214. var years = makeGetter('years');
  16215. function weeks () {
  16216. return absFloor(this.days() / 7);
  16217. }
  16218. var round = Math.round;
  16219. var thresholds = {
  16220. ss: 44, // a few seconds to seconds
  16221. s : 45, // seconds to minute
  16222. m : 45, // minutes to hour
  16223. h : 22, // hours to day
  16224. d : 26, // days to month
  16225. M : 11 // months to year
  16226. };
  16227. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  16228. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  16229. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  16230. }
  16231. function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
  16232. var duration = createDuration(posNegDuration).abs();
  16233. var seconds = round(duration.as('s'));
  16234. var minutes = round(duration.as('m'));
  16235. var hours = round(duration.as('h'));
  16236. var days = round(duration.as('d'));
  16237. var months = round(duration.as('M'));
  16238. var years = round(duration.as('y'));
  16239. var a = seconds <= thresholds.ss && ['s', seconds] ||
  16240. seconds < thresholds.s && ['ss', seconds] ||
  16241. minutes <= 1 && ['m'] ||
  16242. minutes < thresholds.m && ['mm', minutes] ||
  16243. hours <= 1 && ['h'] ||
  16244. hours < thresholds.h && ['hh', hours] ||
  16245. days <= 1 && ['d'] ||
  16246. days < thresholds.d && ['dd', days] ||
  16247. months <= 1 && ['M'] ||
  16248. months < thresholds.M && ['MM', months] ||
  16249. years <= 1 && ['y'] || ['yy', years];
  16250. a[2] = withoutSuffix;
  16251. a[3] = +posNegDuration > 0;
  16252. a[4] = locale;
  16253. return substituteTimeAgo.apply(null, a);
  16254. }
  16255. // This function allows you to set the rounding function for relative time strings
  16256. function getSetRelativeTimeRounding (roundingFunction) {
  16257. if (roundingFunction === undefined) {
  16258. return round;
  16259. }
  16260. if (typeof(roundingFunction) === 'function') {
  16261. round = roundingFunction;
  16262. return true;
  16263. }
  16264. return false;
  16265. }
  16266. // This function allows you to set a threshold for relative time strings
  16267. function getSetRelativeTimeThreshold (threshold, limit) {
  16268. if (thresholds[threshold] === undefined) {
  16269. return false;
  16270. }
  16271. if (limit === undefined) {
  16272. return thresholds[threshold];
  16273. }
  16274. thresholds[threshold] = limit;
  16275. if (threshold === 's') {
  16276. thresholds.ss = limit - 1;
  16277. }
  16278. return true;
  16279. }
  16280. function humanize (withSuffix) {
  16281. if (!this.isValid()) {
  16282. return this.localeData().invalidDate();
  16283. }
  16284. var locale = this.localeData();
  16285. var output = relativeTime$1(this, !withSuffix, locale);
  16286. if (withSuffix) {
  16287. output = locale.pastFuture(+this, output);
  16288. }
  16289. return locale.postformat(output);
  16290. }
  16291. var abs$1 = Math.abs;
  16292. function sign(x) {
  16293. return ((x > 0) - (x < 0)) || +x;
  16294. }
  16295. function toISOString$1() {
  16296. // for ISO strings we do not use the normal bubbling rules:
  16297. // * milliseconds bubble up until they become hours
  16298. // * days do not bubble at all
  16299. // * months bubble up until they become years
  16300. // This is because there is no context-free conversion between hours and days
  16301. // (think of clock changes)
  16302. // and also not between days and months (28-31 days per month)
  16303. if (!this.isValid()) {
  16304. return this.localeData().invalidDate();
  16305. }
  16306. var seconds = abs$1(this._milliseconds) / 1000;
  16307. var days = abs$1(this._days);
  16308. var months = abs$1(this._months);
  16309. var minutes, hours, years;
  16310. // 3600 seconds -> 60 minutes -> 1 hour
  16311. minutes = absFloor(seconds / 60);
  16312. hours = absFloor(minutes / 60);
  16313. seconds %= 60;
  16314. minutes %= 60;
  16315. // 12 months -> 1 year
  16316. years = absFloor(months / 12);
  16317. months %= 12;
  16318. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  16319. var Y = years;
  16320. var M = months;
  16321. var D = days;
  16322. var h = hours;
  16323. var m = minutes;
  16324. var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  16325. var total = this.asSeconds();
  16326. if (!total) {
  16327. // this is the same as C#'s (Noda) and python (isodate)...
  16328. // but not other JS (goog.date)
  16329. return 'P0D';
  16330. }
  16331. var totalSign = total < 0 ? '-' : '';
  16332. var ymSign = sign(this._months) !== sign(total) ? '-' : '';
  16333. var daysSign = sign(this._days) !== sign(total) ? '-' : '';
  16334. var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  16335. return totalSign + 'P' +
  16336. (Y ? ymSign + Y + 'Y' : '') +
  16337. (M ? ymSign + M + 'M' : '') +
  16338. (D ? daysSign + D + 'D' : '') +
  16339. ((h || m || s) ? 'T' : '') +
  16340. (h ? hmsSign + h + 'H' : '') +
  16341. (m ? hmsSign + m + 'M' : '') +
  16342. (s ? hmsSign + s + 'S' : '');
  16343. }
  16344. var proto$2 = Duration.prototype;
  16345. proto$2.isValid = isValid$1;
  16346. proto$2.abs = abs;
  16347. proto$2.add = add$1;
  16348. proto$2.subtract = subtract$1;
  16349. proto$2.as = as;
  16350. proto$2.asMilliseconds = asMilliseconds;
  16351. proto$2.asSeconds = asSeconds;
  16352. proto$2.asMinutes = asMinutes;
  16353. proto$2.asHours = asHours;
  16354. proto$2.asDays = asDays;
  16355. proto$2.asWeeks = asWeeks;
  16356. proto$2.asMonths = asMonths;
  16357. proto$2.asQuarters = asQuarters;
  16358. proto$2.asYears = asYears;
  16359. proto$2.valueOf = valueOf$1;
  16360. proto$2._bubble = bubble;
  16361. proto$2.clone = clone$1;
  16362. proto$2.get = get$2;
  16363. proto$2.milliseconds = milliseconds;
  16364. proto$2.seconds = seconds;
  16365. proto$2.minutes = minutes;
  16366. proto$2.hours = hours;
  16367. proto$2.days = days;
  16368. proto$2.weeks = weeks;
  16369. proto$2.months = months;
  16370. proto$2.years = years;
  16371. proto$2.humanize = humanize;
  16372. proto$2.toISOString = toISOString$1;
  16373. proto$2.toString = toISOString$1;
  16374. proto$2.toJSON = toISOString$1;
  16375. proto$2.locale = locale;
  16376. proto$2.localeData = localeData;
  16377. proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
  16378. proto$2.lang = lang;
  16379. // Side effect imports
  16380. // FORMATTING
  16381. addFormatToken('X', 0, 0, 'unix');
  16382. addFormatToken('x', 0, 0, 'valueOf');
  16383. // PARSING
  16384. addRegexToken('x', matchSigned);
  16385. addRegexToken('X', matchTimestamp);
  16386. addParseToken('X', function (input, array, config) {
  16387. config._d = new Date(parseFloat(input, 10) * 1000);
  16388. });
  16389. addParseToken('x', function (input, array, config) {
  16390. config._d = new Date(toInt(input));
  16391. });
  16392. // Side effect imports
  16393. hooks.version = '2.24.0';
  16394. setHookCallback(createLocal);
  16395. hooks.fn = proto;
  16396. hooks.min = min;
  16397. hooks.max = max;
  16398. hooks.now = now;
  16399. hooks.utc = createUTC;
  16400. hooks.unix = createUnix;
  16401. hooks.months = listMonths;
  16402. hooks.isDate = isDate;
  16403. hooks.locale = getSetGlobalLocale;
  16404. hooks.invalid = createInvalid;
  16405. hooks.duration = createDuration;
  16406. hooks.isMoment = isMoment;
  16407. hooks.weekdays = listWeekdays;
  16408. hooks.parseZone = createInZone;
  16409. hooks.localeData = getLocale;
  16410. hooks.isDuration = isDuration;
  16411. hooks.monthsShort = listMonthsShort;
  16412. hooks.weekdaysMin = listWeekdaysMin;
  16413. hooks.defineLocale = defineLocale;
  16414. hooks.updateLocale = updateLocale;
  16415. hooks.locales = listLocales;
  16416. hooks.weekdaysShort = listWeekdaysShort;
  16417. hooks.normalizeUnits = normalizeUnits;
  16418. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  16419. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  16420. hooks.calendarFormat = getCalendarFormat;
  16421. hooks.prototype = proto;
  16422. // currently HTML5 input type only supports 24-hour formats
  16423. hooks.HTML5_FMT = {
  16424. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  16425. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  16426. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  16427. DATE: 'YYYY-MM-DD', // <input type="date" />
  16428. TIME: 'HH:mm', // <input type="time" />
  16429. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  16430. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  16431. WEEK: 'GGGG-[W]WW', // <input type="week" />
  16432. MONTH: 'YYYY-MM' // <input type="month" />
  16433. };
  16434. return hooks;
  16435. })));
  16436. });
  16437. var FORMATS = {
  16438. datetime: 'MMM D, YYYY, h:mm:ss a',
  16439. millisecond: 'h:mm:ss.SSS a',
  16440. second: 'h:mm:ss a',
  16441. minute: 'h:mm a',
  16442. hour: 'hA',
  16443. day: 'MMM D',
  16444. week: 'll',
  16445. month: 'MMM YYYY',
  16446. quarter: '[Q]Q - YYYY',
  16447. year: 'YYYY'
  16448. };
  16449. core_adapters._date.override(typeof moment === 'function' ? {
  16450. _id: 'moment', // DEBUG ONLY
  16451. formats: function() {
  16452. return FORMATS;
  16453. },
  16454. parse: function(value, format) {
  16455. if (typeof value === 'string' && typeof format === 'string') {
  16456. value = moment(value, format);
  16457. } else if (!(value instanceof moment)) {
  16458. value = moment(value);
  16459. }
  16460. return value.isValid() ? value.valueOf() : null;
  16461. },
  16462. format: function(time, format) {
  16463. return moment(time).format(format);
  16464. },
  16465. add: function(time, amount, unit) {
  16466. return moment(time).add(amount, unit).valueOf();
  16467. },
  16468. diff: function(max, min, unit) {
  16469. return moment(max).diff(moment(min), unit);
  16470. },
  16471. startOf: function(time, unit, weekday) {
  16472. time = moment(time);
  16473. if (unit === 'isoWeek') {
  16474. return time.isoWeekday(weekday).valueOf();
  16475. }
  16476. return time.startOf(unit).valueOf();
  16477. },
  16478. endOf: function(time, unit) {
  16479. return moment(time).endOf(unit).valueOf();
  16480. },
  16481. // DEPRECATIONS
  16482. /**
  16483. * Provided for backward compatibility with scale.getValueForPixel().
  16484. * @deprecated since version 2.8.0
  16485. * @todo remove at version 3
  16486. * @private
  16487. */
  16488. _create: function(time) {
  16489. return moment(time);
  16490. },
  16491. } : {});
  16492. core_defaults._set('global', {
  16493. plugins: {
  16494. filler: {
  16495. propagate: true
  16496. }
  16497. }
  16498. });
  16499. var mappers = {
  16500. dataset: function(source) {
  16501. var index = source.fill;
  16502. var chart = source.chart;
  16503. var meta = chart.getDatasetMeta(index);
  16504. var visible = meta && chart.isDatasetVisible(index);
  16505. var points = (visible && meta.dataset._children) || [];
  16506. var length = points.length || 0;
  16507. return !length ? null : function(point, i) {
  16508. return (i < length && points[i]._view) || null;
  16509. };
  16510. },
  16511. boundary: function(source) {
  16512. var boundary = source.boundary;
  16513. var x = boundary ? boundary.x : null;
  16514. var y = boundary ? boundary.y : null;
  16515. if (helpers$1.isArray(boundary)) {
  16516. return function(point, i) {
  16517. return boundary[i];
  16518. };
  16519. }
  16520. return function(point) {
  16521. return {
  16522. x: x === null ? point.x : x,
  16523. y: y === null ? point.y : y,
  16524. };
  16525. };
  16526. }
  16527. };
  16528. // @todo if (fill[0] === '#')
  16529. function decodeFill(el, index, count) {
  16530. var model = el._model || {};
  16531. var fill = model.fill;
  16532. var target;
  16533. if (fill === undefined) {
  16534. fill = !!model.backgroundColor;
  16535. }
  16536. if (fill === false || fill === null) {
  16537. return false;
  16538. }
  16539. if (fill === true) {
  16540. return 'origin';
  16541. }
  16542. target = parseFloat(fill, 10);
  16543. if (isFinite(target) && Math.floor(target) === target) {
  16544. if (fill[0] === '-' || fill[0] === '+') {
  16545. target = index + target;
  16546. }
  16547. if (target === index || target < 0 || target >= count) {
  16548. return false;
  16549. }
  16550. return target;
  16551. }
  16552. switch (fill) {
  16553. // compatibility
  16554. case 'bottom':
  16555. return 'start';
  16556. case 'top':
  16557. return 'end';
  16558. case 'zero':
  16559. return 'origin';
  16560. // supported boundaries
  16561. case 'origin':
  16562. case 'start':
  16563. case 'end':
  16564. return fill;
  16565. // invalid fill values
  16566. default:
  16567. return false;
  16568. }
  16569. }
  16570. function computeLinearBoundary(source) {
  16571. var model = source.el._model || {};
  16572. var scale = source.el._scale || {};
  16573. var fill = source.fill;
  16574. var target = null;
  16575. var horizontal;
  16576. if (isFinite(fill)) {
  16577. return null;
  16578. }
  16579. // Backward compatibility: until v3, we still need to support boundary values set on
  16580. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  16581. // controllers might still use it (e.g. the Smith chart).
  16582. if (fill === 'start') {
  16583. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  16584. } else if (fill === 'end') {
  16585. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  16586. } else if (model.scaleZero !== undefined) {
  16587. target = model.scaleZero;
  16588. } else if (scale.getBasePixel) {
  16589. target = scale.getBasePixel();
  16590. }
  16591. if (target !== undefined && target !== null) {
  16592. if (target.x !== undefined && target.y !== undefined) {
  16593. return target;
  16594. }
  16595. if (helpers$1.isFinite(target)) {
  16596. horizontal = scale.isHorizontal();
  16597. return {
  16598. x: horizontal ? target : null,
  16599. y: horizontal ? null : target
  16600. };
  16601. }
  16602. }
  16603. return null;
  16604. }
  16605. function computeCircularBoundary(source) {
  16606. var scale = source.el._scale;
  16607. var options = scale.options;
  16608. var length = scale.chart.data.labels.length;
  16609. var fill = source.fill;
  16610. var target = [];
  16611. var start, end, center, i, point;
  16612. if (!length) {
  16613. return null;
  16614. }
  16615. start = options.ticks.reverse ? scale.max : scale.min;
  16616. end = options.ticks.reverse ? scale.min : scale.max;
  16617. center = scale.getPointPositionForValue(0, start);
  16618. for (i = 0; i < length; ++i) {
  16619. point = fill === 'start' || fill === 'end'
  16620. ? scale.getPointPositionForValue(i, fill === 'start' ? start : end)
  16621. : scale.getBasePosition(i);
  16622. if (options.gridLines.circular) {
  16623. point.cx = center.x;
  16624. point.cy = center.y;
  16625. point.angle = scale.getIndexAngle(i) - Math.PI / 2;
  16626. }
  16627. target.push(point);
  16628. }
  16629. return target;
  16630. }
  16631. function computeBoundary(source) {
  16632. var scale = source.el._scale || {};
  16633. if (scale.getPointPositionForValue) {
  16634. return computeCircularBoundary(source);
  16635. }
  16636. return computeLinearBoundary(source);
  16637. }
  16638. function resolveTarget(sources, index, propagate) {
  16639. var source = sources[index];
  16640. var fill = source.fill;
  16641. var visited = [index];
  16642. var target;
  16643. if (!propagate) {
  16644. return fill;
  16645. }
  16646. while (fill !== false && visited.indexOf(fill) === -1) {
  16647. if (!isFinite(fill)) {
  16648. return fill;
  16649. }
  16650. target = sources[fill];
  16651. if (!target) {
  16652. return false;
  16653. }
  16654. if (target.visible) {
  16655. return fill;
  16656. }
  16657. visited.push(fill);
  16658. fill = target.fill;
  16659. }
  16660. return false;
  16661. }
  16662. function createMapper(source) {
  16663. var fill = source.fill;
  16664. var type = 'dataset';
  16665. if (fill === false) {
  16666. return null;
  16667. }
  16668. if (!isFinite(fill)) {
  16669. type = 'boundary';
  16670. }
  16671. return mappers[type](source);
  16672. }
  16673. function isDrawable(point) {
  16674. return point && !point.skip;
  16675. }
  16676. function drawArea(ctx, curve0, curve1, len0, len1) {
  16677. var i, cx, cy, r;
  16678. if (!len0 || !len1) {
  16679. return;
  16680. }
  16681. // building first area curve (normal)
  16682. ctx.moveTo(curve0[0].x, curve0[0].y);
  16683. for (i = 1; i < len0; ++i) {
  16684. helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  16685. }
  16686. if (curve1[0].angle !== undefined) {
  16687. cx = curve1[0].cx;
  16688. cy = curve1[0].cy;
  16689. r = Math.sqrt(Math.pow(curve1[0].x - cx, 2) + Math.pow(curve1[0].y - cy, 2));
  16690. for (i = len1 - 1; i > 0; --i) {
  16691. ctx.arc(cx, cy, r, curve1[i].angle, curve1[i - 1].angle, true);
  16692. }
  16693. return;
  16694. }
  16695. // joining the two area curves
  16696. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  16697. // building opposite area curve (reverse)
  16698. for (i = len1 - 1; i > 0; --i) {
  16699. helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  16700. }
  16701. }
  16702. function doFill(ctx, points, mapper, view, color, loop) {
  16703. var count = points.length;
  16704. var span = view.spanGaps;
  16705. var curve0 = [];
  16706. var curve1 = [];
  16707. var len0 = 0;
  16708. var len1 = 0;
  16709. var i, ilen, index, p0, p1, d0, d1, loopOffset;
  16710. ctx.beginPath();
  16711. for (i = 0, ilen = count; i < ilen; ++i) {
  16712. index = i % count;
  16713. p0 = points[index]._view;
  16714. p1 = mapper(p0, index, view);
  16715. d0 = isDrawable(p0);
  16716. d1 = isDrawable(p1);
  16717. if (loop && loopOffset === undefined && d0) {
  16718. loopOffset = i + 1;
  16719. ilen = count + loopOffset;
  16720. }
  16721. if (d0 && d1) {
  16722. len0 = curve0.push(p0);
  16723. len1 = curve1.push(p1);
  16724. } else if (len0 && len1) {
  16725. if (!span) {
  16726. drawArea(ctx, curve0, curve1, len0, len1);
  16727. len0 = len1 = 0;
  16728. curve0 = [];
  16729. curve1 = [];
  16730. } else {
  16731. if (d0) {
  16732. curve0.push(p0);
  16733. }
  16734. if (d1) {
  16735. curve1.push(p1);
  16736. }
  16737. }
  16738. }
  16739. }
  16740. drawArea(ctx, curve0, curve1, len0, len1);
  16741. ctx.closePath();
  16742. ctx.fillStyle = color;
  16743. ctx.fill();
  16744. }
  16745. var plugin_filler = {
  16746. id: 'filler',
  16747. afterDatasetsUpdate: function(chart, options) {
  16748. var count = (chart.data.datasets || []).length;
  16749. var propagate = options.propagate;
  16750. var sources = [];
  16751. var meta, i, el, source;
  16752. for (i = 0; i < count; ++i) {
  16753. meta = chart.getDatasetMeta(i);
  16754. el = meta.dataset;
  16755. source = null;
  16756. if (el && el._model && el instanceof elements.Line) {
  16757. source = {
  16758. visible: chart.isDatasetVisible(i),
  16759. fill: decodeFill(el, i, count),
  16760. chart: chart,
  16761. el: el
  16762. };
  16763. }
  16764. meta.$filler = source;
  16765. sources.push(source);
  16766. }
  16767. for (i = 0; i < count; ++i) {
  16768. source = sources[i];
  16769. if (!source) {
  16770. continue;
  16771. }
  16772. source.fill = resolveTarget(sources, i, propagate);
  16773. source.boundary = computeBoundary(source);
  16774. source.mapper = createMapper(source);
  16775. }
  16776. },
  16777. beforeDatasetsDraw: function(chart) {
  16778. var metasets = chart._getSortedVisibleDatasetMetas();
  16779. var ctx = chart.ctx;
  16780. var meta, i, el, view, points, mapper, color;
  16781. for (i = metasets.length - 1; i >= 0; --i) {
  16782. meta = metasets[i].$filler;
  16783. if (!meta || !meta.visible) {
  16784. continue;
  16785. }
  16786. el = meta.el;
  16787. view = el._view;
  16788. points = el._children || [];
  16789. mapper = meta.mapper;
  16790. color = view.backgroundColor || core_defaults.global.defaultColor;
  16791. if (mapper && color && points.length) {
  16792. helpers$1.canvas.clipArea(ctx, chart.chartArea);
  16793. doFill(ctx, points, mapper, view, color, el._loop);
  16794. helpers$1.canvas.unclipArea(ctx);
  16795. }
  16796. }
  16797. }
  16798. };
  16799. var getRtlHelper$1 = helpers$1.rtl.getRtlAdapter;
  16800. var noop$1 = helpers$1.noop;
  16801. var valueOrDefault$e = helpers$1.valueOrDefault;
  16802. core_defaults._set('global', {
  16803. legend: {
  16804. display: true,
  16805. position: 'top',
  16806. align: 'center',
  16807. fullWidth: true,
  16808. reverse: false,
  16809. weight: 1000,
  16810. // a callback that will handle
  16811. onClick: function(e, legendItem) {
  16812. var index = legendItem.datasetIndex;
  16813. var ci = this.chart;
  16814. var meta = ci.getDatasetMeta(index);
  16815. // See controller.isDatasetVisible comment
  16816. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  16817. // We hid a dataset ... rerender the chart
  16818. ci.update();
  16819. },
  16820. onHover: null,
  16821. onLeave: null,
  16822. labels: {
  16823. boxWidth: 40,
  16824. padding: 10,
  16825. // Generates labels shown in the legend
  16826. // Valid properties to return:
  16827. // text : text to display
  16828. // fillStyle : fill of coloured box
  16829. // strokeStyle: stroke of coloured box
  16830. // hidden : if this legend item refers to a hidden item
  16831. // lineCap : cap style for line
  16832. // lineDash
  16833. // lineDashOffset :
  16834. // lineJoin :
  16835. // lineWidth :
  16836. generateLabels: function(chart) {
  16837. var datasets = chart.data.datasets;
  16838. var options = chart.options.legend || {};
  16839. var usePointStyle = options.labels && options.labels.usePointStyle;
  16840. return chart._getSortedDatasetMetas().map(function(meta) {
  16841. var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  16842. return {
  16843. text: datasets[meta.index].label,
  16844. fillStyle: style.backgroundColor,
  16845. hidden: !chart.isDatasetVisible(meta.index),
  16846. lineCap: style.borderCapStyle,
  16847. lineDash: style.borderDash,
  16848. lineDashOffset: style.borderDashOffset,
  16849. lineJoin: style.borderJoinStyle,
  16850. lineWidth: style.borderWidth,
  16851. strokeStyle: style.borderColor,
  16852. pointStyle: style.pointStyle,
  16853. rotation: style.rotation,
  16854. // Below is extra data used for toggling the datasets
  16855. datasetIndex: meta.index
  16856. };
  16857. }, this);
  16858. }
  16859. }
  16860. },
  16861. legendCallback: function(chart) {
  16862. var list = document.createElement('ul');
  16863. var datasets = chart.data.datasets;
  16864. var i, ilen, listItem, listItemSpan;
  16865. list.setAttribute('class', chart.id + '-legend');
  16866. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  16867. listItem = list.appendChild(document.createElement('li'));
  16868. listItemSpan = listItem.appendChild(document.createElement('span'));
  16869. listItemSpan.style.backgroundColor = datasets[i].backgroundColor;
  16870. if (datasets[i].label) {
  16871. listItem.appendChild(document.createTextNode(datasets[i].label));
  16872. }
  16873. }
  16874. return list.outerHTML;
  16875. }
  16876. });
  16877. /**
  16878. * Helper function to get the box width based on the usePointStyle option
  16879. * @param {object} labelopts - the label options on the legend
  16880. * @param {number} fontSize - the label font size
  16881. * @return {number} width of the color box area
  16882. */
  16883. function getBoxWidth(labelOpts, fontSize) {
  16884. return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
  16885. fontSize :
  16886. labelOpts.boxWidth;
  16887. }
  16888. /**
  16889. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  16890. */
  16891. var Legend = core_element.extend({
  16892. initialize: function(config) {
  16893. var me = this;
  16894. helpers$1.extend(me, config);
  16895. // Contains hit boxes for each dataset (in dataset order)
  16896. me.legendHitBoxes = [];
  16897. /**
  16898. * @private
  16899. */
  16900. me._hoveredItem = null;
  16901. // Are we in doughnut mode which has a different data type
  16902. me.doughnutMode = false;
  16903. },
  16904. // These methods are ordered by lifecycle. Utilities then follow.
  16905. // Any function defined here is inherited by all legend types.
  16906. // Any function can be extended by the legend type
  16907. beforeUpdate: noop$1,
  16908. update: function(maxWidth, maxHeight, margins) {
  16909. var me = this;
  16910. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  16911. me.beforeUpdate();
  16912. // Absorb the master measurements
  16913. me.maxWidth = maxWidth;
  16914. me.maxHeight = maxHeight;
  16915. me.margins = margins;
  16916. // Dimensions
  16917. me.beforeSetDimensions();
  16918. me.setDimensions();
  16919. me.afterSetDimensions();
  16920. // Labels
  16921. me.beforeBuildLabels();
  16922. me.buildLabels();
  16923. me.afterBuildLabels();
  16924. // Fit
  16925. me.beforeFit();
  16926. me.fit();
  16927. me.afterFit();
  16928. //
  16929. me.afterUpdate();
  16930. return me.minSize;
  16931. },
  16932. afterUpdate: noop$1,
  16933. //
  16934. beforeSetDimensions: noop$1,
  16935. setDimensions: function() {
  16936. var me = this;
  16937. // Set the unconstrained dimension before label rotation
  16938. if (me.isHorizontal()) {
  16939. // Reset position before calculating rotation
  16940. me.width = me.maxWidth;
  16941. me.left = 0;
  16942. me.right = me.width;
  16943. } else {
  16944. me.height = me.maxHeight;
  16945. // Reset position before calculating rotation
  16946. me.top = 0;
  16947. me.bottom = me.height;
  16948. }
  16949. // Reset padding
  16950. me.paddingLeft = 0;
  16951. me.paddingTop = 0;
  16952. me.paddingRight = 0;
  16953. me.paddingBottom = 0;
  16954. // Reset minSize
  16955. me.minSize = {
  16956. width: 0,
  16957. height: 0
  16958. };
  16959. },
  16960. afterSetDimensions: noop$1,
  16961. //
  16962. beforeBuildLabels: noop$1,
  16963. buildLabels: function() {
  16964. var me = this;
  16965. var labelOpts = me.options.labels || {};
  16966. var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
  16967. if (labelOpts.filter) {
  16968. legendItems = legendItems.filter(function(item) {
  16969. return labelOpts.filter(item, me.chart.data);
  16970. });
  16971. }
  16972. if (me.options.reverse) {
  16973. legendItems.reverse();
  16974. }
  16975. me.legendItems = legendItems;
  16976. },
  16977. afterBuildLabels: noop$1,
  16978. //
  16979. beforeFit: noop$1,
  16980. fit: function() {
  16981. var me = this;
  16982. var opts = me.options;
  16983. var labelOpts = opts.labels;
  16984. var display = opts.display;
  16985. var ctx = me.ctx;
  16986. var labelFont = helpers$1.options._parseFont(labelOpts);
  16987. var fontSize = labelFont.size;
  16988. // Reset hit boxes
  16989. var hitboxes = me.legendHitBoxes = [];
  16990. var minSize = me.minSize;
  16991. var isHorizontal = me.isHorizontal();
  16992. if (isHorizontal) {
  16993. minSize.width = me.maxWidth; // fill all the width
  16994. minSize.height = display ? 10 : 0;
  16995. } else {
  16996. minSize.width = display ? 10 : 0;
  16997. minSize.height = me.maxHeight; // fill all the height
  16998. }
  16999. // Increase sizes here
  17000. if (!display) {
  17001. me.width = minSize.width = me.height = minSize.height = 0;
  17002. return;
  17003. }
  17004. ctx.font = labelFont.string;
  17005. if (isHorizontal) {
  17006. // Labels
  17007. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  17008. var lineWidths = me.lineWidths = [0];
  17009. var totalHeight = 0;
  17010. ctx.textAlign = 'left';
  17011. ctx.textBaseline = 'middle';
  17012. helpers$1.each(me.legendItems, function(legendItem, i) {
  17013. var boxWidth = getBoxWidth(labelOpts, fontSize);
  17014. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  17015. if (i === 0 || lineWidths[lineWidths.length - 1] + width + 2 * labelOpts.padding > minSize.width) {
  17016. totalHeight += fontSize + labelOpts.padding;
  17017. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  17018. }
  17019. // Store the hitbox width and height here. Final position will be updated in `draw`
  17020. hitboxes[i] = {
  17021. left: 0,
  17022. top: 0,
  17023. width: width,
  17024. height: fontSize
  17025. };
  17026. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  17027. });
  17028. minSize.height += totalHeight;
  17029. } else {
  17030. var vPadding = labelOpts.padding;
  17031. var columnWidths = me.columnWidths = [];
  17032. var columnHeights = me.columnHeights = [];
  17033. var totalWidth = labelOpts.padding;
  17034. var currentColWidth = 0;
  17035. var currentColHeight = 0;
  17036. helpers$1.each(me.legendItems, function(legendItem, i) {
  17037. var boxWidth = getBoxWidth(labelOpts, fontSize);
  17038. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  17039. // If too tall, go to new column
  17040. if (i > 0 && currentColHeight + fontSize + 2 * vPadding > minSize.height) {
  17041. totalWidth += currentColWidth + labelOpts.padding;
  17042. columnWidths.push(currentColWidth); // previous column width
  17043. columnHeights.push(currentColHeight);
  17044. currentColWidth = 0;
  17045. currentColHeight = 0;
  17046. }
  17047. // Get max width
  17048. currentColWidth = Math.max(currentColWidth, itemWidth);
  17049. currentColHeight += fontSize + vPadding;
  17050. // Store the hitbox width and height here. Final position will be updated in `draw`
  17051. hitboxes[i] = {
  17052. left: 0,
  17053. top: 0,
  17054. width: itemWidth,
  17055. height: fontSize
  17056. };
  17057. });
  17058. totalWidth += currentColWidth;
  17059. columnWidths.push(currentColWidth);
  17060. columnHeights.push(currentColHeight);
  17061. minSize.width += totalWidth;
  17062. }
  17063. me.width = minSize.width;
  17064. me.height = minSize.height;
  17065. },
  17066. afterFit: noop$1,
  17067. // Shared Methods
  17068. isHorizontal: function() {
  17069. return this.options.position === 'top' || this.options.position === 'bottom';
  17070. },
  17071. // Actually draw the legend on the canvas
  17072. draw: function() {
  17073. var me = this;
  17074. var opts = me.options;
  17075. var labelOpts = opts.labels;
  17076. var globalDefaults = core_defaults.global;
  17077. var defaultColor = globalDefaults.defaultColor;
  17078. var lineDefault = globalDefaults.elements.line;
  17079. var legendHeight = me.height;
  17080. var columnHeights = me.columnHeights;
  17081. var legendWidth = me.width;
  17082. var lineWidths = me.lineWidths;
  17083. if (!opts.display) {
  17084. return;
  17085. }
  17086. var rtlHelper = getRtlHelper$1(opts.rtl, me.left, me.minSize.width);
  17087. var ctx = me.ctx;
  17088. var fontColor = valueOrDefault$e(labelOpts.fontColor, globalDefaults.defaultFontColor);
  17089. var labelFont = helpers$1.options._parseFont(labelOpts);
  17090. var fontSize = labelFont.size;
  17091. var cursor;
  17092. // Canvas setup
  17093. ctx.textAlign = rtlHelper.textAlign('left');
  17094. ctx.textBaseline = 'middle';
  17095. ctx.lineWidth = 0.5;
  17096. ctx.strokeStyle = fontColor; // for strikethrough effect
  17097. ctx.fillStyle = fontColor; // render in correct colour
  17098. ctx.font = labelFont.string;
  17099. var boxWidth = getBoxWidth(labelOpts, fontSize);
  17100. var hitboxes = me.legendHitBoxes;
  17101. // current position
  17102. var drawLegendBox = function(x, y, legendItem) {
  17103. if (isNaN(boxWidth) || boxWidth <= 0) {
  17104. return;
  17105. }
  17106. // Set the ctx for the box
  17107. ctx.save();
  17108. var lineWidth = valueOrDefault$e(legendItem.lineWidth, lineDefault.borderWidth);
  17109. ctx.fillStyle = valueOrDefault$e(legendItem.fillStyle, defaultColor);
  17110. ctx.lineCap = valueOrDefault$e(legendItem.lineCap, lineDefault.borderCapStyle);
  17111. ctx.lineDashOffset = valueOrDefault$e(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  17112. ctx.lineJoin = valueOrDefault$e(legendItem.lineJoin, lineDefault.borderJoinStyle);
  17113. ctx.lineWidth = lineWidth;
  17114. ctx.strokeStyle = valueOrDefault$e(legendItem.strokeStyle, defaultColor);
  17115. if (ctx.setLineDash) {
  17116. // IE 9 and 10 do not support line dash
  17117. ctx.setLineDash(valueOrDefault$e(legendItem.lineDash, lineDefault.borderDash));
  17118. }
  17119. if (labelOpts && labelOpts.usePointStyle) {
  17120. // Recalculate x and y for drawPoint() because its expecting
  17121. // x and y to be center of figure (instead of top left)
  17122. var radius = boxWidth * Math.SQRT2 / 2;
  17123. var centerX = rtlHelper.xPlus(x, boxWidth / 2);
  17124. var centerY = y + fontSize / 2;
  17125. // Draw pointStyle as legend symbol
  17126. helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY, legendItem.rotation);
  17127. } else {
  17128. // Draw box as legend symbol
  17129. ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  17130. if (lineWidth !== 0) {
  17131. ctx.strokeRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  17132. }
  17133. }
  17134. ctx.restore();
  17135. };
  17136. var fillText = function(x, y, legendItem, textWidth) {
  17137. var halfFontSize = fontSize / 2;
  17138. var xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize);
  17139. var yMiddle = y + halfFontSize;
  17140. ctx.fillText(legendItem.text, xLeft, yMiddle);
  17141. if (legendItem.hidden) {
  17142. // Strikethrough the text if hidden
  17143. ctx.beginPath();
  17144. ctx.lineWidth = 2;
  17145. ctx.moveTo(xLeft, yMiddle);
  17146. ctx.lineTo(rtlHelper.xPlus(xLeft, textWidth), yMiddle);
  17147. ctx.stroke();
  17148. }
  17149. };
  17150. var alignmentOffset = function(dimension, blockSize) {
  17151. switch (opts.align) {
  17152. case 'start':
  17153. return labelOpts.padding;
  17154. case 'end':
  17155. return dimension - blockSize;
  17156. default: // center
  17157. return (dimension - blockSize + labelOpts.padding) / 2;
  17158. }
  17159. };
  17160. // Horizontal
  17161. var isHorizontal = me.isHorizontal();
  17162. if (isHorizontal) {
  17163. cursor = {
  17164. x: me.left + alignmentOffset(legendWidth, lineWidths[0]),
  17165. y: me.top + labelOpts.padding,
  17166. line: 0
  17167. };
  17168. } else {
  17169. cursor = {
  17170. x: me.left + labelOpts.padding,
  17171. y: me.top + alignmentOffset(legendHeight, columnHeights[0]),
  17172. line: 0
  17173. };
  17174. }
  17175. helpers$1.rtl.overrideTextDirection(me.ctx, opts.textDirection);
  17176. var itemHeight = fontSize + labelOpts.padding;
  17177. helpers$1.each(me.legendItems, function(legendItem, i) {
  17178. var textWidth = ctx.measureText(legendItem.text).width;
  17179. var width = boxWidth + (fontSize / 2) + textWidth;
  17180. var x = cursor.x;
  17181. var y = cursor.y;
  17182. rtlHelper.setWidth(me.minSize.width);
  17183. // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
  17184. // instead of me.right and me.bottom because me.width and me.height
  17185. // may have been changed since me.minSize was calculated
  17186. if (isHorizontal) {
  17187. if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
  17188. y = cursor.y += itemHeight;
  17189. cursor.line++;
  17190. x = cursor.x = me.left + alignmentOffset(legendWidth, lineWidths[cursor.line]);
  17191. }
  17192. } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
  17193. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  17194. cursor.line++;
  17195. y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]);
  17196. }
  17197. var realX = rtlHelper.x(x);
  17198. drawLegendBox(realX, y, legendItem);
  17199. hitboxes[i].left = rtlHelper.leftForLtr(realX, hitboxes[i].width);
  17200. hitboxes[i].top = y;
  17201. // Fill the actual label
  17202. fillText(realX, y, legendItem, textWidth);
  17203. if (isHorizontal) {
  17204. cursor.x += width + labelOpts.padding;
  17205. } else {
  17206. cursor.y += itemHeight;
  17207. }
  17208. });
  17209. helpers$1.rtl.restoreTextDirection(me.ctx, opts.textDirection);
  17210. },
  17211. /**
  17212. * @private
  17213. */
  17214. _getLegendItemAt: function(x, y) {
  17215. var me = this;
  17216. var i, hitBox, lh;
  17217. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  17218. // See if we are touching one of the dataset boxes
  17219. lh = me.legendHitBoxes;
  17220. for (i = 0; i < lh.length; ++i) {
  17221. hitBox = lh[i];
  17222. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  17223. // Touching an element
  17224. return me.legendItems[i];
  17225. }
  17226. }
  17227. }
  17228. return null;
  17229. },
  17230. /**
  17231. * Handle an event
  17232. * @private
  17233. * @param {IEvent} event - The event to handle
  17234. */
  17235. handleEvent: function(e) {
  17236. var me = this;
  17237. var opts = me.options;
  17238. var type = e.type === 'mouseup' ? 'click' : e.type;
  17239. var hoveredItem;
  17240. if (type === 'mousemove') {
  17241. if (!opts.onHover && !opts.onLeave) {
  17242. return;
  17243. }
  17244. } else if (type === 'click') {
  17245. if (!opts.onClick) {
  17246. return;
  17247. }
  17248. } else {
  17249. return;
  17250. }
  17251. // Chart event already has relative position in it
  17252. hoveredItem = me._getLegendItemAt(e.x, e.y);
  17253. if (type === 'click') {
  17254. if (hoveredItem && opts.onClick) {
  17255. // use e.native for backwards compatibility
  17256. opts.onClick.call(me, e.native, hoveredItem);
  17257. }
  17258. } else {
  17259. if (opts.onLeave && hoveredItem !== me._hoveredItem) {
  17260. if (me._hoveredItem) {
  17261. opts.onLeave.call(me, e.native, me._hoveredItem);
  17262. }
  17263. me._hoveredItem = hoveredItem;
  17264. }
  17265. if (opts.onHover && hoveredItem) {
  17266. // use e.native for backwards compatibility
  17267. opts.onHover.call(me, e.native, hoveredItem);
  17268. }
  17269. }
  17270. }
  17271. });
  17272. function createNewLegendAndAttach(chart, legendOpts) {
  17273. var legend = new Legend({
  17274. ctx: chart.ctx,
  17275. options: legendOpts,
  17276. chart: chart
  17277. });
  17278. core_layouts.configure(chart, legend, legendOpts);
  17279. core_layouts.addBox(chart, legend);
  17280. chart.legend = legend;
  17281. }
  17282. var plugin_legend = {
  17283. id: 'legend',
  17284. /**
  17285. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  17286. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  17287. * the plugin, which one will be re-exposed in the chart.js file.
  17288. * https://github.com/chartjs/Chart.js/pull/2640
  17289. * @private
  17290. */
  17291. _element: Legend,
  17292. beforeInit: function(chart) {
  17293. var legendOpts = chart.options.legend;
  17294. if (legendOpts) {
  17295. createNewLegendAndAttach(chart, legendOpts);
  17296. }
  17297. },
  17298. beforeUpdate: function(chart) {
  17299. var legendOpts = chart.options.legend;
  17300. var legend = chart.legend;
  17301. if (legendOpts) {
  17302. helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
  17303. if (legend) {
  17304. core_layouts.configure(chart, legend, legendOpts);
  17305. legend.options = legendOpts;
  17306. } else {
  17307. createNewLegendAndAttach(chart, legendOpts);
  17308. }
  17309. } else if (legend) {
  17310. core_layouts.removeBox(chart, legend);
  17311. delete chart.legend;
  17312. }
  17313. },
  17314. afterEvent: function(chart, e) {
  17315. var legend = chart.legend;
  17316. if (legend) {
  17317. legend.handleEvent(e);
  17318. }
  17319. }
  17320. };
  17321. var noop$2 = helpers$1.noop;
  17322. core_defaults._set('global', {
  17323. title: {
  17324. display: false,
  17325. fontStyle: 'bold',
  17326. fullWidth: true,
  17327. padding: 10,
  17328. position: 'top',
  17329. text: '',
  17330. weight: 2000 // by default greater than legend (1000) to be above
  17331. }
  17332. });
  17333. /**
  17334. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  17335. */
  17336. var Title = core_element.extend({
  17337. initialize: function(config) {
  17338. var me = this;
  17339. helpers$1.extend(me, config);
  17340. // Contains hit boxes for each dataset (in dataset order)
  17341. me.legendHitBoxes = [];
  17342. },
  17343. // These methods are ordered by lifecycle. Utilities then follow.
  17344. beforeUpdate: noop$2,
  17345. update: function(maxWidth, maxHeight, margins) {
  17346. var me = this;
  17347. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  17348. me.beforeUpdate();
  17349. // Absorb the master measurements
  17350. me.maxWidth = maxWidth;
  17351. me.maxHeight = maxHeight;
  17352. me.margins = margins;
  17353. // Dimensions
  17354. me.beforeSetDimensions();
  17355. me.setDimensions();
  17356. me.afterSetDimensions();
  17357. // Labels
  17358. me.beforeBuildLabels();
  17359. me.buildLabels();
  17360. me.afterBuildLabels();
  17361. // Fit
  17362. me.beforeFit();
  17363. me.fit();
  17364. me.afterFit();
  17365. //
  17366. me.afterUpdate();
  17367. return me.minSize;
  17368. },
  17369. afterUpdate: noop$2,
  17370. //
  17371. beforeSetDimensions: noop$2,
  17372. setDimensions: function() {
  17373. var me = this;
  17374. // Set the unconstrained dimension before label rotation
  17375. if (me.isHorizontal()) {
  17376. // Reset position before calculating rotation
  17377. me.width = me.maxWidth;
  17378. me.left = 0;
  17379. me.right = me.width;
  17380. } else {
  17381. me.height = me.maxHeight;
  17382. // Reset position before calculating rotation
  17383. me.top = 0;
  17384. me.bottom = me.height;
  17385. }
  17386. // Reset padding
  17387. me.paddingLeft = 0;
  17388. me.paddingTop = 0;
  17389. me.paddingRight = 0;
  17390. me.paddingBottom = 0;
  17391. // Reset minSize
  17392. me.minSize = {
  17393. width: 0,
  17394. height: 0
  17395. };
  17396. },
  17397. afterSetDimensions: noop$2,
  17398. //
  17399. beforeBuildLabels: noop$2,
  17400. buildLabels: noop$2,
  17401. afterBuildLabels: noop$2,
  17402. //
  17403. beforeFit: noop$2,
  17404. fit: function() {
  17405. var me = this;
  17406. var opts = me.options;
  17407. var minSize = me.minSize = {};
  17408. var isHorizontal = me.isHorizontal();
  17409. var lineCount, textSize;
  17410. if (!opts.display) {
  17411. me.width = minSize.width = me.height = minSize.height = 0;
  17412. return;
  17413. }
  17414. lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
  17415. textSize = lineCount * helpers$1.options._parseFont(opts).lineHeight + opts.padding * 2;
  17416. me.width = minSize.width = isHorizontal ? me.maxWidth : textSize;
  17417. me.height = minSize.height = isHorizontal ? textSize : me.maxHeight;
  17418. },
  17419. afterFit: noop$2,
  17420. // Shared Methods
  17421. isHorizontal: function() {
  17422. var pos = this.options.position;
  17423. return pos === 'top' || pos === 'bottom';
  17424. },
  17425. // Actually draw the title block on the canvas
  17426. draw: function() {
  17427. var me = this;
  17428. var ctx = me.ctx;
  17429. var opts = me.options;
  17430. if (!opts.display) {
  17431. return;
  17432. }
  17433. var fontOpts = helpers$1.options._parseFont(opts);
  17434. var lineHeight = fontOpts.lineHeight;
  17435. var offset = lineHeight / 2 + opts.padding;
  17436. var rotation = 0;
  17437. var top = me.top;
  17438. var left = me.left;
  17439. var bottom = me.bottom;
  17440. var right = me.right;
  17441. var maxWidth, titleX, titleY;
  17442. ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
  17443. ctx.font = fontOpts.string;
  17444. // Horizontal
  17445. if (me.isHorizontal()) {
  17446. titleX = left + ((right - left) / 2); // midpoint of the width
  17447. titleY = top + offset;
  17448. maxWidth = right - left;
  17449. } else {
  17450. titleX = opts.position === 'left' ? left + offset : right - offset;
  17451. titleY = top + ((bottom - top) / 2);
  17452. maxWidth = bottom - top;
  17453. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  17454. }
  17455. ctx.save();
  17456. ctx.translate(titleX, titleY);
  17457. ctx.rotate(rotation);
  17458. ctx.textAlign = 'center';
  17459. ctx.textBaseline = 'middle';
  17460. var text = opts.text;
  17461. if (helpers$1.isArray(text)) {
  17462. var y = 0;
  17463. for (var i = 0; i < text.length; ++i) {
  17464. ctx.fillText(text[i], 0, y, maxWidth);
  17465. y += lineHeight;
  17466. }
  17467. } else {
  17468. ctx.fillText(text, 0, 0, maxWidth);
  17469. }
  17470. ctx.restore();
  17471. }
  17472. });
  17473. function createNewTitleBlockAndAttach(chart, titleOpts) {
  17474. var title = new Title({
  17475. ctx: chart.ctx,
  17476. options: titleOpts,
  17477. chart: chart
  17478. });
  17479. core_layouts.configure(chart, title, titleOpts);
  17480. core_layouts.addBox(chart, title);
  17481. chart.titleBlock = title;
  17482. }
  17483. var plugin_title = {
  17484. id: 'title',
  17485. /**
  17486. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  17487. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  17488. * the plugin, which one will be re-exposed in the chart.js file.
  17489. * https://github.com/chartjs/Chart.js/pull/2640
  17490. * @private
  17491. */
  17492. _element: Title,
  17493. beforeInit: function(chart) {
  17494. var titleOpts = chart.options.title;
  17495. if (titleOpts) {
  17496. createNewTitleBlockAndAttach(chart, titleOpts);
  17497. }
  17498. },
  17499. beforeUpdate: function(chart) {
  17500. var titleOpts = chart.options.title;
  17501. var titleBlock = chart.titleBlock;
  17502. if (titleOpts) {
  17503. helpers$1.mergeIf(titleOpts, core_defaults.global.title);
  17504. if (titleBlock) {
  17505. core_layouts.configure(chart, titleBlock, titleOpts);
  17506. titleBlock.options = titleOpts;
  17507. } else {
  17508. createNewTitleBlockAndAttach(chart, titleOpts);
  17509. }
  17510. } else if (titleBlock) {
  17511. core_layouts.removeBox(chart, titleBlock);
  17512. delete chart.titleBlock;
  17513. }
  17514. }
  17515. };
  17516. var plugins = {};
  17517. var filler = plugin_filler;
  17518. var legend = plugin_legend;
  17519. var title = plugin_title;
  17520. plugins.filler = filler;
  17521. plugins.legend = legend;
  17522. plugins.title = title;
  17523. /**
  17524. * @namespace Chart
  17525. */
  17526. core_controller.helpers = helpers$1;
  17527. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  17528. core_helpers();
  17529. core_controller._adapters = core_adapters;
  17530. core_controller.Animation = core_animation;
  17531. core_controller.animationService = core_animations;
  17532. core_controller.controllers = controllers;
  17533. core_controller.DatasetController = core_datasetController;
  17534. core_controller.defaults = core_defaults;
  17535. core_controller.Element = core_element;
  17536. core_controller.elements = elements;
  17537. core_controller.Interaction = core_interaction;
  17538. core_controller.layouts = core_layouts;
  17539. core_controller.platform = platform;
  17540. core_controller.plugins = core_plugins;
  17541. core_controller.Scale = core_scale;
  17542. core_controller.scaleService = core_scaleService;
  17543. core_controller.Ticks = core_ticks;
  17544. core_controller.Tooltip = core_tooltip;
  17545. // Register built-in scales
  17546. core_controller.helpers.each(scales, function(scale, type) {
  17547. core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
  17548. });
  17549. // Load to register built-in adapters (as side effects)
  17550. // Loading built-in plugins
  17551. for (var k in plugins) {
  17552. if (plugins.hasOwnProperty(k)) {
  17553. core_controller.plugins.register(plugins[k]);
  17554. }
  17555. }
  17556. core_controller.platform.initialize();
  17557. var src = core_controller;
  17558. if (typeof window !== 'undefined') {
  17559. window.Chart = core_controller;
  17560. }
  17561. // DEPRECATIONS
  17562. /**
  17563. * Provided for backward compatibility, not available anymore
  17564. * @namespace Chart.Chart
  17565. * @deprecated since version 2.8.0
  17566. * @todo remove at version 3
  17567. * @private
  17568. */
  17569. core_controller.Chart = core_controller;
  17570. /**
  17571. * Provided for backward compatibility, not available anymore
  17572. * @namespace Chart.Legend
  17573. * @deprecated since version 2.1.5
  17574. * @todo remove at version 3
  17575. * @private
  17576. */
  17577. core_controller.Legend = plugins.legend._element;
  17578. /**
  17579. * Provided for backward compatibility, not available anymore
  17580. * @namespace Chart.Title
  17581. * @deprecated since version 2.1.5
  17582. * @todo remove at version 3
  17583. * @private
  17584. */
  17585. core_controller.Title = plugins.title._element;
  17586. /**
  17587. * Provided for backward compatibility, use Chart.plugins instead
  17588. * @namespace Chart.pluginService
  17589. * @deprecated since version 2.1.5
  17590. * @todo remove at version 3
  17591. * @private
  17592. */
  17593. core_controller.pluginService = core_controller.plugins;
  17594. /**
  17595. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  17596. * effect, instead simply create/register plugins via plain JavaScript objects.
  17597. * @interface Chart.PluginBase
  17598. * @deprecated since version 2.5.0
  17599. * @todo remove at version 3
  17600. * @private
  17601. */
  17602. core_controller.PluginBase = core_controller.Element.extend({});
  17603. /**
  17604. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  17605. * @namespace Chart.canvasHelpers
  17606. * @deprecated since version 2.6.0
  17607. * @todo remove at version 3
  17608. * @private
  17609. */
  17610. core_controller.canvasHelpers = core_controller.helpers.canvas;
  17611. /**
  17612. * Provided for backward compatibility, use Chart.layouts instead.
  17613. * @namespace Chart.layoutService
  17614. * @deprecated since version 2.7.3
  17615. * @todo remove at version 3
  17616. * @private
  17617. */
  17618. core_controller.layoutService = core_controller.layouts;
  17619. /**
  17620. * Provided for backward compatibility, not available anymore.
  17621. * @namespace Chart.LinearScaleBase
  17622. * @deprecated since version 2.8
  17623. * @todo remove at version 3
  17624. * @private
  17625. */
  17626. core_controller.LinearScaleBase = scale_linearbase;
  17627. /**
  17628. * Provided for backward compatibility, instead we should create a new Chart
  17629. * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
  17630. * @deprecated since version 2.8.0
  17631. * @todo remove at version 3
  17632. */
  17633. core_controller.helpers.each(
  17634. [
  17635. 'Bar',
  17636. 'Bubble',
  17637. 'Doughnut',
  17638. 'Line',
  17639. 'PolarArea',
  17640. 'Radar',
  17641. 'Scatter'
  17642. ],
  17643. function(klass) {
  17644. core_controller[klass] = function(ctx, cfg) {
  17645. return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
  17646. type: klass.charAt(0).toLowerCase() + klass.slice(1)
  17647. }));
  17648. };
  17649. }
  17650. );
  17651. return src;
  17652. })));