vendor: 5,250 bytes, lines 1-163
1/*! 2 * Chart.js v4.5.1 3 * https://www.chartjs.org 4 * (c) 2025 Chart.js Contributors 5 * Released under the MIT License 6 * 7 * @kurkle/color v0.3.2 8 * https://github.com/kurkle/color#readme 9 * (c) 2023 Jukka Kurkela 10 * Released under the MIT License 11 * 12 * chartjs-adapter-date-fns v3.0.0 13 * https://www.chartjs.org 14 * (c) 2022 chartjs-adapter-date-fns Contributors 15 * Released under the MIT license 16 * 17 * date-fns v2.30.0 18 * https://date-fns.org 19 * (c) 2021 Sasha Koss and Lesha Koss 20 * Released under the MIT License 21 */ 22 23(function (global, factory) { 24 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 25 typeof define === 'function' && define.amd ? define(factory) : 26 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Chart = factory()); 27})(this, (function () { 'use strict'; 28 29 function _arrayLikeToArray$1(r, a) { 30 (null == a || a > r.length) && (a = r.length); 31 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; 32 return n; 33 } 34 function _arrayWithHoles(r) { 35 if (Array.isArray(r)) return r; 36 } 37 function _arrayWithoutHoles(r) { 38 if (Array.isArray(r)) return _arrayLikeToArray$1(r); 39 } 40 function _assertThisInitialized$1(e) { 41 if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); 42 return e; 43 } 44 function _callSuper(t, o, e) { 45 return o = _getPrototypeOf$1(o), _possibleConstructorReturn$1(t, _isNativeReflectConstruct$1() ? Reflect.construct(o, e || [], _getPrototypeOf$1(t).constructor) : o.apply(t, e)); 46 } 47 function _classCallCheck$1(a, n) { 48 if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); 49 } 50 function _defineProperties$1(e, r) { 51 for (var t = 0; t < r.length; t++) { 52 var o = r[t]; 53 o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); 54 } 55 } 56 function _createClass$1(e, r, t) { 57 return r && _defineProperties$1(e.prototype, r), t && _defineProperties$1(e, t), Object.defineProperty(e, "prototype", { 58 writable: !1 59 }), e; 60 } 61 function _createForOfIteratorHelper$1(r, e) { 62 var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; 63 if (!t) { 64 if (Array.isArray(r) || (t = _unsupportedIterableToArray$1(r)) || e && r && "number" == typeof r.length) { 65 t && (r = t); 66 var n = 0, 67 F = function () {}; 68 return { 69 s: F, 70 n: function () { 71 return n >= r.length ? { 72 done: !0 73 } : { 74 done: !1, 75 value: r[n++] 76 }; 77 }, 78 e: function (r) { 79 throw r; 80 }, 81 f: F 82 }; 83 } 84 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); 85 } 86 var o, 87 a = !0, 88 u = !1; 89 return { 90 s: function () { 91 t = t.call(r); 92 }, 93 n: function () { 94 var r = t.next(); 95 return a = r.done, r; 96 }, 97 e: function (r) { 98 u = !0, o = r; 99 }, 100 f: function () { 101 try { 102 a || null == t.return || t.return(); 103 } finally { 104 if (u) throw o; 105 } 106 } 107 }; 108 } 109 function _defineProperty$1(e, r, t) { 110 return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { 111 value: t, 112 enumerable: !0, 113 configurable: !0, 114 writable: !0 115 }) : e[r] = t, e; 116 } 117 function _get() { 118 return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { 119 var p = _superPropBase(e, t); 120 if (p) { 121 var n = Object.getOwnPropertyDescriptor(p, t); 122 return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; 123 } 124 }, _get.apply(null, arguments); 125 } 126 function _getPrototypeOf$1(t) { 127 return _getPrototypeOf$1 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { 128 return t.__proto__ || Object.getPrototypeOf(t); 129 }, _getPrototypeOf$1(t); 130 } 131 function _inherits$1(t, e) { 132 if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); 133 t.prototype = Object.create(e && e.prototype, { 134 constructor: { 135 value: t, 136 writable: !0, 137 configurable: !0 138 } 139 }), Object.defineProperty(t, "prototype", { 140 writable: !1 141 }), e && _setPrototypeOf$1(t, e); 142 } 143 function _isNativeReflectConstruct$1() { 144 try { 145 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); 146 } catch (t) {} 147 return (_isNativeReflectConstruct$1 = function () { 148 return !!t; 149 })(); 150 } 151 function _iterableToArray(r) { 152 if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); 153 } 154 function _iterableToArrayLimit(r, l) { 155 var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; 156 if (null != t) { 157 var e, 158 n, 159 i, 160 u, 161 a = [], 162 f = !0, 163 o = !1;
164 try { 165 if (i = (t = t.call(r)).next, 0 === l) { 166 if (Object(t) !== t) return; 167 f = !1; 168 } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); 169 } catch (r) { 170 o = !0, n = r; 171 } finally { 172 try { 173 if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; 174 } finally { 175 if (o) throw n; 176 } 177 } 178 return a; 179 } 180 } 181 function _nonIterableRest() { 182 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); 183 } 184 function _nonIterableSpread() { 185 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); 186 } 187 function ownKeys(e, r) { 188 var t = Object.keys(e); 189 if (Object.getOwnPropertySymbols) { 190 var o = Object.getOwnPropertySymbols(e); 191 r && (o = o.filter(function (r) { 192 return Object.getOwnPropertyDescriptor(e, r).enumerable; 193 })), t.push.apply(t, o); 194 } 195 return t; 196 } 197 function _objectSpread2(e) { 198 for (var r = 1; r < arguments.length; r++) { 199 var t = null != arguments[r] ? arguments[r] : {}; 200 r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { 201 _defineProperty$1(e, r, t[r]); 202 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { 203 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); 204 }); 205 } 206 return e; 207 } 208 function _possibleConstructorReturn$1(t, e) { 209 if (e && ("object" == typeof e || "function" == typeof e)) return e; 210 if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); 211 return _assertThisInitialized$1(t); 212 } 213 function _setPrototypeOf$1(t, e) { 214 return _setPrototypeOf$1 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { 215 return t.__proto__ = e, t; 216 }, _setPrototypeOf$1(t, e); 217 } 218 function _slicedToArray(r, e) { 219 return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray$1(r, e) || _nonIterableRest(); 220 } 221 function _superPropBase(t, o) { 222 for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf$1(t));); 223 return t; 224 } 225 function _superPropGet(t, o, e, r) { 226 var p = _get(_getPrototypeOf$1(1 & r ? t.prototype : t), o, e); 227 return 2 & r && "function" == typeof p ? function (t) { 228 return p.apply(e, t); 229 } : p; 230 } 231 function _toConsumableArray(r) { 232 return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray$1(r) || _nonIterableSpread(); 233 } 234 function _toPrimitive(t, r) { 235 if ("object" != typeof t || !t) return t; 236 var e = t[Symbol.toPrimitive]; 237 if (void 0 !== e) { 238 var i = e.call(t, r || "default"); 239 if ("object" != typeof i) return i; 240 throw new TypeError("@@toPrimitive must return a primitive value."); 241 } 242 return ("string" === r ? String : Number)(t); 243 } 244 function _toPropertyKey(t) { 245 var i = _toPrimitive(t, "string"); 246 return "symbol" == typeof i ? i : i + ""; 247 } 248 function _typeof$1(o) { 249 "@babel/helpers - typeof"; 250 251 return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { 252 return typeof o; 253 } : function (o) { 254 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; 255 }, _typeof$1(o); 256 } 257 function _unsupportedIterableToArray$1(r, a) { 258 if (r) { 259 if ("string" == typeof r) return _arrayLikeToArray$1(r, a); 260 var t = {}.toString.call(r).slice(8, -1); 261 return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$1(r, a) : void 0; 262 } 263 } 264 265 /*! 266 * @kurkle/color v0.3.2 267 * https://github.com/kurkle/color#readme 268 * (c) 2023 Jukka Kurkela 269 * Released under the MIT License 270 */ 271 function round(v) { 272 return v + 0.5 | 0; 273 } 274 var lim = function lim(v, l, h) { 275 return Math.max(Math.min(v, h), l); 276 }; 277 function p2b(v) { 278 return lim(round(v * 2.55), 0, 255); 279 } 280 function n2b(v) { 281 return lim(round(v * 255), 0, 255); 282 } 283 function b2n(v) { 284 return lim(round(v / 2.55) / 100, 0, 1); 285 } 286 function n2p(v) { 287 return lim(round(v * 100), 0, 100); 288 } 289 var map$1 = { 290 0: 0, 291 1: 1, 292 2: 2, 293 3: 3, 294 4: 4, 295 5: 5, 296 6: 6, 297 7: 7, 298 8: 8, 299 9: 9, 300 A: 10, 301 B: 11, 302 C: 12, 303 D: 13, 304 E: 14, 305 F: 15, 306 a: 10, 307 b: 11, 308 c: 12, 309 d: 13, 310 e: 14, 311 f: 15 312 }; 313 var hex = _toConsumableArray('0123456789ABCDEF'); 314 var h1 = function h1(b) { 315 return hex[b & 0xF]; 316 }; 317 var h2 = function h2(b) { 318 return hex[(b & 0xF0) >> 4] + hex[b & 0xF]; 319 }; 320 var eq = function eq(b) { 321 return (b & 0xF0) >> 4 === (b & 0xF); 322 }; 323 var isShort = function isShort(v) { 324 return eq(v.r) && eq(v.g) && eq(v.b) && eq(v.a); 325 }; 326 function hexParse(str) { 327 var len = str.length; 328 var ret; 329 if (str[0] === '#') { 330 if (len === 4 || len === 5) { 331 ret = { 332 r: 255 & map$1[str[1]] * 17, 333 g: 255 & map$1[str[2]] * 17, 334 b: 255 & map$1[str[3]] * 17, 335 a: len === 5 ? map$1[str[4]] * 17 : 255 336 }; 337 } else if (len === 7 || len === 9) { 338 ret = { 339 r: map$1[str[1]] << 4 | map$1[str[2]], 340 g: map$1[str[3]] << 4 | map$1[str[4]], 341 b: map$1[str[5]] << 4 | map$1[str[6]], 342 a: len === 9 ? map$1[str[7]] << 4 | map$1[str[8]] : 255 343 }; 344 } 345 } 346 return ret; 347 } 348 var alpha = function alpha(a, f) { 349 return a < 255 ? f(a) : ''; 350 }; 351 function _hexString(v) { 352 var f = isShort(v) ? h1 : h2; 353 return v ? '#' + f(v.r) + f(v.g) + f(v.b) + alpha(v.a, f) : undefined; 354 } 355 var HUE_RE = /^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/; 356 function hsl2rgbn(h, s, l) { 357 var a = s * Math.min(l, 1 - l); 358 var f = function f(n) { 359 var k = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (n + h / 30) % 12;
360 return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1); 361 }; 362 return [f(0), f(8), f(4)]; 363 } 364 function hsv2rgbn(h, s, v) { 365 var f = function f(n) { 366 var k = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (n + h / 60) % 6; 367 return v - v * s * Math.max(Math.min(k, 4 - k, 1), 0); 368 }; 369 return [f(5), f(3), f(1)]; 370 } 371 function hwb2rgbn(h, w, b) { 372 var rgb = hsl2rgbn(h, 1, 0.5); 373 var i; 374 if (w + b > 1) { 375 i = 1 / (w + b); 376 w *= i; 377 b *= i; 378 } 379 for (i = 0; i < 3; i++) { 380 rgb[i] *= 1 - w - b; 381 rgb[i] += w; 382 } 383 return rgb; 384 } 385 function hueValue(r, g, b, d, max) { 386 if (r === max) { 387 return (g - b) / d + (g < b ? 6 : 0); 388 } 389 if (g === max) { 390 return (b - r) / d + 2; 391 } 392 return (r - g) / d + 4; 393 } 394 function rgb2hsl(v) { 395 var range = 255; 396 var r = v.r / range; 397 var g = v.g / range; 398 var b = v.b / range; 399 var max = Math.max(r, g, b); 400 var min = Math.min(r, g, b); 401 var l = (max + min) / 2; 402 var h, s, d; 403 if (max !== min) { 404 d = max - min; 405 s = l > 0.5 ? d / (2 - max - min) : d / (max + min); 406 h = hueValue(r, g, b, d, max); 407 h = h * 60 + 0.5; 408 } 409 return [h | 0, s || 0, l]; 410 } 411 function calln(f, a, b, c) { 412 return (Array.isArray(a) ? f(a[0], a[1], a[2]) : f(a, b, c)).map(n2b); 413 } 414 function hsl2rgb(h, s, l) { 415 return calln(hsl2rgbn, h, s, l); 416 } 417 function hwb2rgb(h, w, b) { 418 return calln(hwb2rgbn, h, w, b); 419 } 420 function hsv2rgb(h, s, v) { 421 return calln(hsv2rgbn, h, s, v); 422 } 423 function hue(h) { 424 return (h % 360 + 360) % 360; 425 } 426 function hueParse(str) { 427 var m = HUE_RE.exec(str); 428 var a = 255; 429 var v; 430 if (!m) { 431 return; 432 } 433 if (m[5] !== v) { 434 a = m[6] ? p2b(+m[5]) : n2b(+m[5]); 435 } 436 var h = hue(+m[2]); 437 var p1 = +m[3] / 100; 438 var p2 = +m[4] / 100; 439 if (m[1] === 'hwb') { 440 v = hwb2rgb(h, p1, p2); 441 } else if (m[1] === 'hsv') { 442 v = hsv2rgb(h, p1, p2); 443 } else { 444 v = hsl2rgb(h, p1, p2); 445 } 446 return { 447 r: v[0], 448 g: v[1], 449 b: v[2], 450 a: a 451 }; 452 } 453 function _rotate(v, deg) { 454 var h = rgb2hsl(v); 455 h[0] = hue(h[0] + deg); 456 h = hsl2rgb(h); 457 v.r = h[0]; 458 v.g = h[1]; 459 v.b = h[2]; 460 } 461 function _hslString(v) { 462 if (!v) { 463 return; 464 } 465 var a = rgb2hsl(v); 466 var h = a[0]; 467 var s = n2p(a[1]); 468 var l = n2p(a[2]); 469 return v.a < 255 ? "hsla(".concat(h, ", ").concat(s, "%, ").concat(l, "%, ").concat(b2n(v.a), ")") : "hsl(".concat(h, ", ").concat(s, "%, ").concat(l, "%)"); 470 } 471 var map$2 = { 472 x: 'dark', 473 Z: 'light', 474 Y: 're', 475 X: 'blu', 476 W: 'gr', 477 V: 'medium', 478 U: 'slate', 479 A: 'ee', 480 T: 'ol', 481 S: 'or', 482 B: 'ra', 483 C: 'lateg', 484 D: 'ights', 485 R: 'in', 486 Q: 'turquois', 487 E: 'hi', 488 P: 'ro', 489 O: 'al', 490 N: 'le', 491 M: 'de', 492 L: 'yello', 493 F: 'en', 494 K: 'ch', 495 G: 'arks', 496 H: 'ea', 497 I: 'ightg', 498 J: 'wh' 499 }; 500 var names$1 = { 501 OiceXe: 'f0f8ff', 502 antiquewEte: 'faebd7', 503 aqua: 'ffff', 504 aquamarRe: '7fffd4', 505 azuY: 'f0ffff', 506 beige: 'f5f5dc', 507 bisque: 'ffe4c4', 508 black: '0', 509 blanKedOmond: 'ffebcd', 510 Xe: 'ff', 511 XeviTet: '8a2be2', 512 bPwn: 'a52a2a', 513 burlywood: 'deb887', 514 caMtXe: '5f9ea0', 515 KartYuse: '7fff00', 516 KocTate: 'd2691e', 517 cSO: 'ff7f50', 518 cSnflowerXe: '6495ed', 519 cSnsilk: 'fff8dc', 520 crimson: 'dc143c', 521 cyan: 'ffff', 522 xXe: '8b', 523 xcyan: '8b8b', 524 xgTMnPd: 'b8860b', 525 xWay: 'a9a9a9', 526 xgYF: '6400', 527 xgYy: 'a9a9a9', 528 xkhaki: 'bdb76b', 529 xmagFta: '8b008b', 530 xTivegYF: '556b2f', 531 xSange: 'ff8c00', 532 xScEd: '9932cc', 533 xYd: '8b0000', 534 xsOmon: 'e9967a', 535 xsHgYF: '8fbc8f', 536 xUXe: '483d8b', 537 xUWay: '2f4f4f', 538 xUgYy: '2f4f4f', 539 xQe: 'ced1', 540 xviTet: '9400d3', 541 dAppRk: 'ff1493', 542 dApskyXe: 'bfff', 543 dimWay: '696969', 544 dimgYy: '696969', 545 dodgerXe: '1e90ff', 546 fiYbrick: 'b22222', 547 flSOwEte: 'fffaf0', 548 foYstWAn: '228b22', 549 fuKsia: 'ff00ff', 550 gaRsbSo: 'dcdcdc', 551 ghostwEte: 'f8f8ff', 552 gTd: 'ffd700', 553 gTMnPd: 'daa520', 554 Way: '808080', 555 gYF: '8000', 556 gYFLw: 'adff2f', 557 gYy: '808080', 558 honeyMw: 'f0fff0', 559 hotpRk: 'ff69b4', 560 RdianYd: 'cd5c5c', 561 Rdigo: '4b0082', 562 ivSy: 'fffff0', 563 khaki: 'f0e68c', 564 lavFMr: 'e6e6fa', 565 lavFMrXsh: 'fff0f5', 566 lawngYF: '7cfc00', 567 NmoncEffon: 'fffacd', 568 ZXe: 'add8e6', 569 ZcSO: 'f08080', 570 Zcyan: 'e0ffff', 571 ZgTMnPdLw: 'fafad2', 572 ZWay: 'd3d3d3', 573 ZgYF: '90ee90', 574 ZgYy: 'd3d3d3', 575 ZpRk: 'ffb6c1', 576 ZsOmon: 'ffa07a', 577 ZsHgYF: '20b2aa', 578 ZskyXe: '87cefa', 579 ZUWay: '778899', 580 ZUgYy: '778899', 581 ZstAlXe: 'b0c4de', 582 ZLw: 'ffffe0', 583 lime: 'ff00', 584 limegYF: '32cd32', 585 lRF: 'faf0e6', 586 magFta: 'ff00ff', 587 maPon: '800000', 588 VaquamarRe: '66cdaa', 589 VXe: 'cd', 590 VScEd: 'ba55d3', 591 VpurpN: '9370db', 592 VsHgYF: '3cb371', 593 VUXe: '7b68ee', 594 VsprRggYF: 'fa9a', 595 VQe: '48d1cc', 596 VviTetYd: 'c71585', 597 midnightXe: '191970', 598 mRtcYam: 'f5fffa', 599 mistyPse: 'ffe4e1', 600 moccasR: 'ffe4b5', 601 navajowEte: 'ffdead', 602 navy: '80', 603 Tdlace: 'fdf5e6', 604 Tive: '808000', 605 TivedBb: '6b8e23', 606 Sange: 'ffa500', 607 SangeYd: 'ff4500', 608 ScEd: 'da70d6', 609 pOegTMnPd: 'eee8aa', 610 pOegYF: '98fb98', 611 pOeQe: 'afeeee', 612 pOeviTetYd: 'db7093', 613 papayawEp: 'ffefd5', 614 pHKpuff: 'ffdab9', 615 peru: 'cd853f', 616 pRk: 'ffc0cb', 617 plum: 'dda0dd', 618 powMrXe: 'b0e0e6', 619 purpN: '800080', 620 YbeccapurpN: '663399', 621 Yd: 'ff0000', 622 Psybrown: 'bc8f8f', 623 PyOXe: '4169e1', 624 saddNbPwn: '8b4513', 625 sOmon: 'fa8072', 626 sandybPwn: 'f4a460', 627 sHgYF: '2e8b57', 628 sHshell: 'fff5ee', 629 siFna: 'a0522d', 630 silver: 'c0c0c0', 631 skyXe: '87ceeb', 632 UXe: '6a5acd', 633 UWay: '708090', 634 UgYy: '708090', 635 snow: 'fffafa', 636 sprRggYF: 'ff7f', 637 stAlXe: '4682b4', 638 tan: 'd2b48c', 639 teO: '8080', 640 tEstN: 'd8bfd8', 641 tomato: 'ff6347', 642 Qe: '40e0d0', 643 viTet: 'ee82ee', 644 JHt: 'f5deb3', 645 wEte: 'ffffff', 646 wEtesmoke: 'f5f5f5', 647 Lw: 'ffff00', 648 LwgYF: '9acd32' 649 }; 650 function unpack() { 651 var unpacked = {}; 652 var keys = Object.keys(names$1); 653 var tkeys = Object.keys(map$2); 654 var i, j, k, ok, nk; 655 for (i = 0; i < keys.length; i++) { 656 ok = nk = keys[i]; 657 for (j = 0; j < tkeys.length; j++) { 658 k = tkeys[j]; 659 nk = nk.replace(k, map$2[k]); 660 } 661 k = parseInt(names$1[ok], 16); 662 unpacked[nk] = [k >> 16 & 0xFF, k >> 8 & 0xFF, k & 0xFF]; 663 } 664 return unpacked; 665 } 666 var names; 667 function nameParse(str) { 668 if (!names) { 669 names = unpack(); 670 names.transparent = [0, 0, 0, 0]; 671 } 672 var a = names[str.toLowerCase()]; 673 return a && { 674 r: a[0], 675 g: a[1], 676 b: a[2],
677 a: a.length === 4 ? a[3] : 255 678 }; 679 } 680 var RGB_RE = /^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/; 681 function rgbParse(str) { 682 var m = RGB_RE.exec(str); 683 var a = 255; 684 var r, g, b; 685 if (!m) { 686 return; 687 } 688 if (m[7] !== r) { 689 var v = +m[7]; 690 a = m[8] ? p2b(v) : lim(v * 255, 0, 255); 691 } 692 r = +m[1]; 693 g = +m[3]; 694 b = +m[5]; 695 r = 255 & (m[2] ? p2b(r) : lim(r, 0, 255)); 696 g = 255 & (m[4] ? p2b(g) : lim(g, 0, 255)); 697 b = 255 & (m[6] ? p2b(b) : lim(b, 0, 255)); 698 return { 699 r: r, 700 g: g, 701 b: b, 702 a: a 703 }; 704 } 705 function _rgbString(v) { 706 return v && (v.a < 255 ? "rgba(".concat(v.r, ", ").concat(v.g, ", ").concat(v.b, ", ").concat(b2n(v.a), ")") : "rgb(".concat(v.r, ", ").concat(v.g, ", ").concat(v.b, ")")); 707 } 708 var to = function to(v) { 709 return v <= 0.0031308 ? v * 12.92 : Math.pow(v, 1.0 / 2.4) * 1.055 - 0.055; 710 }; 711 var from = function from(v) { 712 return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); 713 }; 714 function _interpolate(rgb1, rgb2, t) { 715 var r = from(b2n(rgb1.r)); 716 var g = from(b2n(rgb1.g)); 717 var b = from(b2n(rgb1.b)); 718 return { 719 r: n2b(to(r + t * (from(b2n(rgb2.r)) - r))), 720 g: n2b(to(g + t * (from(b2n(rgb2.g)) - g))), 721 b: n2b(to(b + t * (from(b2n(rgb2.b)) - b))), 722 a: rgb1.a + t * (rgb2.a - rgb1.a) 723 }; 724 } 725 function modHSL(v, i, ratio) { 726 if (v) { 727 var tmp = rgb2hsl(v); 728 tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1)); 729 tmp = hsl2rgb(tmp); 730 v.r = tmp[0]; 731 v.g = tmp[1]; 732 v.b = tmp[2]; 733 } 734 } 735 function clone$1(v, proto) { 736 return v ? Object.assign(proto || {}, v) : v; 737 } 738 function fromObject(input) { 739 var v = { 740 r: 0, 741 g: 0, 742 b: 0, 743 a: 255 744 }; 745 if (Array.isArray(input)) { 746 if (input.length >= 3) { 747 v = { 748 r: input[0], 749 g: input[1], 750 b: input[2], 751 a: 255 752 }; 753 if (input.length > 3) { 754 v.a = n2b(input[3]); 755 } 756 } 757 } else { 758 v = clone$1(input, { 759 r: 0, 760 g: 0, 761 b: 0, 762 a: 1 763 }); 764 v.a = n2b(v.a); 765 } 766 return v; 767 } 768 function functionParse(str) { 769 if (str.charAt(0) === 'r') { 770 return rgbParse(str); 771 } 772 return hueParse(str); 773 } 774 var Color = /*#__PURE__*/function () { 775 function Color(input) { 776 _classCallCheck$1(this, Color); 777 if (input instanceof Color) { 778 return input; 779 } 780 var type = _typeof$1(input); 781 var v; 782 if (type === 'object') { 783 v = fromObject(input); 784 } else if (type === 'string') { 785 v = hexParse(input) || nameParse(input) || functionParse(input); 786 } 787 this._rgb = v; 788 this._valid = !!v; 789 } 790 return _createClass$1(Color, [{ 791 key: "valid", 792 get: function get() { 793 return this._valid; 794 } 795 }, { 796 key: "rgb", 797 get: function get() { 798 var v = clone$1(this._rgb); 799 if (v) { 800 v.a = b2n(v.a); 801 } 802 return v; 803 }, 804 set: function set(obj) { 805 this._rgb = fromObject(obj); 806 } 807 }, { 808 key: "rgbString", 809 value: function rgbString() { 810 return this._valid ? _rgbString(this._rgb) : undefined; 811 } 812 }, { 813 key: "hexString", 814 value: function hexString() { 815 return this._valid ? _hexString(this._rgb) : undefined; 816 } 817 }, { 818 key: "hslString", 819 value: function hslString() { 820 return this._valid ? _hslString(this._rgb) : undefined; 821 } 822 }, { 823 key: "mix", 824 value: function mix(color, weight) { 825 if (color) { 826 var c1 = this.rgb; 827 var c2 = color.rgb; 828 var w2; 829 var p = weight === w2 ? 0.5 : weight; 830 var w = 2 * p - 1; 831 var a = c1.a - c2.a; 832 var w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0; 833 w2 = 1 - w1; 834 c1.r = 0xFF & w1 * c1.r + w2 * c2.r + 0.5; 835 c1.g = 0xFF & w1 * c1.g + w2 * c2.g + 0.5; 836 c1.b = 0xFF & w1 * c1.b + w2 * c2.b + 0.5; 837 c1.a = p * c1.a + (1 - p) * c2.a; 838 this.rgb = c1; 839 } 840 return this; 841 } 842 }, {
843 key: "interpolate", 844 value: function interpolate(color, t) { 845 if (color) { 846 this._rgb = _interpolate(this._rgb, color._rgb, t); 847 } 848 return this; 849 } 850 }, { 851 key: "clone", 852 value: function clone() { 853 return new Color(this.rgb); 854 } 855 }, { 856 key: "alpha", 857 value: function alpha(a) { 858 this._rgb.a = n2b(a); 859 return this; 860 } 861 }, { 862 key: "clearer", 863 value: function clearer(ratio) { 864 var rgb = this._rgb; 865 rgb.a *= 1 - ratio; 866 return this; 867 } 868 }, { 869 key: "greyscale", 870 value: function greyscale() { 871 var rgb = this._rgb; 872 var val = round(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11); 873 rgb.r = rgb.g = rgb.b = val; 874 return this; 875 } 876 }, { 877 key: "opaquer", 878 value: function opaquer(ratio) { 879 var rgb = this._rgb; 880 rgb.a *= 1 + ratio; 881 return this; 882 } 883 }, { 884 key: "negate", 885 value: function negate() { 886 var v = this._rgb; 887 v.r = 255 - v.r; 888 v.g = 255 - v.g; 889 v.b = 255 - v.b; 890 return this; 891 } 892 }, { 893 key: "lighten", 894 value: function lighten(ratio) { 895 modHSL(this._rgb, 2, ratio); 896 return this; 897 } 898 }, { 899 key: "darken", 900 value: function darken(ratio) { 901 modHSL(this._rgb, 2, -ratio); 902 return this; 903 } 904 }, { 905 key: "saturate", 906 value: function saturate(ratio) { 907 modHSL(this._rgb, 1, ratio); 908 return this; 909 } 910 }, { 911 key: "desaturate", 912 value: function desaturate(ratio) { 913 modHSL(this._rgb, 1, -ratio); 914 return this; 915 } 916 }, { 917 key: "rotate", 918 value: function rotate(deg) { 919 _rotate(this._rgb, deg); 920 return this; 921 } 922 }]); 923 }(); 924 925 /** 926 * @namespace Chart.helpers 927 */ /** 928 * An empty function that can be used, for example, for optional callback. 929 */ 930 function noop() { 931 /* noop */} 932 /** 933 * Returns a unique id, sequentially generated from a global variable. 934 */ 935 var uid = function () { 936 var id = 0; 937 return function () { 938 return id++; 939 }; 940 }(); 941 /** 942 * Returns true if `value` is neither null nor undefined, else returns false. 943 * @param value - The value to test. 944 * @since 2.7.0 945 */ 946 function isNullOrUndef(value) { 947 return value === null || value === undefined; 948 } 949 /** 950 * Returns true if `value` is an array (including typed arrays), else returns false. 951 * @param value - The value to test. 952 * @function 953 */ 954 function isArray(value) { 955 if (Array.isArray && Array.isArray(value)) { 956 return true; 957 } 958 var type = Object.prototype.toString.call(value); 959 if (type.slice(0, 7) === '[object' && type.slice(-6) === 'Array]') { 960 return true; 961 } 962 return false; 963 } 964 /** 965 * Returns true if `value` is an object (excluding null), else returns false. 966 * @param value - The value to test. 967 * @since 2.7.0 968 */ 969 function isObject(value) { 970 return value !== null && Object.prototype.toString.call(value) === '[object Object]'; 971 } 972 /** 973 * Returns true if `value` is a finite number, else returns false 974 * @param value - The value to test. 975 */ 976 function isNumberFinite(value) { 977 return (typeof value === 'number' || value instanceof Number) && isFinite(+value); 978 } 979 /** 980 * Returns `value` if finite, else returns `defaultValue`. 981 * @param value - The value to return if defined. 982 * @param defaultValue - The value to return if `value` is not finite. 983 */ 984 function finiteOrDefault(value, defaultValue) { 985 return isNumberFinite(value) ? value : defaultValue; 986 } 987 /** 988 * Returns `value` if defined, else returns `defaultValue`. 989 * @param value - The value to return if defined. 990 * @param defaultValue - The value to return if `value` is undefined. 991 */ 992 function valueOrDefault(value, defaultValue) { 993 return typeof value === 'undefined' ? defaultValue : value; 994 } 995 var toPercentage = function toPercentage(value, dimension) { 996 return typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 : +value / dimension; 997 }; 998 var toDimension = function toDimension(value, dimension) { 999 return typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 * dimension : +value; 1000 }; 1001 /** 1002 * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the 1003 * value returned by `fn`. If `fn` is not a function, this method returns undefined. 1004 * @param fn - The function to call. 1005 * @param args - The arguments with which `fn` should be called. 1006 * @param [thisArg] - The value of `this` provided for the call to `fn`. 1007 */ 1008 function callback(fn, args, thisArg) { 1009 if (fn && typeof fn.call === 'function') { 1010 return fn.apply(thisArg, args); 1011 } 1012 } 1013 function each(loopable, fn, thisArg, reverse) { 1014 var i, len, keys; 1015 if (isArray(loopable)) { 1016 len = loopable.length; 1017 if (reverse) { 1018 for (i = len - 1; i >= 0; i--) { 1019 fn.call(thisArg, loopable[i], i); 1020 } 1021 } else { 1022 for (i = 0; i < len; i++) { 1023 fn.call(thisArg, loopable[i], i); 1024 } 1025 } 1026 } else if (isObject(loopable)) { 1027 keys = Object.keys(loopable); 1028 len = keys.length; 1029 for (i = 0; i < len; i++) { 1030 fn.call(thisArg, loopable[keys[i]], keys[i]); 1031 } 1032 } 1033 } 1034 /** 1035 * Returns true if the `a0` and `a1` arrays have the same content, else returns false. 1036 * @param a0 - The array to compare 1037 * @param a1 - The array to compare 1038 * @private 1039 */ 1040 function _elementsEqual(a0, a1) { 1041 var i, ilen, v0, v1; 1042 if (!a0 || !a1 || a0.length !== a1.length) { 1043 return false;
1044 } 1045 for (i = 0, ilen = a0.length; i < ilen; ++i) { 1046 v0 = a0[i]; 1047 v1 = a1[i]; 1048 if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) { 1049 return false; 1050 } 1051 } 1052 return true; 1053 } 1054 /** 1055 * Returns a deep copy of `source` without keeping references on objects and arrays. 1056 * @param source - The value to clone. 1057 */ 1058 function clone(source) { 1059 if (isArray(source)) { 1060 return source.map(clone); 1061 } 1062 if (isObject(source)) { 1063 var target = Object.create(null); 1064 var keys = Object.keys(source); 1065 var klen = keys.length; 1066 var k = 0; 1067 for (; k < klen; ++k) { 1068 target[keys[k]] = clone(source[keys[k]]); 1069 } 1070 return target; 1071 } 1072 return source; 1073 } 1074 function isValidKey(key) { 1075 return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1; 1076 } 1077 /** 1078 * The default merger when Chart.helpers.merge is called without merger option. 1079 * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback. 1080 * @private 1081 */ 1082 function _merger(key, target, source, options) { 1083 if (!isValidKey(key)) { 1084 return; 1085 } 1086 var tval = target[key]; 1087 var sval = source[key]; 1088 if (isObject(tval) && isObject(sval)) { 1089 // eslint-disable-next-line @typescript-eslint/no-use-before-define 1090 merge(tval, sval, options); 1091 } else { 1092 target[key] = clone(sval); 1093 } 1094 } 1095 function merge(target, source, options) { 1096 var sources = isArray(source) ? source : [source]; 1097 var ilen = sources.length; 1098 if (!isObject(target)) { 1099 return target; 1100 } 1101 options = options || {}; 1102 var merger = options.merger || _merger; 1103 var current; 1104 for (var i = 0; i < ilen; ++i) { 1105 current = sources[i]; 1106 if (!isObject(current)) { 1107 continue; 1108 } 1109 var keys = Object.keys(current); 1110 for (var k = 0, klen = keys.length; k < klen; ++k) { 1111 merger(keys[k], target, current, options); 1112 } 1113 } 1114 return target; 1115 } 1116 function mergeIf(target, source) { 1117 // eslint-disable-next-line @typescript-eslint/no-use-before-define 1118 return merge(target, source, { 1119 merger: _mergerIf 1120 }); 1121 } 1122 /** 1123 * Merges source[key] in target[key] only if target[key] is undefined. 1124 * @private 1125 */ 1126 function _mergerIf(key, target, source) { 1127 if (!isValidKey(key)) { 1128 return; 1129 } 1130 var tval = target[key]; 1131 var sval = source[key]; 1132 if (isObject(tval) && isObject(sval)) { 1133 mergeIf(tval, sval); 1134 } else if (!Object.prototype.hasOwnProperty.call(target, key)) { 1135 target[key] = clone(sval); 1136 } 1137 } 1138 /** 1139 * @private 1140 */ 1141 function _deprecated(scope, value, previous, current) { 1142 if (value !== undefined) { 1143 console.warn(scope + ': "' + previous + '" is deprecated. Please use "' + current + '" instead'); 1144 } 1145 } 1146 // resolveObjectKey resolver cache 1147 var keyResolvers = { 1148 // Chart.helpers.core resolveObjectKey should resolve empty key to root object 1149 '': function _(v) { 1150 return v; 1151 }, 1152 // default resolvers 1153 x: function x(o) { 1154 return o.x; 1155 }, 1156 y: function y(o) { 1157 return o.y; 1158 } 1159 }; 1160 /** 1161 * @private 1162 */ 1163 function _splitKey(key) { 1164 var parts = key.split('.'); 1165 var keys = []; 1166 var tmp = ''; 1167 var _iterator = _createForOfIteratorHelper$1(parts), 1168 _step; 1169 try { 1170 for (_iterator.s(); !(_step = _iterator.n()).done;) { 1171 var part = _step.value; 1172 tmp += part; 1173 if (tmp.endsWith('\\')) { 1174 tmp = tmp.slice(0, -1) + '.'; 1175 } else { 1176 keys.push(tmp); 1177 tmp = ''; 1178 } 1179 } 1180 } catch (err) { 1181 _iterator.e(err); 1182 } finally { 1183 _iterator.f(); 1184 } 1185 return keys; 1186 } 1187 function _getKeyResolver(key) { 1188 var keys = _splitKey(key); 1189 return function (obj) { 1190 var _iterator2 = _createForOfIteratorHelper$1(keys), 1191 _step2; 1192 try { 1193 for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { 1194 var k = _step2.value; 1195 if (k === '') { 1196 break; 1197 } 1198 obj = obj && obj[k]; 1199 } 1200 } catch (err) { 1201 _iterator2.e(err); 1202 } finally { 1203 _iterator2.f(); 1204 } 1205 return obj; 1206 }; 1207 } 1208 function resolveObjectKey(obj, key) { 1209 var resolver = keyResolvers[key] || (keyResolvers[key] = _getKeyResolver(key)); 1210 return resolver(obj); 1211 } 1212 /** 1213 * @private 1214 */ 1215 function _capitalize(str) { 1216 return str.charAt(0).toUpperCase() + str.slice(1); 1217 } 1218 var defined = function defined(value) { 1219 return typeof value !== 'undefined'; 1220 }; 1221 var isFunction = function isFunction(value) { 1222 return typeof value === 'function'; 1223 }; 1224 // Adapted from https://stackoverflow.com/questions/31128855/comparing-ecma6-sets-for-equality#31129384 1225 var setsEqual = function setsEqual(a, b) { 1226 if (a.size !== b.size) { 1227 return false;
1228 } 1229 var _iterator3 = _createForOfIteratorHelper$1(a), 1230 _step3; 1231 try { 1232 for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { 1233 var item = _step3.value; 1234 if (!b.has(item)) { 1235 return false; 1236 } 1237 } 1238 } catch (err) { 1239 _iterator3.e(err); 1240 } finally { 1241 _iterator3.f(); 1242 } 1243 return true; 1244 }; 1245 /** 1246 * @param e - The event 1247 * @private 1248 */ 1249 function _isClickEvent(e) { 1250 return e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu'; 1251 } 1252 1253 /** 1254 * @alias Chart.helpers.math 1255 * @namespace 1256 */ 1257 var PI = Math.PI; 1258 var TAU = 2 * PI; 1259 var PITAU = TAU + PI; 1260 var INFINITY = Number.POSITIVE_INFINITY; 1261 var RAD_PER_DEG = PI / 180; 1262 var HALF_PI = PI / 2; 1263 var QUARTER_PI = PI / 4; 1264 var TWO_THIRDS_PI = PI * 2 / 3; 1265 var log10 = Math.log10; 1266 var sign = Math.sign; 1267 function almostEquals(x, y, epsilon) { 1268 return Math.abs(x - y) < epsilon; 1269 } 1270 /** 1271 * Implementation of the nice number algorithm used in determining where axis labels will go 1272 */ 1273 function niceNum(range) { 1274 var roundedRange = Math.round(range); 1275 range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range; 1276 var niceRange = Math.pow(10, Math.floor(log10(range))); 1277 var fraction = range / niceRange; 1278 var niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10; 1279 return niceFraction * niceRange; 1280 } 1281 /** 1282 * Returns an array of factors sorted from 1 to sqrt(value) 1283 * @private 1284 */ 1285 function _factorize(value) { 1286 var result = []; 1287 var sqrt = Math.sqrt(value); 1288 var i; 1289 for (i = 1; i < sqrt; i++) { 1290 if (value % i === 0) { 1291 result.push(i); 1292 result.push(value / i); 1293 } 1294 } 1295 if (sqrt === (sqrt | 0)) { 1296 result.push(sqrt); 1297 } 1298 result.sort(function (a, b) { 1299 return a - b; 1300 }).pop(); 1301 return result; 1302 } 1303 /** 1304 * Verifies that attempting to coerce n to string or number won't throw a TypeError. 1305 */ 1306 function isNonPrimitive(n) { 1307 return _typeof$1(n) === 'symbol' || _typeof$1(n) === 'object' && n !== null && !(Symbol.toPrimitive in n || 'toString' in n || 'valueOf' in n); 1308 } 1309 function isNumber(n) { 1310 return !isNonPrimitive(n) && !isNaN(parseFloat(n)) && isFinite(n); 1311 } 1312 function almostWhole(x, epsilon) { 1313 var rounded = Math.round(x); 1314 return rounded - epsilon <= x && rounded + epsilon >= x; 1315 } 1316 /** 1317 * @private 1318 */ 1319 function _setMinAndMaxByKey(array, target, property) { 1320 var i, ilen, value; 1321 for (i = 0, ilen = array.length; i < ilen; i++) { 1322 value = array[i][property]; 1323 if (!isNaN(value)) { 1324 target.min = Math.min(target.min, value); 1325 target.max = Math.max(target.max, value); 1326 } 1327 } 1328 } 1329 function toRadians(degrees) { 1330 return degrees * (PI / 180); 1331 } 1332 function toDegrees(radians) { 1333 return radians * (180 / PI); 1334 } 1335 /** 1336 * Returns the number of decimal places 1337 * i.e. the number of digits after the decimal point, of the value of this Number. 1338 * @param x - A number. 1339 * @returns The number of decimal places. 1340 * @private 1341 */ 1342 function _decimalPlaces(x) { 1343 if (!isNumberFinite(x)) { 1344 return; 1345 } 1346 var e = 1; 1347 var p = 0; 1348 while (Math.round(x * e) / e !== x) { 1349 e *= 10; 1350 p++; 1351 } 1352 return p; 1353 } 1354 // Gets the angle from vertical upright to the point about a centre. 1355 function getAngleFromPoint(centrePoint, anglePoint) { 1356 var distanceFromXCenter = anglePoint.x - centrePoint.x; 1357 var distanceFromYCenter = anglePoint.y - centrePoint.y; 1358 var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter); 1359 var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter); 1360 if (angle < -0.5 * PI) { 1361 angle += TAU; // make sure the returned angle is in the range of (-PI/2, 3PI/2] 1362 } 1363 return { 1364 angle: angle, 1365 distance: radialDistanceFromCenter 1366 }; 1367 } 1368 function distanceBetweenPoints(pt1, pt2) { 1369 return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2)); 1370 } 1371 /** 1372 * Shortest distance between angles, in either direction. 1373 * @private 1374 */ 1375 function _angleDiff(a, b) {
1376 return (a - b + PITAU) % TAU - PI; 1377 } 1378 /** 1379 * Normalize angle to be between 0 and 2*PI 1380 * @private 1381 */ 1382 function _normalizeAngle(a) { 1383 return (a % TAU + TAU) % TAU; 1384 } 1385 /** 1386 * @private 1387 */ 1388 function _angleBetween(angle, start, end, sameAngleIsFullCircle) { 1389 var a = _normalizeAngle(angle); 1390 var s = _normalizeAngle(start); 1391 var e = _normalizeAngle(end); 1392 var angleToStart = _normalizeAngle(s - a); 1393 var angleToEnd = _normalizeAngle(e - a); 1394 var startToAngle = _normalizeAngle(a - s); 1395 var endToAngle = _normalizeAngle(a - e); 1396 return a === s || a === e || sameAngleIsFullCircle && s === e || angleToStart > angleToEnd && startToAngle < endToAngle; 1397 } 1398 /** 1399 * Limit `value` between `min` and `max` 1400 * @param value 1401 * @param min 1402 * @param max 1403 * @private 1404 */ 1405 function _limitValue(value, min, max) { 1406 return Math.max(min, Math.min(max, value)); 1407 } 1408 /** 1409 * @param {number} value 1410 * @private 1411 */ 1412 function _int16Range(value) { 1413 return _limitValue(value, -32768, 32767); 1414 } 1415 /** 1416 * @param value 1417 * @param start 1418 * @param end 1419 * @param [epsilon] 1420 * @private 1421 */ 1422 function _isBetween(value, start, end) { 1423 var epsilon = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1e-6; 1424 return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon; 1425 } 1426 function _lookup(table, value, cmp) { 1427 cmp = cmp || function (index) { 1428 return table[index] < value; 1429 }; 1430 var hi = table.length - 1; 1431 var lo = 0; 1432 var mid; 1433 while (hi - lo > 1) { 1434 mid = lo + hi >> 1; 1435 if (cmp(mid)) { 1436 lo = mid; 1437 } else { 1438 hi = mid; 1439 } 1440 } 1441 return { 1442 lo: lo, 1443 hi: hi 1444 }; 1445 } 1446 /** 1447 * Binary search 1448 * @param table - the table search. must be sorted! 1449 * @param key - property name for the value in each entry 1450 * @param value - value to find 1451 * @param last - lookup last index 1452 * @private 1453 */ 1454 var _lookupByKey = function _lookupByKey(table, key, value, last) { 1455 return _lookup(table, value, last ? function (index) { 1456 var ti = table[index][key]; 1457 return ti < value || ti === value && table[index + 1][key] === value; 1458 } : function (index) { 1459 return table[index][key] < value; 1460 }); 1461 }; 1462 /** 1463 * Reverse binary search 1464 * @param table - the table search. must be sorted! 1465 * @param key - property name for the value in each entry 1466 * @param value - value to find 1467 * @private 1468 */ 1469 var _rlookupByKey = function _rlookupByKey(table, key, value) { 1470 return _lookup(table, value, function (index) { 1471 return table[index][key] >= value; 1472 }); 1473 }; 1474 /** 1475 * Return subset of `values` between `min` and `max` inclusive. 1476 * Values are assumed to be in sorted order. 1477 * @param values - sorted array of values 1478 * @param min - min value 1479 * @param max - max value 1480 */ 1481 function _filterBetween(values, min, max) { 1482 var start = 0; 1483 var end = values.length; 1484 while (start < end && values[start] < min) { 1485 start++; 1486 } 1487 while (end > start && values[end - 1] > max) { 1488 end--; 1489 } 1490 return start > 0 || end < values.length ? values.slice(start, end) : values; 1491 } 1492 var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift']; 1493 function listenArrayEvents(array, listener) { 1494 if (array._chartjs) { 1495 array._chartjs.listeners.push(listener); 1496 return; 1497 } 1498 Object.defineProperty(array, '_chartjs', { 1499 configurable: true, 1500 enumerable: false, 1501 value: { 1502 listeners: [listener] 1503 } 1504 }); 1505 arrayEvents.forEach(function (key) { 1506 var method = '_onData' + _capitalize(key); 1507 var base = array[key]; 1508 Object.defineProperty(array, key, { 1509 configurable: true, 1510 enumerable: false, 1511 value: function value() { 1512 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 1513 args[_key] = arguments[_key]; 1514 } 1515 var res = base.apply(this, args); 1516 array._chartjs.listeners.forEach(function (object) { 1517 if (typeof object[method] === 'function') { 1518 object[method].apply(object, args); 1519 } 1520 }); 1521 return res; 1522 } 1523 }); 1524 }); 1525 } 1526 function unlistenArrayEvents(array, listener) { 1527 var stub = array._chartjs; 1528 if (!stub) { 1529 return; 1530 } 1531 var listeners = stub.listeners; 1532 var index = listeners.indexOf(listener); 1533 if (index !== -1) { 1534 listeners.splice(index, 1); 1535 } 1536 if (listeners.length > 0) { 1537 return; 1538 }
1539 arrayEvents.forEach(function (key) { 1540 delete array[key]; 1541 }); 1542 delete array._chartjs; 1543 } 1544 /** 1545 * @param items 1546 */ 1547 function _arrayUnique(items) { 1548 var set = new Set(items); 1549 if (set.size === items.length) { 1550 return items; 1551 } 1552 return Array.from(set); 1553 } 1554 function fontString(pixelSize, fontStyle, fontFamily) { 1555 return fontStyle + ' ' + pixelSize + 'px ' + fontFamily; 1556 } 1557 /** 1558 * Request animation polyfill 1559 */ 1560 var requestAnimFrame = function () { 1561 if (typeof window === 'undefined') { 1562 return function (callback) { 1563 return callback(); 1564 }; 1565 } 1566 return window.requestAnimationFrame; 1567 }(); 1568 /** 1569 * Throttles calling `fn` once per animation frame 1570 * Latest arguments are used on the actual call 1571 */ 1572 function throttled(fn, thisArg) { 1573 var argsToUse = []; 1574 var ticking = false; 1575 return function () { 1576 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { 1577 args[_key2] = arguments[_key2]; 1578 } 1579 // Save the args for use later 1580 argsToUse = args; 1581 if (!ticking) { 1582 ticking = true; 1583 requestAnimFrame.call(window, function () { 1584 ticking = false; 1585 fn.apply(thisArg, argsToUse); 1586 }); 1587 } 1588 }; 1589 } 1590 /** 1591 * Debounces calling `fn` for `delay` ms 1592 */ 1593 function debounce(fn, delay) { 1594 var timeout; 1595 return function () { 1596 for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { 1597 args[_key3] = arguments[_key3]; 1598 } 1599 if (delay) { 1600 clearTimeout(timeout); 1601 timeout = setTimeout(fn, delay, args); 1602 } else { 1603 fn.apply(this, args); 1604 } 1605 return delay; 1606 }; 1607 } 1608 /** 1609 * Converts 'start' to 'left', 'end' to 'right' and others to 'center' 1610 * @private 1611 */ 1612 var _toLeftRightCenter = function _toLeftRightCenter(align) { 1613 return align === 'start' ? 'left' : align === 'end' ? 'right' : 'center'; 1614 }; 1615 /** 1616 * Returns `start`, `end` or `(start + end) / 2` depending on `align`. Defaults to `center` 1617 * @private 1618 */ 1619 var _alignStartEnd = function _alignStartEnd(align, start, end) { 1620 return align === 'start' ? start : align === 'end' ? end : (start + end) / 2; 1621 }; 1622 /** 1623 * Returns `left`, `right` or `(left + right) / 2` depending on `align`. Defaults to `left` 1624 * @private 1625 */ 1626 var _textX = function _textX(align, left, right, rtl) { 1627 var check = rtl ? 'left' : 'right'; 1628 return align === check ? right : align === 'center' ? (left + right) / 2 : left; 1629 }; 1630 /** 1631 * Return start and count of visible points. 1632 * @private 1633 */ 1634 function _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) { 1635 var pointCount = points.length; 1636 var start = 0; 1637 var count = pointCount; 1638 if (meta._sorted) { 1639 var iScale = meta.iScale, 1640 vScale = meta.vScale, 1641 _parsed = meta._parsed; 1642 var spanGaps = meta.dataset ? meta.dataset.options ? meta.dataset.options.spanGaps : null : null; 1643 var axis = iScale.axis; 1644 var _iScale$getUserBounds = iScale.getUserBounds(), 1645 min = _iScale$getUserBounds.min, 1646 max = _iScale$getUserBounds.max, 1647 minDefined = _iScale$getUserBounds.minDefined, 1648 maxDefined = _iScale$getUserBounds.maxDefined; 1649 if (minDefined) { 1650 start = Math.min( 1651 // @ts-expect-error Need to type _parsed 1652 _lookupByKey(_parsed, axis, min).lo, 1653 // @ts-expect-error Need to fix types on _lookupByKey 1654 animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo); 1655 if (spanGaps) { 1656 var distanceToDefinedLo = _parsed.slice(0, start + 1).reverse().findIndex(function (point) { 1657 return !isNullOrUndef(point[vScale.axis]); 1658 }); 1659 start -= Math.max(0, distanceToDefinedLo); 1660 } 1661 start = _limitValue(start, 0, pointCount - 1); 1662 } 1663 if (maxDefined) { 1664 var end = Math.max( 1665 // @ts-expect-error Need to type _parsed 1666 _lookupByKey(_parsed, iScale.axis, max, true).hi + 1, 1667 // @ts-expect-error Need to fix types on _lookupByKey 1668 animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max), true).hi + 1); 1669 if (spanGaps) { 1670 var distanceToDefinedHi = _parsed.slice(end - 1).findIndex(function (point) {
1671 return !isNullOrUndef(point[vScale.axis]); 1672 }); 1673 end += Math.max(0, distanceToDefinedHi); 1674 } 1675 count = _limitValue(end, start, pointCount) - start; 1676 } else { 1677 count = pointCount - start; 1678 } 1679 } 1680 return { 1681 start: start, 1682 count: count 1683 }; 1684 } 1685 /** 1686 * Checks if the scale ranges have changed. 1687 * @param {object} meta - dataset meta. 1688 * @returns {boolean} 1689 * @private 1690 */ 1691 function _scaleRangesChanged(meta) { 1692 var xScale = meta.xScale, 1693 yScale = meta.yScale, 1694 _scaleRanges = meta._scaleRanges; 1695 var newRanges = { 1696 xmin: xScale.min, 1697 xmax: xScale.max, 1698 ymin: yScale.min, 1699 ymax: yScale.max 1700 }; 1701 if (!_scaleRanges) { 1702 meta._scaleRanges = newRanges; 1703 return true; 1704 } 1705 var changed = _scaleRanges.xmin !== xScale.min || _scaleRanges.xmax !== xScale.max || _scaleRanges.ymin !== yScale.min || _scaleRanges.ymax !== yScale.max; 1706 Object.assign(_scaleRanges, newRanges); 1707 return changed; 1708 } 1709 var atEdge = function atEdge(t) { 1710 return t === 0 || t === 1; 1711 }; 1712 var elasticIn = function elasticIn(t, s, p) { 1713 return -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p)); 1714 }; 1715 var elasticOut = function elasticOut(t, s, p) { 1716 return Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1; 1717 }; 1718 /** 1719 * Easing functions adapted from Robert Penner's easing equations. 1720 * @namespace Chart.helpers.easing.effects 1721 * @see http://www.robertpenner.com/easing/ 1722 */ 1723 var effects = { 1724 linear: function linear(t) { 1725 return t; 1726 }, 1727 easeInQuad: function easeInQuad(t) { 1728 return t * t; 1729 }, 1730 easeOutQuad: function easeOutQuad(t) { 1731 return -t * (t - 2); 1732 }, 1733 easeInOutQuad: function easeInOutQuad(t) { 1734 return (t /= 0.5) < 1 ? 0.5 * t * t : -0.5 * (--t * (t - 2) - 1); 1735 }, 1736 easeInCubic: function easeInCubic(t) { 1737 return t * t * t; 1738 }, 1739 easeOutCubic: function easeOutCubic(t) { 1740 return (t -= 1) * t * t + 1; 1741 }, 1742 easeInOutCubic: function easeInOutCubic(t) { 1743 return (t /= 0.5) < 1 ? 0.5 * t * t * t : 0.5 * ((t -= 2) * t * t + 2); 1744 }, 1745 easeInQuart: function easeInQuart(t) { 1746 return t * t * t * t; 1747 }, 1748 easeOutQuart: function easeOutQuart(t) { 1749 return -((t -= 1) * t * t * t - 1); 1750 }, 1751 easeInOutQuart: function easeInOutQuart(t) { 1752 return (t /= 0.5) < 1 ? 0.5 * t * t * t * t : -0.5 * ((t -= 2) * t * t * t - 2); 1753 }, 1754 easeInQuint: function easeInQuint(t) { 1755 return t * t * t * t * t; 1756 }, 1757 easeOutQuint: function easeOutQuint(t) { 1758 return (t -= 1) * t * t * t * t + 1; 1759 }, 1760 easeInOutQuint: function easeInOutQuint(t) { 1761 return (t /= 0.5) < 1 ? 0.5 * t * t * t * t * t : 0.5 * ((t -= 2) * t * t * t * t + 2); 1762 }, 1763 easeInSine: function easeInSine(t) { 1764 return -Math.cos(t * HALF_PI) + 1; 1765 }, 1766 easeOutSine: function easeOutSine(t) { 1767 return Math.sin(t * HALF_PI); 1768 }, 1769 easeInOutSine: function easeInOutSine(t) { 1770 return -0.5 * (Math.cos(PI * t) - 1); 1771 }, 1772 easeInExpo: function easeInExpo(t) { 1773 return t === 0 ? 0 : Math.pow(2, 10 * (t - 1)); 1774 }, 1775 easeOutExpo: function easeOutExpo(t) { 1776 return t === 1 ? 1 : -Math.pow(2, -10 * t) + 1; 1777 }, 1778 easeInOutExpo: function easeInOutExpo(t) { 1779 return atEdge(t) ? t : t < 0.5 ? 0.5 * Math.pow(2, 10 * (t * 2 - 1)) : 0.5 * (-Math.pow(2, -10 * (t * 2 - 1)) + 2); 1780 }, 1781 easeInCirc: function easeInCirc(t) { 1782 return t >= 1 ? t : -(Math.sqrt(1 - t * t) - 1); 1783 }, 1784 easeOutCirc: function easeOutCirc(t) { 1785 return Math.sqrt(1 - (t -= 1) * t); 1786 }, 1787 easeInOutCirc: function easeInOutCirc(t) { 1788 return (t /= 0.5) < 1 ? -0.5 * (Math.sqrt(1 - t * t) - 1) : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1); 1789 }, 1790 easeInElastic: function easeInElastic(t) { 1791 return atEdge(t) ? t : elasticIn(t, 0.075, 0.3); 1792 }, 1793 easeOutElastic: function easeOutElastic(t) { 1794 return atEdge(t) ? t : elasticOut(t, 0.075, 0.3); 1795 }, 1796 easeInOutElastic: function easeInOutElastic(t) { 1797 var s = 0.1125; 1798 var p = 0.45; 1799 return atEdge(t) ? t : t < 0.5 ? 0.5 * elasticIn(t * 2, s, p) : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p); 1800 }, 1801 easeInBack: function easeInBack(t) { 1802 var s = 1.70158; 1803 return t * t * ((s + 1) * t - s); 1804 }, 1805 easeOutBack: function easeOutBack(t) { 1806 var s = 1.70158;
1807 return (t -= 1) * t * ((s + 1) * t + s) + 1; 1808 }, 1809 easeInOutBack: function easeInOutBack(t) { 1810 var s = 1.70158; 1811 if ((t /= 0.5) < 1) { 1812 return 0.5 * (t * t * (((s *= 1.525) + 1) * t - s)); 1813 } 1814 return 0.5 * ((t -= 2) * t * (((s *= 1.525) + 1) * t + s) + 2); 1815 }, 1816 easeInBounce: function easeInBounce(t) { 1817 return 1 - effects.easeOutBounce(1 - t); 1818 }, 1819 easeOutBounce: function easeOutBounce(t) { 1820 var m = 7.5625; 1821 var d = 2.75; 1822 if (t < 1 / d) { 1823 return m * t * t; 1824 } 1825 if (t < 2 / d) { 1826 return m * (t -= 1.5 / d) * t + 0.75; 1827 } 1828 if (t < 2.5 / d) { 1829 return m * (t -= 2.25 / d) * t + 0.9375; 1830 } 1831 return m * (t -= 2.625 / d) * t + 0.984375; 1832 }, 1833 easeInOutBounce: function easeInOutBounce(t) { 1834 return t < 0.5 ? effects.easeInBounce(t * 2) * 0.5 : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5; 1835 } 1836 }; 1837 function isPatternOrGradient(value) { 1838 if (value && _typeof$1(value) === 'object') { 1839 var type = value.toString(); 1840 return type === '[object CanvasPattern]' || type === '[object CanvasGradient]'; 1841 } 1842 return false; 1843 } 1844 function color(value) { 1845 return isPatternOrGradient(value) ? value : new Color(value); 1846 } 1847 function getHoverColor(value) { 1848 return isPatternOrGradient(value) ? value : new Color(value).saturate(0.5).darken(0.1).hexString(); 1849 } 1850 var numbers = ['x', 'y', 'borderWidth', 'radius', 'tension']; 1851 var colors = ['color', 'borderColor', 'backgroundColor']; 1852 function applyAnimationsDefaults(defaults) { 1853 defaults.set('animation', { 1854 delay: undefined, 1855 duration: 1000, 1856 easing: 'easeOutQuart', 1857 fn: undefined, 1858 from: undefined, 1859 loop: undefined, 1860 to: undefined, 1861 type: undefined 1862 }); 1863 defaults.describe('animation', { 1864 _fallback: false, 1865 _indexable: false, 1866 _scriptable: function _scriptable(name) { 1867 return name !== 'onProgress' && name !== 'onComplete' && name !== 'fn'; 1868 } 1869 }); 1870 defaults.set('animations', { 1871 colors: { 1872 type: 'color', 1873 properties: colors 1874 }, 1875 numbers: { 1876 type: 'number', 1877 properties: numbers 1878 } 1879 }); 1880 defaults.describe('animations', { 1881 _fallback: 'animation' 1882 }); 1883 defaults.set('transitions', { 1884 active: { 1885 animation: { 1886 duration: 400 1887 } 1888 }, 1889 resize: { 1890 animation: { 1891 duration: 0 1892 } 1893 }, 1894 show: { 1895 animations: { 1896 colors: { 1897 from: 'transparent' 1898 }, 1899 visible: { 1900 type: 'boolean', 1901 duration: 0 1902 } 1903 } 1904 }, 1905 hide: { 1906 animations: { 1907 colors: { 1908 to: 'transparent' 1909 }, 1910 visible: { 1911 type: 'boolean', 1912 easing: 'linear', 1913 fn: function fn(v) { 1914 return v | 0; 1915 } 1916 } 1917 } 1918 } 1919 }); 1920 } 1921 function applyLayoutsDefaults(defaults) { 1922 defaults.set('layout', { 1923 autoPadding: true, 1924 padding: { 1925 top: 0, 1926 right: 0, 1927 bottom: 0, 1928 left: 0 1929 } 1930 }); 1931 } 1932 var intlCache = new Map(); 1933 function getNumberFormat(locale, options) { 1934 options = options || {}; 1935 var cacheKey = locale + JSON.stringify(options); 1936 var formatter = intlCache.get(cacheKey); 1937 if (!formatter) { 1938 formatter = new Intl.NumberFormat(locale, options); 1939 intlCache.set(cacheKey, formatter); 1940 } 1941 return formatter; 1942 } 1943 function formatNumber(num, locale, options) { 1944 return getNumberFormat(locale, options).format(num); 1945 } 1946 var formatters$4 = { 1947 values: function values(value) { 1948 return isArray(value) ? value : '' + value; 1949 }, 1950 numeric: function numeric(tickValue, index, ticks) { 1951 if (tickValue === 0) { 1952 return '0'; 1953 } 1954 var locale = this.chart.options.locale; 1955 var notation; 1956 var delta = tickValue; 1957 if (ticks.length > 1) { 1958 var maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value)); 1959 if (maxTick < 1e-4 || maxTick > 1e+15) { 1960 notation = 'scientific'; 1961 } 1962 delta = calculateDelta(tickValue, ticks); 1963 } 1964 var logDelta = log10(Math.abs(delta)); 1965 var numDecimal = isNaN(logDelta) ? 1 : Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0); 1966 var options = { 1967 notation: notation, 1968 minimumFractionDigits: numDecimal, 1969 maximumFractionDigits: numDecimal 1970 }; 1971 Object.assign(options, this.options.ticks.format); 1972 return formatNumber(tickValue, locale, options); 1973 }, 1974 logarithmic: function logarithmic(tickValue, index, ticks) { 1975 if (tickValue === 0) { 1976 return '0'; 1977 } 1978 var remain = ticks[index].significand || tickValue / Math.pow(10, Math.floor(log10(tickValue))); 1979 if ([1, 2, 3, 5, 10, 15].includes(remain) || index > 0.8 * ticks.length) { 1980 return formatters$4.numeric.call(this, tickValue, index, ticks); 1981 } 1982 return ''; 1983 } 1984 }; 1985 function calculateDelta(tickValue, ticks) { 1986 var delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value; 1987 if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) { 1988 delta = tickValue - Math.floor(tickValue); 1989 } 1990 return delta; 1991 } 1992 var Ticks = { 1993 formatters: formatters$4 1994 }; 1995 function applyScaleDefaults(defaults) { 1996 defaults.set('scale', { 1997 display: true, 1998 offset: false, 1999 reverse: false, 2000 beginAtZero: false, 2001 bounds: 'ticks', 2002 clip: true, 2003 grace: 0, 2004 grid: { 2005 display: true, 2006 lineWidth: 1, 2007 drawOnChartArea: true, 2008 drawTicks: true, 2009 tickLength: 8, 2010 tickWidth: function tickWidth(_ctx, options) { 2011 return options.lineWidth; 2012 }, 2013 tickColor: function tickColor(_ctx, options) { 2014 return options.color; 2015 }, 2016 offset: false 2017 }, 2018 border: { 2019 display: true, 2020 dash: [], 2021 dashOffset: 0.0, 2022 width: 1 2023 }, 2024 title: { 2025 display: false, 2026 text: '', 2027 padding: { 2028 top: 4, 2029 bottom: 4 2030 } 2031 }, 2032 ticks: { 2033 minRotation: 0, 2034 maxRotation: 50, 2035 mirror: false, 2036 textStrokeWidth: 0, 2037 textStrokeColor: '', 2038 padding: 3, 2039 display: true, 2040 autoSkip: true, 2041 autoSkipPadding: 3, 2042 labelOffset: 0, 2043 callback: Ticks.formatters.values, 2044 minor: {}, 2045 major: {}, 2046 align: 'center', 2047 crossAlign: 'near', 2048 showLabelBackdrop: false, 2049 backdropColor: 'rgba(255, 255, 255, 0.75)', 2050 backdropPadding: 2 2051 } 2052 }); 2053 defaults.route('scale.ticks', 'color', '', 'color'); 2054 defaults.route('scale.grid', 'color', '', 'borderColor'); 2055 defaults.route('scale.border', 'color', '', 'borderColor'); 2056 defaults.route('scale.title', 'color', '', 'color'); 2057 defaults.describe('scale', { 2058 _fallback: false, 2059 _scriptable: function _scriptable(name) { 2060 return !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser'; 2061 }, 2062 _indexable: function _indexable(name) { 2063 return name !== 'borderDash' && name !== 'tickBorderDash' && name !== 'dash'; 2064 } 2065 }); 2066 defaults.describe('scales', { 2067 _fallback: 'scale' 2068 }); 2069 defaults.describe('scale.ticks', { 2070 _scriptable: function _scriptable(name) { 2071 return name !== 'backdropPadding' && name !== 'callback'; 2072 }, 2073 _indexable: function _indexable(name) { 2074 return name !== 'backdropPadding'; 2075 } 2076 }); 2077 } 2078 var overrides = Object.create(null); 2079 var descriptors = Object.create(null); 2080 function getScope$1(node, key) { 2081 if (!key) { 2082 return node; 2083 } 2084 var keys = key.split('.'); 2085 for (var i = 0, n = keys.length; i < n; ++i) { 2086 var k = keys[i]; 2087 node = node[k] || (node[k] = Object.create(null)); 2088 } 2089 return node; 2090 } 2091 function _set(root, scope, values) { 2092 if (typeof scope === 'string') { 2093 return merge(getScope$1(root, scope), values); 2094 } 2095 return merge(getScope$1(root, ''), scope); 2096 } 2097 var Defaults = /*#__PURE__*/function () { 2098 function Defaults(_descriptors, _appliers) { 2099 _classCallCheck$1(this, Defaults); 2100 this.animation = undefined; 2101 this.backgroundColor = 'rgba(0,0,0,0.1)'; 2102 this.borderColor = 'rgba(0,0,0,0.1)'; 2103 this.color = '#666'; 2104 this.datasets = {}; 2105 this.devicePixelRatio = function (context) { 2106 return context.chart.platform.getDevicePixelRatio(); 2107 }; 2108 this.elements = {}; 2109 this.events = ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove']; 2110 this.font = { 2111 family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", 2112 size: 12, 2113 style: 'normal', 2114 lineHeight: 1.2, 2115 weight: null 2116 }; 2117 this.hover = {};
2118 this.hoverBackgroundColor = function (ctx, options) { 2119 return getHoverColor(options.backgroundColor); 2120 }; 2121 this.hoverBorderColor = function (ctx, options) { 2122 return getHoverColor(options.borderColor); 2123 }; 2124 this.hoverColor = function (ctx, options) { 2125 return getHoverColor(options.color); 2126 }; 2127 this.indexAxis = 'x'; 2128 this.interaction = { 2129 mode: 'nearest', 2130 intersect: true, 2131 includeInvisible: false 2132 }; 2133 this.maintainAspectRatio = true; 2134 this.onHover = null; 2135 this.onClick = null; 2136 this.parsing = true; 2137 this.plugins = {}; 2138 this.responsive = true; 2139 this.scale = undefined; 2140 this.scales = {}; 2141 this.showLine = true; 2142 this.drawActiveElementsOnTop = true; 2143 this.describe(_descriptors); 2144 this.apply(_appliers); 2145 } 2146 return _createClass$1(Defaults, [{ 2147 key: "set", 2148 value: function set(scope, values) { 2149 return _set(this, scope, values); 2150 } 2151 }, { 2152 key: "get", 2153 value: function get(scope) { 2154 return getScope$1(this, scope); 2155 } 2156 }, { 2157 key: "describe", 2158 value: function describe(scope, values) { 2159 return _set(descriptors, scope, values); 2160 } 2161 }, { 2162 key: "override", 2163 value: function override(scope, values) { 2164 return _set(overrides, scope, values); 2165 } 2166 }, { 2167 key: "route", 2168 value: function route(scope, name, targetScope, targetName) { 2169 var scopeObject = getScope$1(this, scope); 2170 var targetScopeObject = getScope$1(this, targetScope); 2171 var privateName = '_' + name; 2172 Object.defineProperties(scopeObject, _defineProperty$1(_defineProperty$1({}, privateName, { 2173 value: scopeObject[name], 2174 writable: true 2175 }), name, { 2176 enumerable: true, 2177 get: function get() { 2178 var local = this[privateName]; 2179 var target = targetScopeObject[targetName]; 2180 if (isObject(local)) { 2181 return Object.assign({}, target, local); 2182 } 2183 return valueOrDefault(local, target); 2184 }, 2185 set: function set(value) { 2186 this[privateName] = value; 2187 } 2188 })); 2189 } 2190 }, { 2191 key: "apply", 2192 value: function apply(appliers) { 2193 var _this = this; 2194 appliers.forEach(function (apply) { 2195 return apply(_this); 2196 }); 2197 } 2198 }]); 2199 }(); 2200 var defaults = /* #__PURE__ */new Defaults({ 2201 _scriptable: function _scriptable(name) { 2202 return !name.startsWith('on'); 2203 }, 2204 _indexable: function _indexable(name) { 2205 return name !== 'events'; 2206 }, 2207 hover: { 2208 _fallback: 'interaction' 2209 }, 2210 interaction: { 2211 _scriptable: false, 2212 _indexable: false 2213 } 2214 }, [applyAnimationsDefaults, applyLayoutsDefaults, applyScaleDefaults]); 2215 2216 /** 2217 * Converts the given font object into a CSS font string. 2218 * @param font - A font object. 2219 * @return The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font 2220 * @private 2221 */ 2222 function toFontString(font) { 2223 if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) { 2224 return null; 2225 } 2226 return (font.style ? font.style + ' ' : '') + (font.weight ? font.weight + ' ' : '') + font.size + 'px ' + font.family; 2227 } 2228 /** 2229 * @private 2230 */ 2231 function _measureText(ctx, data, gc, longest, string) { 2232 var textWidth = data[string]; 2233 if (!textWidth) { 2234 textWidth = data[string] = ctx.measureText(string).width; 2235 gc.push(string); 2236 } 2237 if (textWidth > longest) { 2238 longest = textWidth; 2239 } 2240 return longest; 2241 } 2242 /** 2243 * @private 2244 */ // eslint-disable-next-line complexity 2245 function _longestText(ctx, font, arrayOfThings, cache) { 2246 cache = cache || {}; 2247 var data = cache.data = cache.data || {}; 2248 var gc = cache.garbageCollect = cache.garbageCollect || []; 2249 if (cache.font !== font) { 2250 data = cache.data = {}; 2251 gc = cache.garbageCollect = []; 2252 cache.font = font; 2253 } 2254 ctx.save(); 2255 ctx.font = font; 2256 var longest = 0; 2257 var ilen = arrayOfThings.length; 2258 var i, j, jlen, thing, nestedThing; 2259 for (i = 0; i < ilen; i++) { 2260 thing = arrayOfThings[i]; 2261 // Undefined strings and arrays should not be measured 2262 if (thing !== undefined && thing !== null && !isArray(thing)) { 2263 longest = _measureText(ctx, data, gc, longest, thing); 2264 } else if (isArray(thing)) { 2265 // if it is an array lets measure each element 2266 // to do maybe simplify this function a bit so we can do this more recursively? 2267 for (j = 0, jlen = thing.length; j < jlen; j++) { 2268 nestedThing = thing[j]; 2269 // Undefined strings and arrays should not be measured 2270 if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) { 2271 longest = _measureText(ctx, data, gc, longest, nestedThing); 2272 } 2273 } 2274 } 2275 }
vendor: 12,902 bytes, lines 2276-2634
2276 ctx.restore(); 2277 var gcLen = gc.length / 2; 2278 if (gcLen > arrayOfThings.length) { 2279 for (i = 0; i < gcLen; i++) { 2280 delete data[gc[i]]; 2281 } 2282 gc.splice(0, gcLen); 2283 } 2284 return longest; 2285 } 2286 /** 2287 * Returns the aligned pixel value to avoid anti-aliasing blur 2288 * @param chart - The chart instance. 2289 * @param pixel - A pixel value. 2290 * @param width - The width of the element. 2291 * @returns The aligned pixel value. 2292 * @private 2293 */ 2294 function _alignPixel(chart, pixel, width) { 2295 var devicePixelRatio = chart.currentDevicePixelRatio; 2296 var halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0; 2297 return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth; 2298 } 2299 /** 2300 * Clears the entire canvas. 2301 */ 2302 function clearCanvas(canvas, ctx) { 2303 if (!ctx && !canvas) { 2304 return; 2305 } 2306 ctx = ctx || canvas.getContext('2d'); 2307 ctx.save(); 2308 // canvas.width and canvas.height do not consider the canvas transform, 2309 // while clearRect does 2310 ctx.resetTransform(); 2311 ctx.clearRect(0, 0, canvas.width, canvas.height); 2312 ctx.restore(); 2313 } 2314 function drawPoint(ctx, options, x, y) { 2315 // eslint-disable-next-line @typescript-eslint/no-use-before-define 2316 drawPointLegend(ctx, options, x, y, null); 2317 } 2318 // eslint-disable-next-line complexity 2319 function drawPointLegend(ctx, options, x, y, w) { 2320 var type, xOffset, yOffset, size, cornerRadius, width, xOffsetW, yOffsetW; 2321 var style = options.pointStyle; 2322 var rotation = options.rotation; 2323 var radius = options.radius; 2324 var rad = (rotation || 0) * RAD_PER_DEG; 2325 if (style && _typeof$1(style) === 'object') { 2326 type = style.toString(); 2327 if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') { 2328 ctx.save(); 2329 ctx.translate(x, y); 2330 ctx.rotate(rad); 2331 ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height); 2332 ctx.restore(); 2333 return; 2334 } 2335 } 2336 if (isNaN(radius) || radius <= 0) { 2337 return; 2338 } 2339 ctx.beginPath(); 2340 switch (style) { 2341 // Default includes circle 2342 default: 2343 if (w) { 2344 ctx.ellipse(x, y, w / 2, radius, 0, 0, TAU); 2345 } else { 2346 ctx.arc(x, y, radius, 0, TAU); 2347 } 2348 ctx.closePath(); 2349 break; 2350 case 'triangle': 2351 width = w ? w / 2 : radius; 2352 ctx.moveTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius); 2353 rad += TWO_THIRDS_PI; 2354 ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius); 2355 rad += TWO_THIRDS_PI; 2356 ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius); 2357 ctx.closePath(); 2358 break; 2359 case 'rectRounded': 2360 // NOTE: the rounded rect implementation changed to use `arc` instead of 2361 // `quadraticCurveTo` since it generates better results when rect is 2362 // almost a circle. 0.516 (instead of 0.5) produces results with visually 2363 // closer proportion to the previous impl and it is inscribed in the 2364 // circle with `radius`. For more details, see the following PRs: 2365 // https://github.com/chartjs/Chart.js/issues/5597 2366 // https://github.com/chartjs/Chart.js/issues/5858 2367 cornerRadius = radius * 0.516; 2368 size = radius - cornerRadius; 2369 xOffset = Math.cos(rad + QUARTER_PI) * size; 2370 xOffsetW = Math.cos(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size); 2371 yOffset = Math.sin(rad + QUARTER_PI) * size; 2372 yOffsetW = Math.sin(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size); 2373 ctx.arc(x - xOffsetW, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI); 2374 ctx.arc(x + yOffsetW, y - xOffset, cornerRadius, rad - HALF_PI, rad); 2375 ctx.arc(x + xOffsetW, y + yOffset, cornerRadius, rad, rad + HALF_PI); 2376 ctx.arc(x - yOffsetW, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI); 2377 ctx.closePath(); 2378 break; 2379 case 'rect': 2380 if (!rotation) { 2381 size = Math.SQRT1_2 * radius; 2382 width = w ? w / 2 : size; 2383 ctx.rect(x - width, y - size, 2 * width, 2 * size); 2384 break; 2385 } 2386 rad += QUARTER_PI; 2387 /* falls through */ 2388 case 'rectRot': 2389 xOffsetW = Math.cos(rad) * (w ? w / 2 : radius); 2390 xOffset = Math.cos(rad) * radius; 2391 yOffset = Math.sin(rad) * radius; 2392 yOffsetW = Math.sin(rad) * (w ? w / 2 : radius); 2393 ctx.moveTo(x - xOffsetW, y - yOffset); 2394 ctx.lineTo(x + yOffsetW, y - xOffset); 2395 ctx.lineTo(x + xOffsetW, y + yOffset); 2396 ctx.lineTo(x - yOffsetW, y + xOffset); 2397 ctx.closePath(); 2398 break; 2399 case 'crossRot': 2400 rad += QUARTER_PI; 2401 /* falls through */ 2402 case 'cross': 2403 xOffsetW = Math.cos(rad) * (w ? w / 2 : radius); 2404 xOffset = Math.cos(rad) * radius; 2405 yOffset = Math.sin(rad) * radius; 2406 yOffsetW = Math.sin(rad) * (w ? w / 2 : radius); 2407 ctx.moveTo(x - xOffsetW, y - yOffset); 2408 ctx.lineTo(x + xOffsetW, y + yOffset); 2409 ctx.moveTo(x + yOffsetW, y - xOffset); 2410 ctx.lineTo(x - yOffsetW, y + xOffset); 2411 break; 2412 case 'star': 2413 xOffsetW = Math.cos(rad) * (w ? w / 2 : radius); 2414 xOffset = Math.cos(rad) * radius; 2415 yOffset = Math.sin(rad) * radius; 2416 yOffsetW = Math.sin(rad) * (w ? w / 2 : radius); 2417 ctx.moveTo(x - xOffsetW, y - yOffset); 2418 ctx.lineTo(x + xOffsetW, y + yOffset); 2419 ctx.moveTo(x + yOffsetW, y - xOffset); 2420 ctx.lineTo(x - yOffsetW, y + xOffset); 2421 rad += QUARTER_PI; 2422 xOffsetW = Math.cos(rad) * (w ? w / 2 : radius); 2423 xOffset = Math.cos(rad) * radius; 2424 yOffset = Math.sin(rad) * radius; 2425 yOffsetW = Math.sin(rad) * (w ? w / 2 : radius); 2426 ctx.moveTo(x - xOffsetW, y - yOffset); 2427 ctx.lineTo(x + xOffsetW, y + yOffset); 2428 ctx.moveTo(x + yOffsetW, y - xOffset); 2429 ctx.lineTo(x - yOffsetW, y + xOffset); 2430 break; 2431 case 'line': 2432 xOffset = w ? w / 2 : Math.cos(rad) * radius; 2433 yOffset = Math.sin(rad) * radius; 2434 ctx.moveTo(x - xOffset, y - yOffset); 2435 ctx.lineTo(x + xOffset, y + yOffset); 2436 break; 2437 case 'dash': 2438 ctx.moveTo(x, y); 2439 ctx.lineTo(x + Math.cos(rad) * (w ? w / 2 : radius), y + Math.sin(rad) * radius); 2440 break; 2441 case false: 2442 ctx.closePath(); 2443 break; 2444 } 2445 ctx.fill(); 2446 if (options.borderWidth > 0) { 2447 ctx.stroke(); 2448 } 2449 } 2450 /** 2451 * Returns true if the point is inside the rectangle 2452 * @param point - The point to test 2453 * @param area - The rectangle 2454 * @param margin - allowed margin 2455 * @private 2456 */ 2457 function _isPointInArea(point, area, margin) { 2458 margin = margin || 0.5; // margin - default is to match rounded decimals 2459 return !area || point && point.x > area.left - margin && point.x < area.right + margin && point.y > area.top - margin && point.y < area.bottom + margin; 2460 } 2461 function clipArea(ctx, area) { 2462 ctx.save(); 2463 ctx.beginPath(); 2464 ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); 2465 ctx.clip(); 2466 } 2467 function unclipArea(ctx) { 2468 ctx.restore(); 2469 } 2470 /** 2471 * @private 2472 */ 2473 function _steppedLineTo(ctx, previous, target, flip, mode) { 2474 if (!previous) { 2475 return ctx.lineTo(target.x, target.y); 2476 } 2477 if (mode === 'middle') { 2478 var midpoint = (previous.x + target.x) / 2.0; 2479 ctx.lineTo(midpoint, previous.y); 2480 ctx.lineTo(midpoint, target.y); 2481 } else if (mode === 'after' !== !!flip) { 2482 ctx.lineTo(previous.x, target.y); 2483 } else { 2484 ctx.lineTo(target.x, previous.y); 2485 } 2486 ctx.lineTo(target.x, target.y); 2487 } 2488 /** 2489 * @private 2490 */ 2491 function _bezierCurveTo(ctx, previous, target, flip) { 2492 if (!previous) { 2493 return ctx.lineTo(target.x, target.y); 2494 } 2495 ctx.bezierCurveTo(flip ? previous.cp1x : previous.cp2x, flip ? previous.cp1y : previous.cp2y, flip ? target.cp2x : target.cp1x, flip ? target.cp2y : target.cp1y, target.x, target.y); 2496 } 2497 function setRenderOpts(ctx, opts) { 2498 if (opts.translation) { 2499 ctx.translate(opts.translation[0], opts.translation[1]); 2500 } 2501 if (!isNullOrUndef(opts.rotation)) { 2502 ctx.rotate(opts.rotation); 2503 } 2504 if (opts.color) { 2505 ctx.fillStyle = opts.color; 2506 } 2507 if (opts.textAlign) { 2508 ctx.textAlign = opts.textAlign; 2509 } 2510 if (opts.textBaseline) { 2511 ctx.textBaseline = opts.textBaseline; 2512 } 2513 } 2514 function decorateText(ctx, x, y, line, opts) { 2515 if (opts.strikethrough || opts.underline) { 2516 /** 2517 * Now that IE11 support has been dropped, we can use more 2518 * of the TextMetrics object. The actual bounding boxes 2519 * are unflagged in Chrome, Firefox, Edge, and Safari so they 2520 * can be safely used. 2521 * See https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics#Browser_compatibility 2522 */ 2523 var metrics = ctx.measureText(line); 2524 var left = x - metrics.actualBoundingBoxLeft; 2525 var right = x + metrics.actualBoundingBoxRight; 2526 var top = y - metrics.actualBoundingBoxAscent; 2527 var bottom = y + metrics.actualBoundingBoxDescent; 2528 var yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom; 2529 ctx.strokeStyle = ctx.fillStyle; 2530 ctx.beginPath(); 2531 ctx.lineWidth = opts.decorationWidth || 2; 2532 ctx.moveTo(left, yDecoration); 2533 ctx.lineTo(right, yDecoration); 2534 ctx.stroke(); 2535 } 2536 } 2537 function drawBackdrop(ctx, opts) { 2538 var oldColor = ctx.fillStyle; 2539 ctx.fillStyle = opts.color; 2540 ctx.fillRect(opts.left, opts.top, opts.width, opts.height); 2541 ctx.fillStyle = oldColor; 2542 } 2543 /** 2544 * Render text onto the canvas 2545 */ 2546 function renderText(ctx, text, x, y, font) { 2547 var opts = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {}; 2548 var lines = isArray(text) ? text : [text]; 2549 var stroke = opts.strokeWidth > 0 && opts.strokeColor !== ''; 2550 var i, line; 2551 ctx.save(); 2552 ctx.font = font.string; 2553 setRenderOpts(ctx, opts); 2554 for (i = 0; i < lines.length; ++i) { 2555 line = lines[i]; 2556 if (opts.backdrop) { 2557 drawBackdrop(ctx, opts.backdrop); 2558 } 2559 if (stroke) { 2560 if (opts.strokeColor) { 2561 ctx.strokeStyle = opts.strokeColor; 2562 } 2563 if (!isNullOrUndef(opts.strokeWidth)) { 2564 ctx.lineWidth = opts.strokeWidth; 2565 } 2566 ctx.strokeText(line, x, y, opts.maxWidth); 2567 } 2568 ctx.fillText(line, x, y, opts.maxWidth); 2569 decorateText(ctx, x, y, line, opts); 2570 y += Number(font.lineHeight); 2571 } 2572 ctx.restore(); 2573 } 2574 /** 2575 * Add a path of a rectangle with rounded corners to the current sub-path 2576 * @param ctx - Context 2577 * @param rect - Bounding rect 2578 */ 2579 function addRoundedRectPath(ctx, rect) { 2580 var x = rect.x, 2581 y = rect.y, 2582 w = rect.w, 2583 h = rect.h, 2584 radius = rect.radius; 2585 // top left arc 2586 ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, 1.5 * PI, PI, true); 2587 // line from top left to bottom left 2588 ctx.lineTo(x, y + h - radius.bottomLeft); 2589 // bottom left arc 2590 ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true); 2591 // line from bottom left to bottom right 2592 ctx.lineTo(x + w - radius.bottomRight, y + h); 2593 // bottom right arc 2594 ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true); 2595 // line from bottom right to top right 2596 ctx.lineTo(x + w, y + radius.topRight); 2597 // top right arc 2598 ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true); 2599 // line from top right to top left 2600 ctx.lineTo(x + radius.topLeft, y); 2601 } 2602 var LINE_HEIGHT = /^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/; 2603 var FONT_STYLE = /^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/; 2604 /** 2605 * @alias Chart.helpers.options 2606 * @namespace 2607 */ /** 2608 * Converts the given line height `value` in pixels for a specific font `size`. 2609 * @param value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em'). 2610 * @param size - The font size (in pixels) used to resolve relative `value`. 2611 * @returns The effective line height in pixels (size * 1.2 if value is invalid). 2612 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height 2613 * @since 2.7.0 2614 */ 2615 function toLineHeight(value, size) { 2616 var matches = ('' + value).match(LINE_HEIGHT); 2617 if (!matches || matches[1] === 'normal') { 2618 return size * 1.2; 2619 } 2620 value = +matches[2]; 2621 switch (matches[3]) { 2622 case 'px': 2623 return value; 2624 case '%': 2625 value /= 100; 2626 break; 2627 } 2628 return size * value; 2629 } 2630 var numberOrZero = function numberOrZero(v) { 2631 return +v || 0; 2632 }; 2633 function _readValueToProps(value, props) { 2634 var ret = {};
2635 var objProps = isObject(props); 2636 var keys = objProps ? Object.keys(props) : props; 2637 var read = isObject(value) ? objProps ? function (prop) { 2638 return valueOrDefault(value[prop], value[props[prop]]); 2639 } : function (prop) { 2640 return value[prop]; 2641 } : function () { 2642 return value; 2643 }; 2644 var _iterator4 = _createForOfIteratorHelper$1(keys), 2645 _step4; 2646 try { 2647 for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { 2648 var prop = _step4.value; 2649 ret[prop] = numberOrZero(read(prop)); 2650 } 2651 } catch (err) { 2652 _iterator4.e(err); 2653 } finally { 2654 _iterator4.f(); 2655 } 2656 return ret; 2657 } 2658 /** 2659 * Converts the given value into a TRBL object. 2660 * @param value - If a number, set the value to all TRBL component, 2661 * else, if an object, use defined properties and sets undefined ones to 0. 2662 * x / y are shorthands for same value for left/right and top/bottom. 2663 * @returns The padding values (top, right, bottom, left) 2664 * @since 3.0.0 2665 */ 2666 function toTRBL(value) { 2667 return _readValueToProps(value, { 2668 top: 'y', 2669 right: 'x', 2670 bottom: 'y', 2671 left: 'x' 2672 }); 2673 } 2674 /** 2675 * Converts the given value into a TRBL corners object (similar with css border-radius). 2676 * @param value - If a number, set the value to all TRBL corner components, 2677 * else, if an object, use defined properties and sets undefined ones to 0.
2678 * @returns The TRBL corner values (topLeft, topRight, bottomLeft, bottomRight) 2679 * @since 3.0.0 2680 */ 2681 function toTRBLCorners(value) { 2682 return _readValueToProps(value, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']); 2683 } 2684 /** 2685 * Converts the given value into a padding object with pre-computed width/height. 2686 * @param value - If a number, set the value to all TRBL component, 2687 * else, if an object, use defined properties and sets undefined ones to 0. 2688 * x / y are shorthands for same value for left/right and top/bottom. 2689 * @returns The padding values (top, right, bottom, left, width, height) 2690 * @since 2.7.0 2691 */ 2692 function toPadding(value) { 2693 var obj = toTRBL(value); 2694 obj.width = obj.left + obj.right; 2695 obj.height = obj.top + obj.bottom; 2696 return obj; 2697 } 2698 /** 2699 * Parses font options and returns the font object. 2700 * @param options - A object that contains font options to be parsed. 2701 * @param fallback - A object that contains fallback font options. 2702 * @return The font object. 2703 * @private 2704 */ 2705 function toFont(options, fallback) { 2706 options = options || {}; 2707 fallback = fallback || defaults.font; 2708 var size = valueOrDefault(options.size, fallback.size); 2709 if (typeof size === 'string') { 2710 size = parseInt(size, 10); 2711 } 2712 var style = valueOrDefault(options.style, fallback.style); 2713 if (style && !('' + style).match(FONT_STYLE)) { 2714 console.warn('Invalid font style specified: "' + style + '"'); 2715 style = undefined; 2716 } 2717 var font = { 2718 family: valueOrDefault(options.family, fallback.family), 2719 lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size), 2720 size: size, 2721 style: style, 2722 weight: valueOrDefault(options.weight, fallback.weight), 2723 string: '' 2724 }; 2725 font.string = toFontString(font); 2726 return font; 2727 } 2728 /** 2729 * Evaluates the given `inputs` sequentially and returns the first defined value. 2730 * @param inputs - An array of values, falling back to the last value. 2731 * @param context - If defined and the current value is a function, the value 2732 * is called with `context` as first argument and the result becomes the new input. 2733 * @param index - If defined and the current value is an array, the value 2734 * at `index` become the new input. 2735 * @param info - object to return information about resolution in 2736 * @param info.cacheable - Will be set to `false` if option is not cacheable. 2737 * @since 2.7.0 2738 */ 2739 function resolve(inputs, context, index, info) { 2740 var cacheable = true; 2741 var i, ilen, value; 2742 for (i = 0, ilen = inputs.length; i < ilen; ++i) { 2743 value = inputs[i]; 2744 if (value === undefined) { 2745 continue; 2746 } 2747 if (context !== undefined && typeof value === 'function') { 2748 value = value(context); 2749 cacheable = false; 2750 } 2751 if (index !== undefined && isArray(value)) { 2752 value = value[index % value.length]; 2753 cacheable = false; 2754 } 2755 if (value !== undefined) { 2756 if (info && !cacheable) { 2757 info.cacheable = false; 2758 } 2759 return value; 2760 } 2761 } 2762 } 2763 /** 2764 * @param minmax 2765 * @param grace 2766 * @param beginAtZero 2767 * @private 2768 */ 2769 function _addGrace(minmax, grace, beginAtZero) { 2770 var min = minmax.min, 2771 max = minmax.max; 2772 var change = toDimension(grace, (max - min) / 2); 2773 var keepZero = function keepZero(value, add) { 2774 return beginAtZero && value === 0 ? 0 : value + add; 2775 }; 2776 return { 2777 min: keepZero(min, -Math.abs(change)), 2778 max: keepZero(max, change) 2779 }; 2780 } 2781 function createContext(parentContext, context) { 2782 return Object.assign(Object.create(parentContext), context); 2783 } 2784 2785 /** 2786 * Creates a Proxy for resolving raw values for options. 2787 * @param scopes - The option scopes to look for values, in resolution order 2788 * @param prefixes - The prefixes for values, in resolution order. 2789 * @param rootScopes - The root option scopes 2790 * @param fallback - Parent scopes fallback 2791 * @param getTarget - callback for getting the target for changed values 2792 * @returns Proxy 2793 * @private 2794 */ 2795 function _createResolver(scopes) { 2796 var prefixes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['']; 2797 var rootScopes = arguments.length > 2 ? arguments[2] : undefined; 2798 var fallback = arguments.length > 3 ? arguments[3] : undefined; 2799 var getTarget = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : function () { 2800 return scopes[0]; 2801 }; 2802 var finalRootScopes = rootScopes || scopes; 2803 if (typeof fallback === 'undefined') { 2804 fallback = _resolve('_fallback', scopes); 2805 } 2806 var cache = _defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1(_defineProperty$1({}, Symbol.toStringTag, 'Object'), "_cacheable", true), "_scopes", scopes), "_rootScopes", finalRootScopes), "_fallback", fallback), "_getTarget", getTarget), "override", function override(scope) { 2807 return _createResolver([scope].concat(_toConsumableArray(scopes)), prefixes, finalRootScopes, fallback); 2808 }); 2809 return new Proxy(cache, { 2810 /** 2811 * A trap for the delete operator. 2812 */ 2813 deleteProperty: function deleteProperty(target, prop) { 2814 delete target[prop]; // remove from cache 2815 delete target._keys; // remove cached keys 2816 delete scopes[0][prop]; // remove from top level scope 2817 return true; 2818 }, 2819 /** 2820 * A trap for getting property values. 2821 */ 2822 get: function get(target, prop) { 2823 return _cached(target, prop, function () { 2824 return _resolveWithPrefixes(prop, prefixes, scopes, target); 2825 }); 2826 }, 2827 /** 2828 * A trap for Object.getOwnPropertyDescriptor. 2829 * Also used by Object.hasOwnProperty. 2830 */ 2831 getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, prop) { 2832 return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop); 2833 }, 2834 /** 2835 * A trap for Object.getPrototypeOf. 2836 */ 2837 getPrototypeOf: function getPrototypeOf() { 2838 return Reflect.getPrototypeOf(scopes[0]); 2839 }, 2840 /** 2841 * A trap for the in operator. 2842 */ 2843 has: function has(target, prop) { 2844 return getKeysFromAllScopes(target).includes(prop); 2845 }, 2846 /** 2847 * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols. 2848 */ 2849 ownKeys: function ownKeys(target) { 2850 return getKeysFromAllScopes(target); 2851 }, 2852 /** 2853 * A trap for setting property values. 2854 */ 2855 set: function set(target, prop, value) { 2856 var storage = target._storage || (target._storage = getTarget()); 2857 target[prop] = storage[prop] = value; // set to top level scope + cache 2858 delete target._keys; // remove cached keys 2859 return true; 2860 } 2861 }); 2862 } 2863 /** 2864 * Returns an Proxy for resolving option values with context. 2865 * @param proxy - The Proxy returned by `_createResolver` 2866 * @param context - Context object for scriptable/indexable options 2867 * @param subProxy - The proxy provided for scriptable options 2868 * @param descriptorDefaults - Defaults for descriptors 2869 * @private 2870 */ 2871 function _attachContext(proxy, context, subProxy, descriptorDefaults) { 2872 var cache = { 2873 _cacheable: false, 2874 _proxy: proxy, 2875 _context: context, 2876 _subProxy: subProxy, 2877 _stack: new Set(), 2878 _descriptors: _descriptors(proxy, descriptorDefaults), 2879 setContext: function setContext(ctx) { 2880 return _attachContext(proxy, ctx, subProxy, descriptorDefaults); 2881 }, 2882 override: function override(scope) { 2883 return _attachContext(proxy.override(scope), context, subProxy, descriptorDefaults); 2884 } 2885 }; 2886 return new Proxy(cache, { 2887 /** 2888 * A trap for the delete operator. 2889 */ 2890 deleteProperty: function deleteProperty(target, prop) { 2891 delete target[prop]; // remove from cache 2892 delete proxy[prop]; // remove from proxy 2893 return true; 2894 }, 2895 /** 2896 * A trap for getting property values. 2897 */ 2898 get: function get(target, prop, receiver) { 2899 return _cached(target, prop, function () { 2900 return _resolveWithContext(target, prop, receiver); 2901 }); 2902 }, 2903 /** 2904 * A trap for Object.getOwnPropertyDescriptor. 2905 * Also used by Object.hasOwnProperty. 2906 */ 2907 getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, prop) { 2908 return target._descriptors.allKeys ? Reflect.has(proxy, prop
2908) ? { 2909 enumerable: true, 2910 configurable: true 2911 } : undefined : Reflect.getOwnPropertyDescriptor(proxy, prop); 2912 }, 2913 /** 2914 * A trap for Object.getPrototypeOf. 2915 */ 2916 getPrototypeOf: function getPrototypeOf() { 2917 return Reflect.getPrototypeOf(proxy); 2918 }, 2919 /** 2920 * A trap for the in operator. 2921 */ 2922 has: function has(target, prop) { 2923 return Reflect.has(proxy, prop); 2924 }, 2925 /** 2926 * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols. 2927 */ 2928 ownKeys: function ownKeys() { 2929 return Reflect.ownKeys(proxy); 2930 }, 2931 /** 2932 * A trap for setting property values. 2933 */ 2934 set: function set(target, prop, value) { 2935 proxy[prop] = value; // set to proxy 2936 delete target[prop]; // remove from cache 2937 return true; 2938 } 2939 }); 2940 } 2941 /** 2942 * @private 2943 */ 2944 function _descriptors(proxy) { 2945 var defaults = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { 2946 scriptable: true, 2947 indexable: true 2948 }; 2949 var _proxy$_scriptable = proxy._scriptable, 2950 _scriptable = _proxy$_scriptable === void 0 ? defaults.scriptable : _proxy$_scriptable, 2951 _proxy$_indexable = proxy._indexable, 2952 _indexable = _proxy$_indexable === void 0 ? defaults.indexable : _proxy$_indexable, 2953 _proxy$_allKeys = proxy._allKeys, 2954 _allKeys = _proxy$_allKeys === void 0 ? defaults.allKeys : _proxy$_allKeys; 2955 return { 2956 allKeys: _allKeys, 2957 scriptable: _scriptable, 2958 indexable: _indexable, 2959 isScriptable: isFunction(_scriptable) ? _scriptable : function () { 2960 return _scriptable; 2961 }, 2962 isIndexable: isFunction(_indexable) ? _indexable : function () { 2963 return _indexable; 2964 } 2965 }; 2966 } 2967 var readKey = function readKey(prefix, name) { 2968 return prefix ? prefix + _capitalize(name) : name; 2969 }; 2970 var needsSubResolver = function needsSubResolver(prop, value) { 2971 return isObject(value) && prop !== 'adapters' && (Object.getPrototypeOf(value) === null || value.constructor === Object); 2972 }; 2973 function _cached(target, prop, resolve) { 2974 if (Object.prototype.hasOwnProperty.call(target, prop) || prop === 'constructor') { 2975 return target[prop]; 2976 } 2977 var value = resolve(); 2978 // cache the resolved value 2979 target[prop] = value; 2980 return value; 2981 } 2982 function _resolveWithContext(target, prop, receiver) { 2983 var _proxy = target._proxy, 2984 _context = target._context, 2985 _subProxy = target._subProxy, 2986 descriptors = target._descriptors; 2987 var value = _proxy[prop]; // resolve from proxy 2988 // resolve with context 2989 if (isFunction(value) && descriptors.isScriptable(prop)) { 2990 value = _resolveScriptable(prop, value, target, receiver); 2991 } 2992 if (isArray(value) && value.length) { 2993 value = _resolveArray(prop, value, target, descriptors.isIndexable); 2994 } 2995 if (needsSubResolver(prop, value)) { 2996 // if the resolved value is an object, create a sub resolver for it 2997 value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors); 2998 } 2999 return value; 3000 } 3001 function _resolveScriptable(prop, getValue, target, receiver) { 3002 var _proxy = target._proxy, 3003 _context = target._context, 3004 _subProxy = target._subProxy, 3005 _stack = target._stack; 3006 if (_stack.has(prop)) { 3007 throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop); 3008 } 3009 _stack.add(prop); 3010 var value = getValue(_context, _subProxy || receiver); 3011 _stack["delete"](prop); 3012 if (needsSubResolver(prop, value)) { 3013 // When scriptable option returns an object, create a resolver on that. 3014 value = createSubResolver(_proxy._scopes, _proxy, prop, value); 3015 } 3016 return value; 3017 } 3018 function _resolveArray(prop, value, target, isIndexable) { 3019 var _proxy = target._proxy, 3020 _context = target._context, 3021 _subProxy = target._subProxy, 3022 descriptors = target._descriptors; 3023 if (typeof _context.index !== 'undefined' && isIndexable(prop)) {
3024 return value[_context.index % value.length]; 3025 } else if (isObject(value[0])) { 3026 // Array of objects, return array or resolvers 3027 var arr = value; 3028 var scopes = _proxy._scopes.filter(function (s) { 3029 return s !== arr; 3030 }); 3031 value = []; 3032 var _iterator5 = _createForOfIteratorHelper$1(arr), 3033 _step5; 3034 try { 3035 for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { 3036 var item = _step5.value; 3037 var resolver = createSubResolver(scopes, _proxy, prop, item); 3038 value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors)); 3039 } 3040 } catch (err) { 3041 _iterator5.e(err); 3042 } finally { 3043 _iterator5.f(); 3044 } 3045 } 3046 return value; 3047 } 3048 function resolveFallback(fallback, prop, value) { 3049 return isFunction(fallback) ? fallback(prop, value) : fallback; 3050 } 3051 var getScope = function getScope(key, parent) { 3052 return key === true ? parent : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined; 3053 }; 3054 function addScopes(set, parentScopes, key, parentFallback, value) { 3055 var _iterator6 = _createForOfIteratorHelper$1(parentScopes), 3056 _step6; 3057 try { 3058 for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { 3059 var parent = _step6.value; 3060 var scope = getScope(key, parent); 3061 if (scope) { 3062 set.add(scope); 3063 var fallback = resolveFallback(scope._fallback, key, value); 3064 if (typeof fallback !== 'undefined' && fallback !== key && fallback !== parentFallback) { 3065 // When we reach the descriptor that defines a new _fallback, return that. 3066 // The fallback will resume to that new scope. 3067 return fallback; 3068 } 3069 } else if (scope === false && typeof parentFallback !== 'undefined' && key !== parentFallback) { 3070 // Fallback to `false` results to `false`, when falling back to different key. 3071 // For example `interaction` from `hover` or `plugins.tooltip` and `animation` from `animations` 3072 return null; 3073 } 3074 } 3075 } catch (err) { 3076 _iterator6.e(err); 3077 } finally { 3078 _iterator6.f(); 3079 } 3080 return false; 3081 } 3082 function createSubResolver(parentScopes, resolver, prop, value) { 3083 var rootScopes = resolver._rootScopes; 3084 var fallback = resolveFallback(resolver._fallback, prop, value); 3085 var allScopes = [].concat(_toConsumableArray(parentScopes), _toConsumableArray(rootScopes)); 3086 var set = new Set(); 3087 set.add(value); 3088 var key = addScopesFromKey(set, allScopes, prop, fallback || prop, value); 3089 if (key === null) { 3090 return false; 3091 } 3092 if (typeof fallback !== 'undefined' && fallback !== prop) { 3093 key = addScopesFromKey(set, allScopes, fallback, key, value); 3094 if (key === null) { 3095 return false; 3096 } 3097 } 3098 return _createResolver(Array.from(set), [''], rootScopes, fallback, function () { 3099 return subGetTarget(resolver, prop, value); 3100 }); 3101 } 3102 function addScopesFromKey(set, allScopes, key, fallback, item) { 3103 while (key) { 3104 key = addScopes(set, allScopes, key, fallback, item); 3105 } 3106 return key; 3107 } 3108 function subGetTarget(resolver, prop, value) { 3109 var parent = resolver._getTarget(); 3110 if (!(prop in parent)) { 3111 parent[prop] = {}; 3112 } 3113 var target = parent[prop]; 3114 if (isArray(target) && isObject(value)) { 3115 // For array of objects, the object is used to store updated values 3116 return value; 3117 } 3118 return target || {}; 3119 } 3120 function _resolveWithPrefixes(prop, prefixes, scopes, proxy) { 3121 var value; 3122 var _iterator7 = _createForOfIteratorHelper$1(prefixes), 3123 _step7; 3124 try { 3125 for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { 3126 var prefix = _step7.value; 3127 value = _resolve(readKey(prefix, prop), scopes); 3128 if (typeof value !== 'undefined') { 3129 return needsSubResolver(prop, value) ? createSubResolver(scopes, proxy, prop, value) : value; 3130 } 3131 } 3132 } catch (err) { 3133 _iterator7.e(err); 3134 } finally { 3135 _iterator7.f(); 3136 } 3137 } 3138 function _resolve(key, scopes) { 3139 var _iterator8 = _createForOfIteratorHelper$1(scopes), 3140 _step8; 3141 try { 3142 for (_iterator8.s();
3142 !(_step8 = _iterator8.n()).done;) { 3143 var scope = _step8.value; 3144 if (!scope) { 3145 continue; 3146 } 3147 var value = scope[key]; 3148 if (typeof value !== 'undefined') { 3149 return value; 3150 } 3151 } 3152 } catch (err) { 3153 _iterator8.e(err); 3154 } finally { 3155 _iterator8.f(); 3156 } 3157 } 3158 function getKeysFromAllScopes(target) { 3159 var keys = target._keys; 3160 if (!keys) { 3161 keys = target._keys = resolveKeysFromAllScopes(target._scopes); 3162 } 3163 return keys; 3164 } 3165 function resolveKeysFromAllScopes(scopes) { 3166 var set = new Set(); 3167 var _iterator9 = _createForOfIteratorHelper$1(scopes), 3168 _step9; 3169 try { 3170 for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) { 3171 var scope = _step9.value; 3172 var _iterator0 = _createForOfIteratorHelper$1(Object.keys(scope).filter(function (k) { 3173 return !k.startsWith('_'); 3174 })), 3175 _step0; 3176 try { 3177 for (_iterator0.s(); !(_step0 = _iterator0.n()).done;) { 3178 var key = _step0.value; 3179 set.add(key); 3180 } 3181 } catch (err) { 3182 _iterator0.e(err); 3183 } finally { 3184 _iterator0.f(); 3185 } 3186 } 3187 } catch (err) { 3188 _iterator9.e(err); 3189 } finally { 3190 _iterator9.f(); 3191 } 3192 return Array.from(set); 3193 } 3194 function _parseObjectDataRadialScale(meta, data, start, count) { 3195 var iScale = meta.iScale; 3196 var _this$_parsing$key = this._parsing.key, 3197 key = _this$_parsing$key === void 0 ? 'r' : _this$_parsing$key; 3198 var parsed = new Array(count); 3199 var i, ilen, index, item; 3200 for (i = 0, ilen = count; i < ilen; ++i) { 3201 index = i + start; 3202 item = data[index]; 3203 parsed[i] = { 3204 r: iScale.parse(resolveObjectKey(item, key), index) 3205 }; 3206 } 3207 return parsed; 3208 } 3209 var EPSILON = Number.EPSILON || 1e-14; 3210 var getPoint = function getPoint(points, i) { 3211 return i < points.length && !points[i].skip && points[i]; 3212 }; 3213 var getValueAxis = function getValueAxis(indexAxis) { 3214 return indexAxis === 'x' ? 'y' : 'x'; 3215 }; 3216 function splineCurve(firstPoint, middlePoint, afterPoint, t) { 3217 // Props to Rob Spencer at scaled innovation for his post on splining between points 3218 // http://scaledinnovation.com/analytics/splines/aboutSplines.html 3219 // This function must also respect "skipped" points 3220 var previous = firstPoint.skip ? middlePoint : firstPoint; 3221 var current = middlePoint; 3222 var next = afterPoint.skip ? middlePoint : afterPoint; 3223 var d01 = distanceBetweenPoints(current, previous); 3224 var d12 = distanceBetweenPoints(next, current); 3225 var s01 = d01 / (d01 + d12); 3226 var s12 = d12 / (d01 + d12); 3227 // If all points are the same, s01 & s02 will be inf 3228 s01 = isNaN(s01) ? 0 : s01; 3229 s12 = isNaN(s12) ? 0 : s12; 3230 var fa = t * s01; // scaling factor for triangle Ta 3231 var fb = t * s12; 3232 return { 3233 previous: { 3234 x: current.x - fa * (next.x - previous.x), 3235 y: current.y - fa * (next.y - previous.y) 3236 }, 3237 next: { 3238 x: current.x + fb * (next.x - previous.x), 3239 y: current.y + fb * (next.y - previous.y) 3240 } 3241 }; 3242 } 3243 /** 3244 * Adjust tangents to ensure monotonic properties 3245 */ 3246 function monotoneAdjust(points, deltaK, mK) { 3247 var pointsLen = points.length; 3248 var alphaK, betaK, tauK, squaredMagnitude, pointCurrent; 3249 var pointAfter = getPoint(points, 0); 3250 for (var i = 0; i < pointsLen - 1; ++i) { 3251 pointCurrent = pointAfter; 3252 pointAfter = getPoint(points, i + 1); 3253 if (!pointCurrent || !pointAfter) { 3254 continue; 3255 } 3256 if (almostEquals(deltaK[i], 0, EPSILON)) { 3257 mK[i] = mK[i + 1] = 0; 3258 continue; 3259 } 3260 alphaK = mK[i] / deltaK[i]; 3261 betaK = mK[i + 1] / deltaK[i]; 3262 squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2); 3263 if (squaredMagnitude <= 9) { 3264 continue; 3265 } 3266 tauK = 3 / Math.sqrt(squaredMagnitude); 3267 mK[i] = alphaK * tauK * deltaK[i]; 3268 mK[i + 1] = betaK * tauK * deltaK[i]; 3269 } 3270 } 3271 function monotoneCompute(points, mK) { 3272 var indexAxis = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'x'; 3273 var valueAxis = getValueAxis(indexAxis); 3274 var pointsLen = points.length; 3275 var delta, pointBefore, pointCurrent; 3276 var pointAfter = getPoint(points, 0); 3277 for (var i = 0; i < pointsLen; ++i) { 3278 pointBefore = pointCurrent; 3279 pointCurrent = pointAfter; 3280 pointAfter = getPoint(points, i + 1); 3281 if (!pointCurrent) { 3282 continue; 3283 } 3284 var iPixel = pointCurrent[indexAxis]; 3285 var vPixel = pointCurrent[valueAxis]; 3286 if (pointBefore) { 3287 delta = (iPixel - pointBefore[indexAxis]) / 3; 3288 pointCurrent["cp1".concat(indexAxis)] = iPixel - delta; 3289 pointCurrent["cp1".concat(valueAxis)] = vPixel - delta * mK[i]; 3290 } 3291 if (pointAfter) { 3292 delta = (pointAfter[indexAxis] - iPixel) / 3; 3293 pointCurrent["cp2".concat(indexAxis)] = iPixel + delta; 3294 pointCurrent["cp2".concat(valueAxis)] = vPixel + delta * mK[i]; 3295 } 3296 } 3297 } 3298 /** 3299 * This function calculates Bézier control points in a similar way than |splineCurve|, 3300 * but preserves monotonicity of the provided data and ensures no local extremums are added 3301 * between the dataset discrete points due to the interpolation. 3302 * See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation 3303 */ 3304 function splineCurveMonotone(points) { 3305 var indexAxis = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'x'; 3306 var valueAxis = getValueAxis(indexAxis); 3307 var pointsLen = points.length; 3308 var deltaK = Array(pointsLen).fill(0); 3309 var mK = Array(pointsLen); 3310 // Calculate slopes (deltaK) and initialize tangents (mK) 3311 var i, pointBefore, pointCurrent; 3312 var pointAfter = getPoint(points, 0); 3313 for (i = 0; i < pointsLen; ++i) { 3314 pointBefore = pointCurrent; 3315 pointCurrent = pointAfter; 3316 pointAfter = getPoint(points, i + 1); 3317 if (!pointCurrent) { 3318 continue; 3319 } 3320 if (pointAfter) { 3321 var slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis]; 3322 // In the case of two points that appear at the same x pixel, slopeDeltaX is 0 3323 deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0; 3324 } 3325 mK[i] = !pointBefore ? deltaK[i] : !pointAfter ? deltaK[i - 1] : sign(deltaK[i - 1]) !== sign(deltaK[i]) ? 0 : (deltaK[i - 1] + deltaK[i]) / 2; 3326 } 3327 monotoneAdjust(points, deltaK, mK); 3328 monotoneCompute(points, mK, indexAxis); 3329 } 3330 function capControlPoint(pt, min, max) { 3331 return Math.max(Math.min(pt, max), min); 3332 } 3333 function capBezierPoints(points, area) { 3334 var i, ilen, point, inArea, inAreaPrev; 3335 var inAreaNext = _isPointInArea(points[0], area); 3336 for (i = 0, ilen = points.length; i < ilen; ++i) { 3337 inAreaPrev = inArea; 3338 inArea = inAreaNext; 3339 inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area); 3340 if (!inArea) { 3341 continue; 3342 } 3343 point = points[i]; 3344 if (inAreaPrev) { 3345 point.cp1x = capControlPoint(point.cp1x, area.left, area.right); 3346 point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom); 3347 } 3348 if (inAreaNext) { 3349 point.cp2x = capControlPoint(point.cp2x, area.left, area.right); 3350 point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom); 3351 } 3352 } 3353 } 3354 /** 3355 * @private 3356 */ 3357 function _updateBezierControlPoints(points, options, area, loop, indexAxis) { 3358 var i, ilen, point, controlPoints; 3359 // Only consider points that are drawn in case the spanGaps option is used 3360 if (options.spanGaps) { 3361 points = points.filter(function (pt) { 3362 return !pt.skip; 3363 }); 3364 } 3365 if (options.cubicInterpolationMode === 'monotone') { 3366 splineCurveMonotone(points, indexAxis); 3367 } else { 3368 var prev = loop ? points[points.length - 1] : points[0]; 3369 for (i = 0, ilen = points.length; i < ilen; ++i) { 3370 point = points[i]; 3371 controlPoints = splineCurve(prev, point, points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen], options.tension); 3372 point.cp1x = controlPoints.previous.x; 3373 point.cp1y = controlPoints.previous.y; 3374 point.cp2x = controlPoints.next.x; 3375 point.cp2y = controlPoints.next.y; 3376 prev = point; 3377 } 3378 } 3379 if (options.capBezierPoints) { 3380 capBezierPoints(points, area); 3381 } 3382 } 3383 3384 /** 3385 * @private 3386 */
3387 function _isDomSupported() { 3388 return typeof window !== 'undefined' && typeof document !== 'undefined'; 3389 } 3390 /** 3391 * @private 3392 */ 3393 function _getParentNode(domNode) { 3394 var parent = domNode.parentNode; 3395 if (parent && parent.toString() === '[object ShadowRoot]') { 3396 parent = parent.host; 3397 } 3398 return parent; 3399 } 3400 /** 3401 * convert max-width/max-height values that may be percentages into a number 3402 * @private 3403 */ 3404 function parseMaxStyle(styleValue, node, parentProperty) { 3405 var valueInPixels; 3406 if (typeof styleValue === 'string') { 3407 valueInPixels = parseInt(styleValue, 10); 3408 if (styleValue.indexOf('%') !== -1) { 3409 // percentage * size in dimension 3410 valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty]; 3411 } 3412 } else { 3413 valueInPixels = styleValue; 3414 } 3415 return valueInPixels; 3416 } 3417 var getComputedStyle = function getComputedStyle(element) { 3418 return element.ownerDocument.defaultView.getComputedStyle(element, null); 3419 }; 3420 function getStyle(el, property) { 3421 return getComputedStyle(el).getPropertyValue(property); 3422 } 3423 var positions = ['top', 'right', 'bottom', 'left']; 3424 function getPositionedStyle(styles, style, suffix) { 3425 var result = {}; 3426 suffix = suffix ? '-' + suffix : ''; 3427 for (var i = 0; i < 4; i++) { 3428 var pos = positions[i]; 3429 result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0; 3430 } 3431 result.width = result.left + result.right; 3432 result.height = result.top + result.bottom; 3433 return result; 3434 } 3435 var useOffsetPos = function useOffsetPos(x, y, target) { 3436 return (x > 0 || y > 0) && (!target || !target.shadowRoot); 3437 }; 3438 /** 3439 * @param e 3440 * @param canvas 3441 * @returns Canvas position 3442 */ 3443 function getCanvasPosition(e, canvas) { 3444 var touches = e.touches; 3445 var source = touches && touches.length ? touches[0] : e; 3446 var offsetX = source.offsetX, 3447 offsetY = source.offsetY; 3448 var box = false; 3449 var x, y; 3450 if (useOffsetPos(offsetX, offsetY, e.target)) { 3451 x = offsetX; 3452 y = offsetY; 3453 } else { 3454 var rect = canvas.getBoundingClientRect(); 3455 x = source.clientX - rect.left; 3456 y = source.clientY - rect.top; 3457 box = true; 3458 } 3459 return { 3460 x: x, 3461 y: y, 3462 box: box 3463 }; 3464 } 3465 /** 3466 * Gets an event's x, y coordinates, relative to the chart area 3467 * @param event 3468 * @param chart 3469 * @returns x and y coordinates of the event 3470 */ 3471 function getRelativePosition(event, chart) { 3472 if ('native' in event) { 3473 return event; 3474 } 3475 var canvas = chart.canvas, 3476 currentDevicePixelRatio = chart.currentDevicePixelRatio; 3477 var style = getComputedStyle(canvas); 3478 var borderBox = style.boxSizing === 'border-box'; 3479 var paddings = getPositionedStyle(style, 'padding'); 3480 var borders = getPositionedStyle(style, 'border', 'width'); 3481 var _getCanvasPosition = getCanvasPosition(event, canvas), 3482 x = _getCanvasPosition.x, 3483 y = _getCanvasPosition.y, 3484 box = _getCanvasPosition.box; 3485 var xOffset = paddings.left + (box && borders.left); 3486 var yOffset = paddings.top + (box && borders.top); 3487 var width = chart.width, 3488 height = chart.height; 3489 if (borderBox) { 3490 width -= paddings.width + borders.width; 3491 height -= paddings.height + borders.height; 3492 } 3493 return { 3494 x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio), 3495 y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio) 3496 }; 3497 } 3498 function getContainerSize(canvas, width, height) { 3499 var maxWidth, maxHeight; 3500 if (width === undefined || height === undefined) { 3501 var container = canvas && _getParentNode(canvas); 3502 if (!container) { 3503 width = canvas.clientWidth; 3504 height = canvas.clientHeight; 3505 } else { 3506 var rect = container.getBoundingClientRect(); // this is the border box of the container 3507 var containerStyle = getComputedStyle(container); 3508 var containerBorder = getPositionedStyle(containerStyle, 'border', 'width'); 3509 var containerPadding = getPositionedStyle(containerStyle, 'padding'); 3510 width = rect.width - containerPadding.width - containerBorder.width; 3511 height = rect.height - containerPadding.height - containerBorder.height; 3512 maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth'); 3513 maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight'); 3514 } 3515 } 3516 return { 3517 width: width, 3518 height: height, 3519 maxWidth: maxWidth || INFINITY, 3520 maxHeight: maxHeight || INFINITY 3521 }; 3522 } 3523 var round1 = function round1(v) { 3524 return Math.round(v * 10) / 10; 3525 }; 3526 // eslint-disable-next-line complexity 3527 function getMaximumSize(canvas, bbWidth, bbHeight, aspectRatio) { 3528 var style = getComputedStyle(canvas); 3529 var margins = getPositionedStyle(style, 'margin'); 3530 var maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY; 3531 var maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY; 3532 var containerSize = getContainerSize(canvas, bbWidth, bbHeight); 3533 var width = containerSize.width, 3534 height = containerSize.height; 3535 if (style.boxSizing === 'content-box') { 3536 var borders = getPositionedStyle(style, 'border', 'width'); 3537 var paddings = getPositionedStyle(style, 'padding'); 3538 width -= paddings.width + borders.width; 3539 height -= paddings.height + borders.height; 3540 } 3541 width = Math.max(0, width - margins.width); 3542 height = Math.max(0, aspectRatio ? width / aspectRatio : height - margins.height); 3543 width = round1(Math.min(width, maxWidth, containerSize.maxWidth)); 3544 height = round1(Math.min(height, maxHeight, containerSize.maxHeight)); 3545 if (width && !height) { 3546 // https://github.com/chartjs/Chart.js/issues/4659 3547 // If the canvas has width, but no height, default to aspectRatio of 2 (canvas default) 3548 height = round1(width / 2); 3549 } 3550 var maintainHeight = bbWidth !== undefined || bbHeight !== undefined; 3551 if (maintainHeight && aspectRatio && containerSize.height && height > containerSize.height) { 3552 height = containerSize.height; 3553 width = round1(Math.floor(height * aspectRatio)); 3554 } 3555 return { 3556 width: width, 3557 height: height 3558 }; 3559 } 3560 /** 3561 * @param chart 3562 * @param forceRatio 3563 * @param forceStyle 3564 * @returns True if the canvas context size or transformation has changed. 3565 */ 3566 function retinaScale(chart, forceRatio, forceStyle) { 3567 var pixelRatio = forceRatio || 1; 3568 var deviceHeight = round1(chart.height * pixelRatio); 3569 var deviceWidth = round1(chart.width * pixelRatio); 3570 chart.height = round1(chart.height); 3571 chart.width = round1(chart.width); 3572 var canvas = chart.canvas; 3573 // If no style has been set on the canvas, the render size is used as display size, 3574 // making the chart visually bigger, so let's enforce it to the "correct" values. 3575 // See https://github.com/chartjs/Chart.js/issues/3575 3576 if (canvas.style && (forceStyle || !canvas.style.height && !canvas.style.width)) { 3577 canvas.style.height = "".concat(chart.height, "px"); 3578 canvas.style.width = "".concat(chart.width, "px"); 3579 } 3580 if (chart.currentDevicePixelRatio !== pixelRatio || canvas.height !== deviceHeight || canvas.width !== deviceWidth) { 3581 chart.currentDevicePixelRatio = pixelRatio; 3582 canvas.height = deviceHeight; 3583 canvas.width = deviceWidth; 3584 chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); 3585 return true; 3586 } 3587 return false;
3588 } 3589 /** 3590 * Detects support for options object argument in addEventListener. 3591 * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support 3592 * @private 3593 */ 3594 var supportsEventListenerOptions = function () { 3595 var passiveSupported = false; 3596 try { 3597 var options = { 3598 get passive() { 3599 passiveSupported = true; 3600 return false; 3601 } 3602 }; 3603 if (_isDomSupported()) { 3604 window.addEventListener('test', null, options); 3605 window.removeEventListener('test', null, options); 3606 } 3607 } catch (e) { 3608 // continue regardless of error 3609 } 3610 return passiveSupported; 3611 }(); 3612 /** 3613 * The "used" size is the final value of a dimension property after all calculations have 3614 * been performed. This method uses the computed style of `element` but returns undefined 3615 * if the computed style is not expressed in pixels. That can happen in some cases where 3616 * `element` has a size relative to its parent and this last one is not yet displayed, 3617 * for example because of `display: none` on a parent node. 3618 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value 3619 * @returns Size in pixels or undefined if unknown. 3620 */ 3621 function readUsedSize(element, property) { 3622 var value = getStyle(element, property); 3623 var matches = value && value.match(/^(\d+)(\.\d+)?px$/); 3624 return matches ? +matches[1] : undefined; 3625 } 3626 3627 /** 3628 * @private 3629 */ 3630 function _pointInLine(p1, p2, t, mode) { 3631 return { 3632 x: p1.x + t * (p2.x - p1.x), 3633 y: p1.y + t * (p2.y - p1.y) 3634 }; 3635 } 3636 /** 3637 * @private 3638 */ 3639 function _steppedInterpolation(p1, p2, t, mode) { 3640 return { 3641 x: p1.x + t * (p2.x - p1.x), 3642 y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y : mode === 'after' ? t < 1 ? p1.y : p2.y : t > 0 ? p2.y : p1.y 3643 }; 3644 } 3645 /** 3646 * @private 3647 */ 3648 function _bezierInterpolation(p1, p2, t, mode) { 3649 var cp1 = { 3650 x: p1.cp2x, 3651 y: p1.cp2y 3652 }; 3653 var cp2 = { 3654 x: p2.cp1x, 3655 y: p2.cp1y 3656 }; 3657 var a = _pointInLine(p1, cp1, t); 3658 var b = _pointInLine(cp1, cp2, t); 3659 var c = _pointInLine(cp2, p2, t); 3660 var d = _pointInLine(a, b, t); 3661 var e = _pointInLine(b, c, t); 3662 return _pointInLine(d, e, t); 3663 } 3664 var getRightToLeftAdapter = function getRightToLeftAdapter(rectX, width) { 3665 return { 3666 x: function x(_x) { 3667 return rectX + rectX + width - _x; 3668 }, 3669 setWidth: function setWidth(w) { 3670 width = w; 3671 }, 3672 textAlign: function textAlign(align) { 3673 if (align === 'center') { 3674 return align; 3675 } 3676 return align === 'right' ? 'left' : 'right'; 3677 }, 3678 xPlus: function xPlus(x, value) { 3679 return x - value; 3680 }, 3681 leftForLtr: function leftForLtr(x, itemWidth) { 3682 return x - itemWidth; 3683 } 3684 }; 3685 }; 3686 var getLeftToRightAdapter = function getLeftToRightAdapter() { 3687 return { 3688 x: function x(_x2) { 3689 return _x2; 3690 }, 3691 setWidth: function setWidth(w) {}, 3692 textAlign: function textAlign(align) { 3693 return align; 3694 }, 3695 xPlus: function xPlus(x, value) { 3696 return x + value; 3697 }, 3698 leftForLtr: function leftForLtr(x, _itemWidth) { 3699 return x; 3700 } 3701 }; 3702 }; 3703 function getRtlAdapter(rtl, rectX, width) { 3704 return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter(); 3705 } 3706 function overrideTextDirection(ctx, direction) { 3707 var style, original; 3708 if (direction === 'ltr' || direction === 'rtl') { 3709 style = ctx.canvas.style; 3710 original = [style.getPropertyValue('direction'), style.getPropertyPriority('direction')]; 3711 style.setProperty('direction', direction, 'important'); 3712 ctx.prevTextDirection = original; 3713 } 3714 } 3715 function restoreTextDirection(ctx, original) { 3716 if (original !== undefined) { 3717 delete ctx.prevTextDirection; 3718 ctx.canvas.style.setProperty('direction', original[0], original[1]); 3719 } 3720 } 3721 function propertyFn(property) { 3722 if (property === 'angle') { 3723 return { 3724 between: _angleBetween, 3725 compare: _angleDiff, 3726 normalize: _normalizeAngle 3727 }; 3728 } 3729 return { 3730 between: _isBetween, 3731 compare: function compare(a, b) { 3732 return a - b; 3733 }, 3734 normalize: function normalize(x) { 3735 return x; 3736 } 3737 }; 3738 } 3739 function normalizeSegment(_ref) { 3740 var start = _ref.start, 3741 end = _ref.end, 3742 count = _ref.count, 3743 loop = _ref.loop, 3744 style = _ref.style; 3745 return { 3746 start: start % count, 3747 end: end % count, 3748 loop: loop && (end - start + 1) % count === 0, 3749 style: style 3750 }; 3751 } 3752 function getSegment(segment, points, bounds) { 3753 var property = bounds.property, 3754 startBound = bounds.start, 3755 endBound = bounds.end; 3756 var _propertyFn = propertyFn(property), 3757 between = _propertyFn.between, 3758 normalize = _propertyFn.normalize; 3759 var count = points.length; 3760 var start = segment.start, 3761 end = segment.end, 3762 loop = segment.loop; 3763 var i, ilen; 3764 if (loop) { 3765 start += count; 3766 end += count; 3767 for (i = 0, ilen = count; i < ilen; ++i) { 3768 if (!between(normalize(points[start % count][property]), startBound, endBound)) { 3769 break; 3770 } 3771 start--; 3772 end--; 3773 } 3774 start %= count; 3775 end %= count; 3776 } 3777 if (end < start) { 3778 end += count; 3779 } 3780 return { 3781 start: start, 3782 end: end, 3783 loop: loop, 3784 style: segment.style 3785 }; 3786 } 3787 function _boundSegment(segment, points, bounds) { 3788 if (!bounds) { 3789 return [segment]; 3790 } 3791 var property = bounds.property, 3792 startBound = bounds.start, 3793 endBound = bounds.end; 3794 var count = points.length; 3795 var _propertyFn2 = propertyFn(property), 3796 compare = _propertyFn2.compare, 3797 between = _propertyFn2.between, 3798 normalize = _propertyFn2.normalize; 3799 var _getSegment = getSegment(segment, points, bounds), 3800 start = _getSegment.start, 3801 end = _getSegment.end, 3802 loop = _getSegment.loop,
3803 style = _getSegment.style; 3804 var result = []; 3805 var inside = false; 3806 var subStart = null; 3807 var value, point, prevValue; 3808 var startIsBefore = function startIsBefore() { 3809 return between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0; 3810 }; 3811 var endIsBefore = function endIsBefore() { 3812 return compare(endBound, value) === 0 || between(endBound, prevValue, value); 3813 }; 3814 var shouldStart = function shouldStart() { 3815 return inside || startIsBefore(); 3816 }; 3817 var shouldStop = function shouldStop() { 3818 return !inside || endIsBefore(); 3819 }; 3820 for (var i = start, prev = start; i <= end; ++i) { 3821 point = points[i % count]; 3822 if (point.skip) { 3823 continue; 3824 } 3825 value = normalize(point[property]); 3826 if (value === prevValue) { 3827 continue; 3828 } 3829 inside = between(value, startBound, endBound); 3830 if (subStart === null && shouldStart()) { 3831 subStart = compare(value, startBound) === 0 ? i : prev; 3832 } 3833 if (subStart !== null && shouldStop()) { 3834 result.push(normalizeSegment({ 3835 start: subStart, 3836 end: i, 3837 loop: loop, 3838 count: count, 3839 style: style 3840 })); 3841 subStart = null; 3842 } 3843 prev = i; 3844 prevValue = value; 3845 } 3846 if (subStart !== null) { 3847 result.push(normalizeSegment({ 3848 start: subStart, 3849 end: end, 3850 loop: loop, 3851 count: count, 3852 style: style 3853 })); 3854 } 3855 return result; 3856 } 3857 function _boundSegments(line, bounds) { 3858 var result = []; 3859 var segments = line.segments; 3860 for (var i = 0; i < segments.length; i++) { 3861 var sub = _boundSegment(segments[i], line.points, bounds); 3862 if (sub.length) { 3863 result.push.apply(result, _toConsumableArray(sub)); 3864 } 3865 } 3866 return result; 3867 } 3868 function findStartAndEnd(points, count, loop, spanGaps) { 3869 var start = 0; 3870 var end = count - 1; 3871 if (loop && !spanGaps) { 3872 while (start < count && !points[start].skip) { 3873 start++; 3874 } 3875 } 3876 while (start < count && points[start].skip) { 3877 start++; 3878 } 3879 start %= count; 3880 if (loop) { 3881 end += start; 3882 } 3883 while (end > start && points[end % count].skip) { 3884 end--; 3885 } 3886 end %= count; 3887 return { 3888 start: start, 3889 end: end 3890 }; 3891 } 3892 function solidSegments(points, start, max, loop) { 3893 var count = points.length; 3894 var result = []; 3895 var last = start; 3896 var prev = points[start]; 3897 var end; 3898 for (end = start + 1; end <= max; ++end) { 3899 var cur = points[end % count]; 3900 if (cur.skip || cur.stop) { 3901 if (!prev.skip) { 3902 loop = false; 3903 result.push({ 3904 start: start % count, 3905 end: (end - 1) % count, 3906 loop: loop 3907 }); 3908 start = last = cur.stop ? end : null; 3909 } 3910 } else { 3911 last = end; 3912 if (prev.skip) { 3913 start = end; 3914 } 3915 } 3916 prev = cur; 3917 } 3918 if (last !== null) { 3919 result.push({ 3920 start: start % count, 3921 end: last % count, 3922 loop: loop 3923 }); 3924 } 3925 return result; 3926 } 3927 function _computeSegments(line, segmentOptions) { 3928 var points = line.points; 3929 var spanGaps = line.options.spanGaps; 3930 var count = points.length; 3931 if (!count) { 3932 return []; 3933 } 3934 var loop = !!line._loop; 3935 var _findStartAndEnd = findStartAndEnd(points, count, loop, spanGaps), 3936 start = _findStartAndEnd.start, 3937 end = _findStartAndEnd.end; 3938 if (spanGaps === true) { 3939 return splitByStyles(line, [{ 3940 start: start, 3941 end: end, 3942 loop: loop 3943 }], points, segmentOptions); 3944 } 3945 var max = end < start ? end + count : end; 3946 var completeLoop = !!line._fullLoop && start === 0 && end === count - 1; 3947 return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions); 3948 } 3949 function splitByStyles(line, segments, points, segmentOptions) { 3950 if (!segmentOptions || !segmentOptions.setContext || !points) { 3951 return segments; 3952 } 3953 return doSplitByStyles(line, segments, points, segmentOptions); 3954 } 3955 function doSplitByStyles(line, segments, points, segmentOptions) { 3956 var chartContext = line._chart.getContext(); 3957 var baseStyle = readStyle(line.options); 3958 var datasetIndex = line._datasetIndex, 3959 spanGaps = line.options.spanGaps; 3960 var count = points.length; 3961 var result = []; 3962 var prevStyle = baseStyle; 3963 var start = segments[0].start; 3964 var i = start; 3965 function addStyle(s, e, l, st) { 3966 var dir = spanGaps ? -1 : 1; 3967 if (s === e) { 3968 return; 3969 } 3970 s += count; 3971 while (points[s % count].skip) { 3972 s -= dir; 3973 } 3974 while (points[e % count].skip) { 3975 e += dir; 3976 } 3977 if (s % count !== e % count) { 3978 result.push({ 3979 start: s % count, 3980 end: e % count, 3981 loop: l, 3982 style: st 3983 }); 3984 prevStyle = st; 3985 start = e % count; 3986 } 3987 } 3988 var _iterator1 = _createForOfIteratorHelper$1(segments), 3989 _step1; 3990 try { 3991 for (_iterator1.s();
3991 !(_step1 = _iterator1.n()).done;) { 3992 var segment = _step1.value; 3993 start = spanGaps ? start : segment.start; 3994 var prev = points[start % count]; 3995 var style = void 0; 3996 for (i = start + 1; i <= segment.end; i++) { 3997 var pt = points[i % count]; 3998 style = readStyle(segmentOptions.setContext(createContext(chartContext, { 3999 type: 'segment', 4000 p0: prev, 4001 p1: pt, 4002 p0DataIndex: (i - 1) % count, 4003 p1DataIndex: i % count, 4004 datasetIndex: datasetIndex 4005 }))); 4006 if (styleChanged(style, prevStyle)) { 4007 addStyle(start, i - 1, segment.loop, prevStyle); 4008 } 4009 prev = pt; 4010 prevStyle = style; 4011 } 4012 if (start < i - 1) { 4013 addStyle(start, i - 1, segment.loop, prevStyle); 4014 } 4015 } 4016 } catch (err) { 4017 _iterator1.e(err); 4018 } finally { 4019 _iterator1.f(); 4020 } 4021 return result; 4022 } 4023 function readStyle(options) { 4024 return { 4025 backgroundColor: options.backgroundColor, 4026 borderCapStyle: options.borderCapStyle, 4027 borderDash: options.borderDash, 4028 borderDashOffset: options.borderDashOffset, 4029 borderJoinStyle: options.borderJoinStyle, 4030 borderWidth: options.borderWidth, 4031 borderColor: options.borderColor 4032 }; 4033 } 4034 function styleChanged(style, prevStyle) { 4035 if (!prevStyle) { 4036 return false; 4037 } 4038 var cache = []; 4039 var replacer = function replacer(key, value) { 4040 if (!isPatternOrGradient(value)) { 4041 return value; 4042 } 4043 if (!cache.includes(value)) { 4044 cache.push(value); 4045 } 4046 return cache.indexOf(value); 4047 }; 4048 return JSON.stringify(style, replacer) !== JSON.stringify(prevStyle, replacer); 4049 } 4050 function getSizeForArea(scale, chartArea, field) { 4051 return scale.options.clip ? scale[field] : chartArea[field]; 4052 } 4053 function getDatasetArea(meta, chartArea) { 4054 var xScale = meta.xScale, 4055 yScale = meta.yScale; 4056 if (xScale && yScale) { 4057 return { 4058 left: getSizeForArea(xScale, chartArea, 'left'), 4059 right: getSizeForArea(xScale, chartArea, 'right'), 4060 top: getSizeForArea(yScale, chartArea, 'top'), 4061 bottom: getSizeForArea(yScale, chartArea, 'bottom') 4062 }; 4063 } 4064 return chartArea; 4065 } 4066 function getDatasetClipArea(chart, meta) { 4067 var clip = meta._clip; 4068 if (clip.disabled) { 4069 return false; 4070 } 4071 var area = getDatasetArea(meta, chart.chartArea); 4072 return { 4073 left: clip.left === false ? 0 : area.left - (clip.left === true ? 0 : clip.left), 4074 right: clip.right === false ? chart.width : area.right + (clip.right === true ? 0 : clip.right), 4075 top: clip.top === false ? 0 : area.top - (clip.top === true ? 0 : clip.top), 4076 bottom: clip.bottom === false ? chart.height : area.bottom + (clip.bottom === true ? 0 : clip.bottom) 4077 }; 4078 } 4079 4080 var Animator = /*#__PURE__*/function () { 4081 function Animator() { 4082 _classCallCheck$1(this, Animator); 4083 this._request = null; 4084 this._charts = new Map(); 4085 this._running = false; 4086 this._lastDate = undefined; 4087 } 4088 return _createClass$1(Animator, [{ 4089 key: "_notify", 4090 value: function _notify(chart, anims, date, type) { 4091 var callbacks = anims.listeners[type]; 4092 var numSteps = anims.duration; 4093 callbacks.forEach(function (fn) { 4094 return fn({ 4095 chart: chart, 4096 initial: anims.initial, 4097 numSteps: numSteps, 4098 currentStep: Math.min(date - anims.start, numSteps) 4099 }); 4100 }); 4101 } 4102 }, { 4103 key: "_refresh", 4104 value: function _refresh() { 4105 var _this = this; 4106 if (this._request) { 4107 return; 4108 } 4109 this._running = true; 4110 this._request = requestAnimFrame.call(window, function () { 4111 _this._update(); 4112 _this._request = null; 4113 if (_this._running) { 4114 _this._refresh(); 4115 } 4116 }); 4117 } 4118 }, { 4119 key: "_update", 4120 value: function _update() { 4121 var _this2 = this; 4122 var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Date.now(); 4123 var remaining = 0;
4124 this._charts.forEach(function (anims, chart) { 4125 if (!anims.running || !anims.items.length) { 4126 return; 4127 } 4128 var items = anims.items; 4129 var i = items.length - 1; 4130 var draw = false; 4131 var item; 4132 for (; i >= 0; --i) { 4133 item = items[i]; 4134 if (item._active) { 4135 if (item._total > anims.duration) { 4136 anims.duration = item._total; 4137 } 4138 item.tick(date); 4139 draw = true; 4140 } else { 4141 items[i] = items[items.length - 1]; 4142 items.pop(); 4143 } 4144 } 4145 if (draw) { 4146 chart.draw(); 4147 _this2._notify(chart, anims, date, 'progress'); 4148 } 4149 if (!items.length) { 4150 anims.running = false; 4151 _this2._notify(chart, anims, date, 'complete'); 4152 anims.initial = false; 4153 } 4154 remaining += items.length; 4155 }); 4156 this._lastDate = date; 4157 if (remaining === 0) { 4158 this._running = false; 4159 } 4160 } 4161 }, { 4162 key: "_getAnims", 4163 value: function _getAnims(chart) { 4164 var charts = this._charts; 4165 var anims = charts.get(chart); 4166 if (!anims) { 4167 anims = { 4168 running: false, 4169 initial: true, 4170 items: [], 4171 listeners: { 4172 complete: [], 4173 progress: [] 4174 } 4175 }; 4176 charts.set(chart, anims); 4177 } 4178 return anims; 4179 } 4180 }, { 4181 key: "listen", 4182 value: function listen(chart, event, cb) { 4183 this._getAnims(chart).listeners[event].push(cb); 4184 } 4185 }, { 4186 key: "add", 4187 value: function add(chart, items) { 4188 var _this$_getAnims$items; 4189 if (!items || !items.length) { 4190 return; 4191 } 4192 (_this$_getAnims$items = this._getAnims(chart).items).push.apply(_this$_getAnims$items, _toConsumableArray(items)); 4193 } 4194 }, { 4195 key: "has", 4196 value: function has(chart) { 4197 return this._getAnims(chart).items.length > 0; 4198 } 4199 }, { 4200 key: "start", 4201 value: function start(chart) { 4202 var anims = this._charts.get(chart); 4203 if (!anims) { 4204 return; 4205 } 4206 anims.running = true; 4207 anims.start = Date.now(); 4208 anims.duration = anims.items.reduce(function (acc, cur) { 4209 return Math.max(acc, cur._duration); 4210 }, 0); 4211 this._refresh(); 4212 } 4213 }, { 4214 key: "running", 4215 value: function running(chart) { 4216 if (!this._running) { 4217 return false; 4218 } 4219 var anims = this._charts.get(chart); 4220 if (!anims || !anims.running || !anims.items.length) { 4221 return false; 4222 } 4223 return true; 4224 } 4225 }, { 4226 key: "stop", 4227 value: function stop(chart) { 4228 var anims = this._charts.get(chart); 4229 if (!anims || !anims.items.length) { 4230 return; 4231 } 4232 var items = anims.items; 4233 var i = items.length - 1; 4234 for (; i >= 0; --i) { 4235 items[i].cancel(); 4236 } 4237 anims.items = []; 4238 this._notify(chart, anims, Date.now(), 'complete'); 4239 } 4240 }, { 4241 key: "remove", 4242 value: function remove(chart) { 4243 return this._charts["delete"](chart); 4244 } 4245 }]); 4246 }(); 4247 var animator = /* #__PURE__ */new Animator(); 4248 var transparent = 'transparent'; 4249 var interpolators = { 4250 "boolean": function boolean(from, to, factor) { 4251 return factor > 0.5 ? to : from; 4252 }, 4253 color: function color$1(from, to, factor) { 4254 var c0 = color(from || transparent); 4255 var c1 = c0.valid && color(to || transparent); 4256 return c1 && c1.valid ? c1.mix(c0, factor).hexString() : to; 4257 }, 4258 number: function number(from, to, factor) { 4259 return from + (to - from) * factor; 4260 } 4261 }; 4262 var Animation = /*#__PURE__*/function () { 4263 function Animation(cfg, target, prop, to) { 4264 _classCallCheck$1(this, Animation); 4265 var currentValue = target[prop]; 4266 to = resolve([cfg.to, to, currentValue, cfg.from]);
4267 var from = resolve([cfg.from, currentValue, to]); 4268 this._active = true; 4269 this._fn = cfg.fn || interpolators[cfg.type || _typeof$1(from)]; 4270 this._easing = effects[cfg.easing] || effects.linear; 4271 this._start = Math.floor(Date.now() + (cfg.delay || 0)); 4272 this._duration = this._total = Math.floor(cfg.duration); 4273 this._loop = !!cfg.loop; 4274 this._target = target; 4275 this._prop = prop; 4276 this._from = from; 4277 this._to = to; 4278 this._promises = undefined; 4279 } 4280 return _createClass$1(Animation, [{ 4281 key: "active", 4282 value: function active() { 4283 return this._active; 4284 } 4285 }, { 4286 key: "update", 4287 value: function update(cfg, to, date) { 4288 if (this._active) { 4289 this._notify(false); 4290 var currentValue = this._target[this._prop]; 4291 var elapsed = date - this._start; 4292 var remain = this._duration - elapsed; 4293 this._start = date; 4294 this._duration = Math.floor(Math.max(remain, cfg.duration)); 4295 this._total += elapsed; 4296 this._loop = !!cfg.loop; 4297 this._to = resolve([cfg.to, to, currentValue, cfg.from]); 4298 this._from = resolve([cfg.from, currentValue, to]); 4299 } 4300 } 4301 }, { 4302 key: "cancel", 4303 value: function cancel() { 4304 if (this._active) { 4305 this.tick(Date.now()); 4306 this._active = false; 4307 this._notify(false); 4308 } 4309 } 4310 }, { 4311 key: "tick", 4312 value: function tick(date) { 4313 var elapsed = date - this._start; 4314 var duration = this._duration; 4315 var prop = this._prop; 4316 var from = this._from; 4317 var loop = this._loop; 4318 var to = this._to; 4319 var factor; 4320 this._active = from !== to && (loop || elapsed < duration); 4321 if (!this._active) { 4322 this._target[prop] = to; 4323 this._notify(true); 4324 return; 4325 } 4326 if (elapsed < 0) { 4327 this._target[prop] = from; 4328 return; 4329 } 4330 factor = elapsed / duration % 2; 4331 factor = loop && factor > 1 ? 2 - factor : factor; 4332 factor = this._easing(Math.min(1, Math.max(0, factor))); 4333 this._target[prop] = this._fn(from, to, factor); 4334 } 4335 }, { 4336 key: "wait", 4337 value: function wait() { 4338 var promises = this._promises || (this._promises = []); 4339 return new Promise(function (res, rej) { 4340 promises.push({ 4341 res: res, 4342 rej: rej 4343 }); 4344 }); 4345 } 4346 }, { 4347 key: "_notify", 4348 value: function _notify(resolved) { 4349 var method = resolved ? 'res' : 'rej'; 4350 var promises = this._promises || []; 4351 for (var i = 0; i < promises.length; i++) { 4352 promises[i][method](); 4353 } 4354 } 4355 }]); 4356 }(); 4357 var Animations = /*#__PURE__*/function () { 4358 function Animations(chart, config) { 4359 _classCallCheck$1(this, Animations); 4360 this._chart = chart; 4361 this._properties = new Map(); 4362 this.configure(config); 4363 } 4364 return _createClass$1(Animations, [{ 4365 key: "configure", 4366 value: function configure(config) { 4367 if (!isObject(config)) { 4368 return; 4369 } 4370 var animationOptions = Object.keys(defaults.animation); 4371 var animatedProps = this._properties; 4372 Object.getOwnPropertyNames(config).forEach(function (key) { 4373 var cfg = config[key]; 4374 if (!isObject(cfg)) { 4375 return; 4376 } 4377 var resolved = {}; 4378 for (var _i = 0, _animationOptions = animationOptions; _i < _animationOptions.length; _i++) { 4379 var option = _animationOptions[_i]; 4380 resolved[option] = cfg[option]; 4381 } 4382 (isArray(cfg.properties) && cfg.properties || [key]).forEach(function (prop) { 4383 if (prop === key || !animatedProps.has(prop)) { 4384 animatedProps.set(prop, resolved); 4385 } 4386 }); 4387 }); 4388 } 4389 }, { 4390 key: "_animateOptions", 4391 value: function _animateOptions(target, values) { 4392 var newOptions = values.options; 4393 var options = resolveTargetOptions(target, newOptions); 4394 if (!options) { 4395 return []; 4396 } 4397 var animations = this._createAnimations(options, newOptions); 4398 if (newOptions.$shared) { 4399 awaitAll(target.options.$animations, newOptions).then(function () { 4400 target.options = newOptions; 4401 }, function () {}); 4402 } 4403 return animations; 4404 } 4405 }, {
4406 key: "_createAnimations", 4407 value: function _createAnimations(target, values) { 4408 var animatedProps = this._properties; 4409 var animations = []; 4410 var running = target.$animations || (target.$animations = {}); 4411 var props = Object.keys(values); 4412 var date = Date.now(); 4413 var i; 4414 for (i = props.length - 1; i >= 0; --i) { 4415 var prop = props[i]; 4416 if (prop.charAt(0) === '$') { 4417 continue; 4418 } 4419 if (prop === 'options') { 4420 animations.push.apply(animations, _toConsumableArray(this._animateOptions(target, values))); 4421 continue; 4422 } 4423 var value = values[prop]; 4424 var animation = running[prop]; 4425 var cfg = animatedProps.get(prop); 4426 if (animation) { 4427 if (cfg && animation.active()) { 4428 animation.update(cfg, value, date); 4429 continue; 4430 } else { 4431 animation.cancel(); 4432 } 4433 } 4434 if (!cfg || !cfg.duration) { 4435 target[prop] = value; 4436 continue; 4437 } 4438 running[prop] = animation = new Animation(cfg, target, prop, value); 4439 animations.push(animation); 4440 } 4441 return animations; 4442 } 4443 }, { 4444 key: "update", 4445 value: function update(target, values) { 4446 if (this._properties.size === 0) { 4447 Object.assign(target, values); 4448 return; 4449 } 4450 var animations = this._createAnimations(target, values); 4451 if (animations.length) { 4452 animator.add(this._chart, animations); 4453 return true; 4454 } 4455 } 4456 }]); 4457 }(); 4458 function awaitAll(animations, properties) { 4459 var running = []; 4460 var keys = Object.keys(properties); 4461 for (var i = 0; i < keys.length; i++) { 4462 var anim = animations[keys[i]]; 4463 if (anim && anim.active()) { 4464 running.push(anim.wait()); 4465 } 4466 } 4467 return Promise.all(running); 4468 } 4469 function resolveTargetOptions(target, newOptions) { 4470 if (!newOptions) { 4471 return; 4472 } 4473 var options = target.options; 4474 if (!options) { 4475 target.options = newOptions; 4476 return; 4477 } 4478 if (options.$shared) { 4479 target.options = options = Object.assign({}, options, { 4480 $shared: false, 4481 $animations: {} 4482 }); 4483 } 4484 return options; 4485 } 4486 function scaleClip(scale, allowedOverflow) { 4487 var opts = scale && scale.options || {}; 4488 var reverse = opts.reverse; 4489 var min = opts.min === undefined ? allowedOverflow : 0; 4490 var max = opts.max === undefined ? allowedOverflow : 0; 4491 return { 4492 start: reverse ? max : min, 4493 end: reverse ? min : max 4494 }; 4495 } 4496 function defaultClip(xScale, yScale, allowedOverflow) { 4497 if (allowedOverflow === false) { 4498 return false; 4499 } 4500 var x = scaleClip(xScale, allowedOverflow); 4501 var y = scaleClip(yScale, allowedOverflow); 4502 return { 4503 top: y.end, 4504 right: x.end, 4505 bottom: y.start, 4506 left: x.start 4507 }; 4508 } 4509 function toClip(value) { 4510 var t, r, b, l; 4511 if (isObject(value)) { 4512 t = value.top; 4513 r = value.right; 4514 b = value.bottom; 4515 l = value.left; 4516 } else { 4517 t = r = b = l = value; 4518 } 4519 return { 4520 top: t, 4521 right: r, 4522 bottom: b, 4523 left: l, 4524 disabled: value === false 4525 }; 4526 } 4527 function getSortedDatasetIndices(chart, filterVisible) { 4528 var keys = []; 4529 var metasets = chart._getSortedDatasetMetas(filterVisible); 4530 var i, ilen; 4531 for (i = 0, ilen = metasets.length; i < ilen; ++i) { 4532 keys.push(metasets[i].index); 4533 } 4534 return keys; 4535 } 4536 function _applyStack(stack, value, dsIndex) { 4537 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; 4538 var keys = stack.keys; 4539 var singleMode = options.mode === 'single'; 4540 var i, ilen, datasetIndex, otherValue; 4541 if (value === null) { 4542 return; 4543 } 4544 var found = false; 4545 for (i = 0, ilen = keys.length; i < ilen; ++i) { 4546 datasetIndex = +keys[i]; 4547 if (datasetIndex === dsIndex) { 4548 found = true; 4549 if (options.all) { 4550 continue; 4551 } 4552 break; 4553 } 4554 otherValue = stack.values[datasetIndex]; 4555 if (isNumberFinite(otherValue) && (singleMode || value === 0 || sign(value) === sign(otherValue))) { 4556 value += otherValue; 4557 } 4558 } 4559 if (!found && !options.all) { 4560 return 0; 4561 } 4562 return value; 4563 } 4564 function convertObjectDataToArray(data, meta) { 4565 var iScale = meta.iScale, 4566 vScale = meta.vScale; 4567 var iAxisKey = iScale.axis === 'x' ? 'x' : 'y'; 4568 var vAxisKey = vScale.axis === 'x' ? 'x' : 'y'; 4569 var keys = Object.keys(data); 4570 var adata = new Array(keys.length); 4571 var i, ilen, key; 4572 for (i = 0, ilen = keys.length; i < ilen; ++i) { 4573 key = keys[i]; 4574 adata[i] = _defineProperty$1(_defineProperty$1({}, iAxisKey, key), vAxisKey, data[key]); 4575 } 4576 return adata; 4577 } 4578 function isStacked(scale, meta) { 4579 var stacked = scale && scale.options.stacked; 4580 return stacked || stacked === undefined && meta.stack !== undefined; 4581 } 4582 function getStackKey(indexScale, valueScale, meta) { 4583 return "".concat(indexScale.id, ".").concat(valueScale.id, ".").concat(meta.stack || meta.type); 4584 } 4585 function getUserBounds(scale) { 4586 var _scale$getUserBounds = scale.getUserBounds(), 4587 min = _scale$getUserBounds.min,
4588 max = _scale$getUserBounds.max, 4589 minDefined = _scale$getUserBounds.minDefined, 4590 maxDefined = _scale$getUserBounds.maxDefined; 4591 return { 4592 min: minDefined ? min : Number.NEGATIVE_INFINITY, 4593 max: maxDefined ? max : Number.POSITIVE_INFINITY 4594 }; 4595 } 4596 function getOrCreateStack(stacks, stackKey, indexValue) { 4597 var subStack = stacks[stackKey] || (stacks[stackKey] = {}); 4598 return subStack[indexValue] || (subStack[indexValue] = {}); 4599 } 4600 function getLastIndexInStack(stack, vScale, positive, type) { 4601 var _iterator = _createForOfIteratorHelper$1(vScale.getMatchingVisibleMetas(type).reverse()), 4602 _step; 4603 try { 4604 for (_iterator.s(); !(_step = _iterator.n()).done;) { 4605 var meta = _step.value; 4606 var value = stack[meta.index]; 4607 if (positive && value > 0 || !positive && value < 0) { 4608 return meta.index; 4609 } 4610 } 4611 } catch (err) { 4612 _iterator.e(err); 4613 } finally { 4614 _iterator.f(); 4615 } 4616 return null; 4617 } 4618 function updateStacks(controller, parsed) { 4619 var chart = controller.chart, 4620 meta = controller._cachedMeta; 4621 var stacks = chart._stacks || (chart._stacks = {}); 4622 var iScale = meta.iScale, 4623 vScale = meta.vScale, 4624 datasetIndex = meta.index; 4625 var iAxis = iScale.axis; 4626 var vAxis = vScale.axis; 4627 var key = getStackKey(iScale, vScale, meta); 4628 var ilen = parsed.length; 4629 var stack; 4630 for (var i = 0; i < ilen; ++i) { 4631 var item = parsed[i]; 4632 var _index = item[iAxis], 4633 value = item[vAxis]; 4634 var itemStacks = item._stacks || (item._stacks = {}); 4635 stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, _index); 4636 stack[datasetIndex] = value; 4637 stack._top = getLastIndexInStack(stack, vScale, true, meta.type); 4638 stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type); 4639 var visualValues = stack._visualValues || (stack._visualValues = {}); 4640 visualValues[datasetIndex] = value; 4641 } 4642 } 4643 function getFirstScaleId(chart, axis) { 4644 var scales = chart.scales; 4645 return Object.keys(scales).filter(function (key) { 4646 return scales[key].axis === axis; 4647 }).shift(); 4648 } 4649 function createDatasetContext(parent, index) { 4650 return createContext(parent, { 4651 active: false, 4652 dataset: undefined, 4653 datasetIndex: index, 4654 index: index, 4655 mode: 'default', 4656 type: 'dataset' 4657 }); 4658 } 4659 function createDataContext(parent, index, element) { 4660 return createContext(parent, { 4661 active: false, 4662 dataIndex: index, 4663 parsed: undefined, 4664 raw: undefined, 4665 element: element, 4666 index: index, 4667 mode: 'default', 4668 type: 'data' 4669 }); 4670 } 4671 function clearStacks(meta, items) { 4672 var datasetIndex = meta.controller.index; 4673 var axis = meta.vScale && meta.vScale.axis; 4674 if (!axis) { 4675 return; 4676 } 4677 items = items || meta._parsed; 4678 var _iterator2 = _createForOfIteratorHelper$1(items), 4679 _step2; 4680 try { 4681 for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { 4682 var parsed = _step2.value; 4683 var stacks = parsed._stacks; 4684 if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) { 4685 return; 4686 } 4687 delete stacks[axis][datasetIndex]; 4688 if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) { 4689 delete stacks[axis]._visualValues[datasetIndex]; 4690 } 4691 } 4692 } catch (err) { 4693 _iterator2.e(err); 4694 } finally { 4695 _iterator2.f(); 4696 } 4697 } 4698 var isDirectUpdateMode = function isDirectUpdateMode(mode) { 4699 return mode === 'reset' || mode === 'none'; 4700 }; 4701 var cloneIfNotShared = function cloneIfNotShared(cached, shared) { 4702 return shared ? cached : Object.assign({}, cached); 4703 }; 4704 var createStack = function createStack(canStack, meta, chart) { 4705 return canStack && !meta.hidden && meta._stacked && { 4706 keys: getSortedDatasetIndices(chart, true), 4707 values: null 4708 }; 4709 }; 4710 var DatasetController = /*#__PURE__*/function () { 4711 function DatasetController(chart, datasetIndex) { 4712 _classCallCheck$1(this, DatasetController); 4713 this.chart = chart; 4714 this._ctx = chart.ctx; 4715 this.index = datasetIndex; 4716 this._cachedDataOpts = {}; 4717 this._cachedMeta = this.getMeta(); 4718 this._type = this._cachedMeta.type; 4719 this.options = undefined; 4720 this._parsing = false;
4721 this._data = undefined; 4722 this._objectData = undefined; 4723 this._sharedOptions = undefined; 4724 this._drawStart = undefined; 4725 this._drawCount = undefined; 4726 this.enableOptionSharing = false; 4727 this.supportsDecimation = false; 4728 this.$context = undefined; 4729 this._syncList = []; 4730 this.datasetElementType = (this instanceof DatasetController ? this.constructor : void 0).datasetElementType; 4731 this.dataElementType = (this instanceof DatasetController ? this.constructor : void 0).dataElementType; 4732 this.initialize(); 4733 } 4734 return _createClass$1(DatasetController, [{ 4735 key: "initialize", 4736 value: function initialize() { 4737 var meta = this._cachedMeta; 4738 this.configure(); 4739 this.linkScales(); 4740 meta._stacked = isStacked(meta.vScale, meta); 4741 this.addElements(); 4742 if (this.options.fill && !this.chart.isPluginEnabled('filler')) { 4743 console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options"); 4744 } 4745 } 4746 }, { 4747 key: "updateIndex", 4748 value: function updateIndex(datasetIndex) { 4749 if (this.index !== datasetIndex) { 4750 clearStacks(this._cachedMeta); 4751 } 4752 this.index = datasetIndex; 4753 } 4754 }, { 4755 key: "linkScales", 4756 value: function linkScales() { 4757 var chart = this.chart; 4758 var meta = this._cachedMeta; 4759 var dataset = this.getDataset(); 4760 var chooseId = function chooseId(axis, x, y, r) { 4761 return axis === 'x' ? x : axis === 'r' ? r : y; 4762 }; 4763 var xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x')); 4764 var yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y')); 4765 var rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r')); 4766 var indexAxis = meta.indexAxis; 4767 var iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid); 4768 var vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid); 4769 meta.xScale = this.getScaleForId(xid); 4770 meta.yScale = this.getScaleForId(yid); 4771 meta.rScale = this.getScaleForId(rid); 4772 meta.iScale = this.getScaleForId(iid); 4773 meta.vScale = this.getScaleForId(vid); 4774 } 4775 }, { 4776 key: "getDataset", 4777 value: function getDataset() { 4778 return this.chart.data.datasets[this.index]; 4779 } 4780 }, { 4781 key: "getMeta", 4782 value: function getMeta() { 4783 return this.chart.getDatasetMeta(this.index); 4784 } 4785 }, { 4786 key: "getScaleForId", 4787 value: function getScaleForId(scaleID) { 4788 return this.chart.scales[scaleID]; 4789 } 4790 }, { 4791 key: "_getOtherScale", 4792 value: function _getOtherScale(scale) { 4793 var meta = this._cachedMeta; 4794 return scale === meta.iScale ? meta.vScale : meta.iScale; 4795 } 4796 }, { 4797 key: "reset", 4798 value: function reset() { 4799 this._update('reset'); 4800 } 4801 }, { 4802 key: "_destroy", 4803 value: function _destroy() { 4804 var meta = this._cachedMeta; 4805 if (this._data) { 4806 unlistenArrayEvents(this._data, this); 4807 } 4808 if (meta._stacked) { 4809 clearStacks(meta); 4810 } 4811 } 4812 }, { 4813 key: "_dataCheck", 4814 value: function _dataCheck() { 4815 var dataset = this.getDataset(); 4816 var data = dataset.data || (dataset.data = []); 4817 var _data = this._data; 4818 if (isObject(data)) { 4819 var meta = this._cachedMeta; 4820 this._data = convertObjectDataToArray(data, meta); 4821 } else if (_data !== data) { 4822 if (_data) { 4823 unlistenArrayEvents(_data, this); 4824 var _meta = this._cachedMeta; 4825 clearStacks(_meta); 4826 _meta._parsed = []; 4827 } 4828 if (data && Object.isExtensible(data)) { 4829 listenArrayEvents(data, this); 4830 } 4831 this._syncList = []; 4832 this._data = data; 4833 } 4834 } 4835 }, { 4836 key: "addElements", 4837 value: function addElements() { 4838 var meta = this._cachedMeta; 4839 this._dataCheck(); 4840 if (this.datasetElementType) { 4841 meta.dataset = new this.datasetElementType(); 4842 } 4843 } 4844 }, {
4845 key: "buildOrUpdateElements", 4846 value: function buildOrUpdateElements(resetNewElements) { 4847 var meta = this._cachedMeta; 4848 var dataset = this.getDataset(); 4849 var stackChanged = false; 4850 this._dataCheck(); 4851 var oldStacked = meta._stacked; 4852 meta._stacked = isStacked(meta.vScale, meta); 4853 if (meta.stack !== dataset.stack) { 4854 stackChanged = true; 4855 clearStacks(meta); 4856 meta.stack = dataset.stack; 4857 } 4858 this._resyncElements(resetNewElements); 4859 if (stackChanged || oldStacked !== meta._stacked) { 4860 updateStacks(this, meta._parsed); 4861 meta._stacked = isStacked(meta.vScale, meta); 4862 } 4863 } 4864 }, { 4865 key: "configure", 4866 value: function configure() { 4867 var config = this.chart.config; 4868 var scopeKeys = config.datasetScopeKeys(this._type); 4869 var scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true); 4870 this.options = config.createResolver(scopes, this.getContext()); 4871 this._parsing = this.options.parsing; 4872 this._cachedDataOpts = {}; 4873 } 4874 }, { 4875 key: "parse", 4876 value: function parse(start, count) { 4877 var meta = this._cachedMeta, 4878 data = this._data; 4879 var iScale = meta.iScale, 4880 _stacked = meta._stacked; 4881 var iAxis = iScale.axis; 4882 var sorted = start === 0 && count === data.length ? true : meta._sorted; 4883 var prev = start > 0 && meta._parsed[start - 1]; 4884 var i, cur, parsed; 4885 if (this._parsing === false) { 4886 meta._parsed = data; 4887 meta._sorted = true; 4888 parsed = data; 4889 } else { 4890 if (isArray(data[start])) { 4891 parsed = this.parseArrayData(meta, data, start, count); 4892 } else if (isObject(data[start])) { 4893 parsed = this.parseObjectData(meta, data, start, count); 4894 } else { 4895 parsed = this.parsePrimitiveData(meta, data, start, count); 4896 } 4897 var isNotInOrderComparedToPrev = function isNotInOrderComparedToPrev() { 4898 return cur[iAxis] === null || prev && cur[iAxis] < prev[iAxis]; 4899 }; 4900 for (i = 0; i < count; ++i) { 4901 meta._parsed[i + start] = cur = parsed[i]; 4902 if (sorted) { 4903 if (isNotInOrderComparedToPrev()) { 4904 sorted = false; 4905 } 4906 prev = cur; 4907 } 4908 } 4909 meta._sorted = sorted; 4910 } 4911 if (_stacked) { 4912 updateStacks(this, parsed); 4913 } 4914 } 4915 }, { 4916 key: "parsePrimitiveData", 4917 value: function parsePrimitiveData(meta, data, start, count) { 4918 var iScale = meta.iScale, 4919 vScale = meta.vScale; 4920 var iAxis = iScale.axis; 4921 var vAxis = vScale.axis; 4922 var labels = iScale.getLabels(); 4923 var singleScale = iScale === vScale; 4924 var parsed = new Array(count); 4925 var i, ilen, index; 4926 for (i = 0, ilen = count; i < ilen; ++i) { 4927 index = i + start; 4928 parsed[i] = _defineProperty$1(_defineProperty$1({}, iAxis, singleScale || iScale.parse(labels[index], index)), vAxis, vScale.parse(data[index], index)); 4929 } 4930 return parsed; 4931 } 4932 }, { 4933 key: "parseArrayData", 4934 value: function parseArrayData(meta, data, start, count) { 4935 var xScale = meta.xScale, 4936 yScale = meta.yScale; 4937 var parsed = new Array(count); 4938 var i, ilen, index, item; 4939 for (i = 0, ilen = count; i < ilen; ++i) { 4940 index = i + start; 4941 item = data[index]; 4942 parsed[i] = { 4943 x: xScale.parse(item[0], index), 4944 y: yScale.parse(item[1], index) 4945 }; 4946 } 4947 return parsed; 4948 } 4949 }, { 4950 key: "parseObjectData", 4951 value: function parseObjectData(meta, data, start, count) { 4952 var xScale = meta.xScale, 4953 yScale = meta.yScale; 4954 var _this$_parsing = this._parsing, 4955 _this$_parsing$xAxisK = _this$_parsing.xAxisKey, 4956 xAxisKey = _this$_parsing$xAxisK === void 0 ? 'x' : _this$_parsing$xAxisK, 4957 _this$_parsing$yAxisK = _this$_parsing.yAxisKey, 4958 yAxisKey = _this$_parsing$yAxisK === void 0 ? 'y' : _this$_parsing$yAxisK; 4959 var parsed = new Array(count); 4960 var i, ilen, index, item; 4961 for (i = 0, ilen = count; i < ilen; ++i) { 4962 index = i + start; 4963 item = data[index]; 4964 parsed[i] = {
4965 x: xScale.parse(resolveObjectKey(item, xAxisKey), index), 4966 y: yScale.parse(resolveObjectKey(item, yAxisKey), index) 4967 }; 4968 } 4969 return parsed; 4970 } 4971 }, { 4972 key: "getParsed", 4973 value: function getParsed(index) { 4974 return this._cachedMeta._parsed[index]; 4975 } 4976 }, { 4977 key: "getDataElement", 4978 value: function getDataElement(index) { 4979 return this._cachedMeta.data[index]; 4980 } 4981 }, { 4982 key: "applyStack", 4983 value: function applyStack(scale, parsed, mode) { 4984 var chart = this.chart; 4985 var meta = this._cachedMeta; 4986 var value = parsed[scale.axis]; 4987 var stack = { 4988 keys: getSortedDatasetIndices(chart, true), 4989 values: parsed._stacks[scale.axis]._visualValues 4990 }; 4991 return _applyStack(stack, value, meta.index, { 4992 mode: mode 4993 }); 4994 } 4995 }, { 4996 key: "updateRangeFromParsed", 4997 value: function updateRangeFromParsed(range, scale, parsed, stack) { 4998 var parsedValue = parsed[scale.axis]; 4999 var value = parsedValue === null ? NaN : parsedValue; 5000 var values = stack && parsed._stacks[scale.axis]; 5001 if (stack && values) { 5002 stack.values = values; 5003 value = _applyStack(stack, parsedValue, this._cachedMeta.index); 5004 } 5005 range.min = Math.min(range.min, value); 5006 range.max = Math.max(range.max, value); 5007 } 5008 }, { 5009 key: "getMinMax", 5010 value: function getMinMax(scale, canStack) { 5011 var meta = this._cachedMeta; 5012 var _parsed = meta._parsed; 5013 var sorted = meta._sorted && scale === meta.iScale; 5014 var ilen = _parsed.length; 5015 var otherScale = this._getOtherScale(scale); 5016 var stack = createStack(canStack, meta, this.chart); 5017 var range = { 5018 min: Number.POSITIVE_INFINITY, 5019 max: Number.NEGATIVE_INFINITY 5020 }; 5021 var _getUserBounds = getUserBounds(otherScale), 5022 otherMin = _getUserBounds.min, 5023 otherMax = _getUserBounds.max; 5024 var i, parsed; 5025 function _skip() { 5026 parsed = _parsed[i]; 5027 var otherValue = parsed[otherScale.axis]; 5028 return !isNumberFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue; 5029 } 5030 for (i = 0; i < ilen; ++i) { 5031 if (_skip()) { 5032 continue; 5033 } 5034 this.updateRangeFromParsed(range, scale, parsed, stack); 5035 if (sorted) { 5036 break; 5037 } 5038 } 5039 if (sorted) { 5040 for (i = ilen - 1; i >= 0; --i) { 5041 if (_skip()) { 5042 continue; 5043 } 5044 this.updateRangeFromParsed(range, scale, parsed, stack); 5045 break; 5046 } 5047 } 5048 return range; 5049 } 5050 }, { 5051 key: "getAllParsedValues", 5052 value: function getAllParsedValues(scale) { 5053 var parsed = this._cachedMeta._parsed; 5054 var values = []; 5055 var i, ilen, value; 5056 for (i = 0, ilen = parsed.length; i < ilen; ++i) { 5057 value = parsed[i][scale.axis]; 5058 if (isNumberFinite(value)) { 5059 values.push(value); 5060 } 5061 } 5062 return values; 5063 } 5064 }, { 5065 key: "getMaxOverflow", 5066 value: function getMaxOverflow() { 5067 return false; 5068 } 5069 }, { 5070 key: "getLabelAndValue", 5071 value: function getLabelAndValue(index) { 5072 var meta = this._cachedMeta; 5073 var iScale = meta.iScale; 5074 var vScale = meta.vScale; 5075 var parsed = this.getParsed(index); 5076 return { 5077 label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '', 5078 value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : '' 5079 }; 5080 } 5081 }, { 5082 key: "_update", 5083 value: function _update(mode) { 5084 var meta = this._cachedMeta; 5085 this.update(mode || 'default'); 5086 meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow()))); 5087 } 5088 }, { 5089 key: "update", 5090 value: function update(mode) {} 5091 }, {
5092 key: "draw", 5093 value: function draw() { 5094 var ctx = this._ctx; 5095 var chart = this.chart; 5096 var meta = this._cachedMeta; 5097 var elements = meta.data || []; 5098 var area = chart.chartArea; 5099 var active = []; 5100 var start = this._drawStart || 0; 5101 var count = this._drawCount || elements.length - start; 5102 var drawActiveElementsOnTop = this.options.drawActiveElementsOnTop; 5103 var i; 5104 if (meta.dataset) { 5105 meta.dataset.draw(ctx, area, start, count); 5106 } 5107 for (i = start; i < start + count; ++i) { 5108 var element = elements[i]; 5109 if (element.hidden) { 5110 continue; 5111 } 5112 if (element.active && drawActiveElementsOnTop) { 5113 active.push(element); 5114 } else { 5115 element.draw(ctx, area); 5116 } 5117 } 5118 for (i = 0; i < active.length; ++i) { 5119 active[i].draw(ctx, area); 5120 } 5121 } 5122 }, { 5123 key: "getStyle", 5124 value: function getStyle(index, active) { 5125 var mode = active ? 'active' : 'default'; 5126 return index === undefined && this._cachedMeta.dataset ? this.resolveDatasetElementOptions(mode) : this.resolveDataElementOptions(index || 0, mode); 5127 } 5128 }, { 5129 key: "getContext", 5130 value: function getContext(index, active, mode) { 5131 var dataset = this.getDataset(); 5132 var context; 5133 if (index >= 0 && index < this._cachedMeta.data.length) { 5134 var element = this._cachedMeta.data[index]; 5135 context = element.$context || (element.$context = createDataContext(this.getContext(), index, element)); 5136 context.parsed = this.getParsed(index); 5137 context.raw = dataset.data[index]; 5138 context.index = context.dataIndex = index; 5139 } else { 5140 context = this.$context || (this.$context = createDatasetContext(this.chart.getContext(), this.index)); 5141 context.dataset = dataset; 5142 context.index = context.datasetIndex = this.index; 5143 } 5144 context.active = !!active; 5145 context.mode = mode; 5146 return context; 5147 } 5148 }, { 5149 key: "resolveDatasetElementOptions", 5150 value: function resolveDatasetElementOptions(mode) { 5151 return this._resolveElementOptions(this.datasetElementType.id, mode); 5152 } 5153 }, { 5154 key: "resolveDataElementOptions", 5155 value: function resolveDataElementOptions(index, mode) { 5156 return this._resolveElementOptions(this.dataElementType.id, mode, index); 5157 } 5158 }, { 5159 key: "_resolveElementOptions", 5160 value: function _resolveElementOptions(elementType) { 5161 var _this3 = this; 5162 var mode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default'; 5163 var index = arguments.length > 2 ? arguments[2] : undefined; 5164 var active = mode === 'active'; 5165 var cache = this._cachedDataOpts; 5166 var cacheKey = elementType + '-' + mode; 5167 var cached = cache[cacheKey]; 5168 var sharing = this.enableOptionSharing && defined(index); 5169 if (cached) { 5170 return cloneIfNotShared(cached, sharing); 5171 } 5172 var config = this.chart.config; 5173 var scopeKeys = config.datasetElementScopeKeys(this._type, elementType); 5174 var prefixes = active ? ["".concat(elementType, "Hover"), 'hover', elementType, ''] : [elementType, '']; 5175 var scopes = config.getOptionScopes(this.getDataset(), scopeKeys); 5176 var names = Object.keys(defaults.elements[elementType]); 5177 var context = function context() { 5178 return _this3.getContext(index, active, mode); 5179 }; 5180 var values = config.resolveNamedOptions(scopes, names, context, prefixes); 5181 if (values.$shared) { 5182 values.$shared = sharing; 5183 cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing)); 5184 } 5185 return values; 5186 } 5187 }, { 5188 key: "_resolveAnimations", 5189 value: function _resolveAnimations(index, transition, active) { 5190 var chart = this.chart; 5191 var cache = this._cachedDataOpts; 5192 var cacheKey = "animation-".concat(transition);
5193 var cached = cache[cacheKey]; 5194 if (cached) { 5195 return cached; 5196 } 5197 var options; 5198 if (chart.options.animation !== false) { 5199 var config = this.chart.config; 5200 var scopeKeys = config.datasetAnimationScopeKeys(this._type, transition); 5201 var scopes = config.getOptionScopes(this.getDataset(), scopeKeys); 5202 options = config.createResolver(scopes, this.getContext(index, active, transition)); 5203 } 5204 var animations = new Animations(chart, options && options.animations); 5205 if (options && options._cacheable) { 5206 cache[cacheKey] = Object.freeze(animations); 5207 } 5208 return animations; 5209 } 5210 }, { 5211 key: "getSharedOptions", 5212 value: function getSharedOptions(options) { 5213 if (!options.$shared) { 5214 return; 5215 } 5216 return this._sharedOptions || (this._sharedOptions = Object.assign({}, options)); 5217 } 5218 }, { 5219 key: "includeOptions", 5220 value: function includeOptions(mode, sharedOptions) { 5221 return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled; 5222 } 5223 }, { 5224 key: "_getSharedOptions", 5225 value: function _getSharedOptions(start, mode) { 5226 var firstOpts = this.resolveDataElementOptions(start, mode); 5227 var previouslySharedOptions = this._sharedOptions; 5228 var sharedOptions = this.getSharedOptions(firstOpts); 5229 var includeOptions = this.includeOptions(mode, sharedOptions) || sharedOptions !== previouslySharedOptions; 5230 this.updateSharedOptions(sharedOptions, mode, firstOpts); 5231 return { 5232 sharedOptions: sharedOptions, 5233 includeOptions: includeOptions 5234 }; 5235 } 5236 }, { 5237 key: "updateElement", 5238 value: function updateElement(element, index, properties, mode) { 5239 if (isDirectUpdateMode(mode)) { 5240 Object.assign(element, properties); 5241 } else { 5242 this._resolveAnimations(index, mode).update(element, properties); 5243 } 5244 } 5245 }, { 5246 key: "updateSharedOptions", 5247 value: function updateSharedOptions(sharedOptions, mode, newOptions) { 5248 if (sharedOptions && !isDirectUpdateMode(mode)) { 5249 this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions); 5250 } 5251 } 5252 }, { 5253 key: "_setStyle", 5254 value: function _setStyle(element, index, mode, active) { 5255 element.active = active; 5256 var options = this.getStyle(index, active); 5257 this._resolveAnimations(index, mode, active).update(element, { 5258 options: !active && this.getSharedOptions(options) || options 5259 }); 5260 } 5261 }, { 5262 key: "removeHoverStyle", 5263 value: function removeHoverStyle(element, datasetIndex, index) { 5264 this._setStyle(element, index, 'active', false); 5265 } 5266 }, { 5267 key: "setHoverStyle", 5268 value: function setHoverStyle(element, datasetIndex, index) { 5269 this._setStyle(element, index, 'active', true); 5270 } 5271 }, { 5272 key: "_removeDatasetHoverStyle", 5273 value: function _removeDatasetHoverStyle() { 5274 var element = this._cachedMeta.dataset; 5275 if (element) { 5276 this._setStyle(element, undefined, 'active', false); 5277 } 5278 } 5279 }, { 5280 key: "_setDatasetHoverStyle", 5281 value: function _setDatasetHoverStyle() { 5282 var element = this._cachedMeta.dataset; 5283 if (element) { 5284 this._setStyle(element, undefined, 'active', true); 5285 } 5286 } 5287 }, { 5288 key: "_resyncElements", 5289 value: function _resyncElements(resetNewElements) { 5290 var data = this._data; 5291 var elements = this._cachedMeta.data; 5292 var _iterator3 = _createForOfIteratorHelper$1(this._syncList), 5293 _step3; 5294 try { 5295 for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { 5296 var _step3$value = _slicedToArray(_step3.value, 3), 5297 method = _step3$value[0], 5298 arg1 = _step3$value[1], 5299 arg2 = _step3$value[2]; 5300 this[method](arg1, arg2); 5301 } 5302 } catch (err) { 5303 _iterator3.e(err); 5304 } finally { 5305 _iterator3.f(); 5306 } 5307 this._syncList = []; 5308 var numMeta = elements.length; 5309 var numData = data.length; 5310 var count = Math.min(numData, numMeta); 5311 if (count) { 5312 this.parse(0, count); 5313 } 5314 if (numData > numMeta) { 5315 this._insertElements(numMeta, numData - numMeta, resetNewElements); 5316 } else if (numData < numMeta) { 5317 this._removeElements(numData, numMeta - numData); 5318 } 5319 } 5320 }, {
5321 key: "_insertElements", 5322 value: function _insertElements(start, count) { 5323 var resetNewElements = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; 5324 var meta = this._cachedMeta; 5325 var data = meta.data; 5326 var end = start + count; 5327 var i; 5328 var move = function move(arr) { 5329 arr.length += count; 5330 for (i = arr.length - 1; i >= end; i--) { 5331 arr[i] = arr[i - count]; 5332 } 5333 }; 5334 move(data); 5335 for (i = start; i < end; ++i) { 5336 data[i] = new this.dataElementType(); 5337 } 5338 if (this._parsing) { 5339 move(meta._parsed); 5340 } 5341 this.parse(start, count); 5342 if (resetNewElements) { 5343 this.updateElements(data, start, count, 'reset'); 5344 } 5345 } 5346 }, { 5347 key: "updateElements", 5348 value: function updateElements(element, start, count, mode) {} 5349 }, { 5350 key: "_removeElements", 5351 value: function _removeElements(start, count) { 5352 var meta = this._cachedMeta; 5353 if (this._parsing) { 5354 var removed = meta._parsed.splice(start, count); 5355 if (meta._stacked) { 5356 clearStacks(meta, removed); 5357 } 5358 } 5359 meta.data.splice(start, count); 5360 } 5361 }, { 5362 key: "_sync", 5363 value: function _sync(args) { 5364 if (this._parsing) { 5365 this._syncList.push(args); 5366 } else { 5367 var _args2 = _slicedToArray(args, 3), 5368 method = _args2[0], 5369 arg1 = _args2[1], 5370 arg2 = _args2[2]; 5371 this[method](arg1, arg2); 5372 } 5373 this.chart._dataChanges.push([this.index].concat(_toConsumableArray(args))); 5374 } 5375 }, { 5376 key: "_onDataPush", 5377 value: function _onDataPush() { 5378 var count = arguments.length; 5379 this._sync(['_insertElements', this.getDataset().data.length - count, count]); 5380 } 5381 }, { 5382 key: "_onDataPop", 5383 value: function _onDataPop() { 5384 this._sync(['_removeElements', this._cachedMeta.data.length - 1, 1]); 5385 } 5386 }, { 5387 key: "_onDataShift", 5388 value: function _onDataShift() { 5389 this._sync(['_removeElements', 0, 1]); 5390 } 5391 }, { 5392 key: "_onDataSplice", 5393 value: function _onDataSplice(start, count) { 5394 if (count) { 5395 this._sync(['_removeElements', start, count]); 5396 } 5397 var newCount = arguments.length - 2; 5398 if (newCount) { 5399 this._sync(['_insertElements', start, newCount]); 5400 } 5401 } 5402 }, { 5403 key: "_onDataUnshift", 5404 value: function _onDataUnshift() { 5405 this._sync(['_insertElements', 0, arguments.length]); 5406 } 5407 }]); 5408 }(); 5409 _defineProperty$1(DatasetController, "defaults", {}); 5410 _defineProperty$1(DatasetController, "datasetElementType", null); 5411 _defineProperty$1(DatasetController, "dataElementType", null); 5412 function getAllScaleValues(scale, type) { 5413 if (!scale._cache.$bar) { 5414 var visibleMetas = scale.getMatchingVisibleMetas(type); 5415 var values = []; 5416 for (var i = 0, ilen = visibleMetas.length; i < ilen; i++) { 5417 values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale)); 5418 } 5419 scale._cache.$bar = _arrayUnique(values.sort(function (a, b) { 5420 return a - b; 5421 })); 5422 } 5423 return scale._cache.$bar; 5424 } 5425 function computeMinSampleSize(meta) { 5426 var scale = meta.iScale; 5427 var values = getAllScaleValues(scale, meta.type); 5428 var min = scale._length; 5429 var i, ilen, curr, prev; 5430 var updateMinAndPrev = function updateMinAndPrev() { 5431 if (curr === 32767 || curr === -32768) { 5432 return; 5433 } 5434 if (defined(prev)) { 5435 min = Math.min(min, Math.abs(curr - prev) || min); 5436 } 5437 prev = curr; 5438 }; 5439 for (i = 0, ilen = values.length; i < ilen; ++i) { 5440 curr = scale.getPixelForValue(values[i]); 5441 updateMinAndPrev(); 5442 } 5443 prev = undefined; 5444 for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) { 5445 curr = scale.getPixelForTick(i); 5446 updateMinAndPrev(); 5447 } 5448 return min; 5449 } 5450 function computeFitCategoryTraits(index, ruler, options, stackCount) { 5451 var thickness = options.barThickness; 5452 var size, ratio; 5453 if (isNullOrUndef(thickness)) { 5454 size = ruler.min * options.categoryPercentage; 5455 ratio = options.barPercentage; 5456 } else { 5457 size = thickness * stackCount; 5458 ratio = 1; 5459 } 5460 return { 5461 chunk: size / stackCount, 5462 ratio: ratio, 5463 start: ruler.pixels[index] - size / 2 5464 }; 5465 } 5466 function computeFlexCategoryTraits(index, ruler, options, stackCount) { 5467 var pixels = ruler.pixels; 5468 var curr = pixels[index]; 5469 var prev = index > 0 ? pixels[index - 1] : null; 5470 var next = index < pixels.length - 1 ? pixels[index + 1] : null; 5471 var percent = options.categoryPercentage; 5472 if (prev === null) { 5473 prev = curr - (next === null ? ruler.end - ruler.start : next - curr); 5474 } 5475 if (next === null) { 5476 next = curr + curr - prev; 5477 } 5478 var start = curr - (curr - Math.min(prev, next)) / 2 * percent; 5479 var size = Math.abs(next - prev) / 2 * percent; 5480 return { 5481 chunk: size / stackCount, 5482 ratio: options.barPercentage, 5483 start: start 5484 }; 5485 } 5486 function parseFloatBar(entry, item, vScale, i) { 5487 var startValue = vScale.parse(entry[0], i); 5488 var endValue = vScale.parse(entry[1], i); 5489 var min = Math.min(startValue, endValue); 5490 var max = Math.max(startValue, endValue); 5491 var barStart = min; 5492 var barEnd = max; 5493 if (Math.abs(min) > Math.abs(max)) { 5494 barStart = max; 5495 barEnd = min; 5496 }
vendor: 4,819 bytes, lines 5497-5652
5497 item[vScale.axis] = barEnd; 5498 item._custom = { 5499 barStart: barStart, 5500 barEnd: barEnd, 5501 start: startValue, 5502 end: endValue, 5503 min: min, 5504 max: max 5505 }; 5506 } 5507 function parseValue(entry, item, vScale, i) { 5508 if (isArray(entry)) { 5509 parseFloatBar(entry, item, vScale, i); 5510 } else { 5511 item[vScale.axis] = vScale.parse(entry, i); 5512 } 5513 return item; 5514 } 5515 function parseArrayOrPrimitive(meta, data, start, count) { 5516 var iScale = meta.iScale; 5517 var vScale = meta.vScale; 5518 var labels = iScale.getLabels(); 5519 var singleScale = iScale === vScale; 5520 var parsed = []; 5521 var i, ilen, item, entry; 5522 for (i = start, ilen = start + count; i < ilen; ++i) { 5523 entry = data[i]; 5524 item = {}; 5525 item[iScale.axis] = singleScale || iScale.parse(labels[i], i); 5526 parsed.push(parseValue(entry, item, vScale, i)); 5527 } 5528 return parsed; 5529 } 5530 function isFloatBar(custom) { 5531 return custom && custom.barStart !== undefined && custom.barEnd !== undefined; 5532 } 5533 function barSign(size, vScale, actualBase) { 5534 if (size !== 0) { 5535 return sign(size); 5536 } 5537 return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1); 5538 } 5539 function borderProps(properties) { 5540 var reverse, start, end, top, bottom; 5541 if (properties.horizontal) { 5542 reverse = properties.base > properties.x; 5543 start = 'left'; 5544 end = 'right'; 5545 } else { 5546 reverse = properties.base < properties.y; 5547 start = 'bottom'; 5548 end = 'top'; 5549 } 5550 if (reverse) { 5551 top = 'end'; 5552 bottom = 'start'; 5553 } else { 5554 top = 'start'; 5555 bottom = 'end'; 5556 } 5557 return { 5558 start: start, 5559 end: end, 5560 reverse: reverse, 5561 top: top, 5562 bottom: bottom 5563 }; 5564 } 5565 function setBorderSkipped(properties, options, stack, index) { 5566 var edge = options.borderSkipped; 5567 var res = {}; 5568 if (!edge) { 5569 properties.borderSkipped = res; 5570 return; 5571 } 5572 if (edge === true) { 5573 properties.borderSkipped = { 5574 top: true, 5575 right: true, 5576 bottom: true, 5577 left: true 5578 }; 5579 return; 5580 } 5581 var _borderProps = borderProps(properties), 5582 start = _borderProps.start, 5583 end = _borderProps.end, 5584 reverse = _borderProps.reverse, 5585 top = _borderProps.top, 5586 bottom = _borderProps.bottom; 5587 if (edge === 'middle' && stack) { 5588 properties.enableBorderRadius = true; 5589 if ((stack._top || 0) === index) { 5590 edge = top; 5591 } else if ((stack._bottom || 0) === index) { 5592 edge = bottom; 5593 } else { 5594 res[parseEdge(bottom, start, end, reverse)] = true; 5595 edge = top; 5596 } 5597 } 5598 res[parseEdge(edge, start, end, reverse)] = true; 5599 properties.borderSkipped = res; 5600 } 5601 function parseEdge(edge, a, b, reverse) { 5602 if (reverse) { 5603 edge = swap(edge, a, b); 5604 edge = startEnd(edge, b, a); 5605 } else { 5606 edge = startEnd(edge, a, b); 5607 } 5608 return edge; 5609 } 5610 function swap(orig, v1, v2) { 5611 return orig === v1 ? v2 : orig === v2 ? v1 : orig; 5612 } 5613 function startEnd(v, start, end) { 5614 return v === 'start' ? start : v === 'end' ? end : v; 5615 } 5616 function setInflateAmount(properties, _ref, ratio) { 5617 var inflateAmount = _ref.inflateAmount; 5618 properties.inflateAmount = inflateAmount === 'auto' ? ratio === 1 ? 0.33 : 0 : inflateAmount; 5619 } 5620 var BarController = /*#__PURE__*/function (_DatasetController2) { 5621 function BarController() { 5622 _classCallCheck$1(this, BarController); 5623 return _callSuper(this, BarController, arguments); 5624 } 5625 _inherits$1(BarController, _DatasetController2); 5626 return _createClass$1(BarController, [{ 5627 key: "parsePrimitiveData", 5628 value: function parsePrimitiveData(meta, data, start, count) { 5629 return parseArrayOrPrimitive(meta, data, start, count); 5630 } 5631 }, { 5632 key: "parseArrayData", 5633 value: function parseArrayData(meta, data, start, count) { 5634 return parseArrayOrPrimitive(meta, data, start, count); 5635 } 5636 }, { 5637 key: "parseObjectData", 5638 value: function parseObjectData(meta, data, start, count) { 5639 var iScale = meta.iScale, 5640 vScale = meta.vScale; 5641 var _this$_parsing2 = this._parsing, 5642 _this$_parsing2$xAxis = _this$_parsing2.xAxisKey, 5643 xAxisKey = _this$_parsing2$xAxis === void 0 ? 'x' : _this$_parsing2$xAxis, 5644 _this$_parsing2$yAxis = _this$_parsing2.yAxisKey, 5645 yAxisKey = _this$_parsing2$yAxis === void 0 ? 'y' : _this$_parsing2$yAxis; 5646 var iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey; 5647 var vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey; 5648 var parsed = []; 5649 var i, ilen, item, obj; 5650 for (i = start, ilen = start + count; i < ilen; ++i) { 5651 obj = data[i]; 5652 item = {};
5653 item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i); 5654 parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i)); 5655 } 5656 return parsed; 5657 } 5658 }, { 5659 key: "updateRangeFromParsed", 5660 value: function updateRangeFromParsed(range, scale, parsed, stack) { 5661 _superPropGet(BarController, "updateRangeFromParsed", this, 3)([range, scale, parsed, stack]); 5662 var custom = parsed._custom; 5663 if (custom && scale === this._cachedMeta.vScale) { 5664 range.min = Math.min(range.min, custom.min); 5665 range.max = Math.max(range.max, custom.max); 5666 } 5667 } 5668 }, { 5669 key: "getMaxOverflow", 5670 value: function getMaxOverflow() { 5671 return 0; 5672 } 5673 }, { 5674 key: "getLabelAndValue", 5675 value: function getLabelAndValue(index) { 5676 var meta = this._cachedMeta; 5677 var iScale = meta.iScale, 5678 vScale = meta.vScale; 5679 var parsed = this.getParsed(index); 5680 var custom = parsed._custom; 5681 var value = isFloatBar(custom) ? '[' + custom.start + ', ' + custom.end + ']' : '' + vScale.getLabelForValue(parsed[vScale.axis]); 5682 return { 5683 label: '' + iScale.getLabelForValue(parsed[iScale.axis]), 5684 value: value 5685 }; 5686 } 5687 }, { 5688 key: "initialize", 5689 value: function initialize() { 5690 this.enableOptionSharing = true; 5691 _superPropGet(BarController, "initialize", this, 3)([]); 5692 var meta = this._cachedMeta; 5693 meta.stack = this.getDataset().stack; 5694 } 5695 }, { 5696 key: "update", 5697 value: function update(mode) { 5698 var meta = this._cachedMeta; 5699 this.updateElements(meta.data, 0, meta.data.length, mode); 5700 } 5701 }, { 5702 key: "updateElements", 5703 value: function updateElements(bars, start, count, mode) { 5704 var reset = mode === 'reset'; 5705 var index = this.index, 5706 vScale = this._cachedMeta.vScale; 5707 var base = vScale.getBasePixel(); 5708 var horizontal = vScale.isHorizontal(); 5709 var ruler = this._getRuler(); 5710 var _this$_getSharedOptio = this._getSharedOptions(start, mode), 5711 sharedOptions = _this$_getSharedOptio.sharedOptions, 5712 includeOptions = _this$_getSharedOptio.includeOptions; 5713 for (var i = start; i < start + count; i++) { 5714 var parsed = this.getParsed(i); 5715 var vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? { 5716 base: base, 5717 head: base 5718 } : this._calculateBarValuePixels(i); 5719 var ipixels = this._calculateBarIndexPixels(i, ruler); 5720 var stack = (parsed._stacks || {})[vScale.axis]; 5721 var properties = { 5722 horizontal: horizontal, 5723 base: vpixels.base, 5724 enableBorderRadius: !stack || isFloatBar(parsed._custom) || index === stack._top || index === stack._bottom, 5725 x: horizontal ? vpixels.head : ipixels.center, 5726 y: horizontal ? ipixels.center : vpixels.head, 5727 height: horizontal ? ipixels.size : Math.abs(vpixels.size), 5728 width: horizontal ? Math.abs(vpixels.size) : ipixels.size 5729 }; 5730 if (includeOptions) { 5731 properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode); 5732 } 5733 var options = properties.options || bars[i].options; 5734 setBorderSkipped(properties, options, stack, index); 5735 setInflateAmount(properties, options, ruler.ratio); 5736 this.updateElement(bars[i], i, properties, mode); 5737 } 5738 } 5739 }, { 5740 key: "_getStacks", 5741 value: function _getStacks(last, dataIndex) { 5742 var iScale = this._cachedMeta.iScale; 5743 var metasets = iScale.getMatchingVisibleMetas(this._type).filter(function (meta) { 5744 return meta.controller.options.grouped; 5745 }); 5746 var stacked = iScale.options.stacked; 5747 var stacks = []; 5748 var currentParsed = this._cachedMeta.controller.getParsed(dataIndex); 5749 var iScaleValue = currentParsed && currentParsed[iScale.axis
5749]; 5750 var skipNull = function skipNull(meta) { 5751 var parsed = meta._parsed.find(function (item) { 5752 return item[iScale.axis] === iScaleValue; 5753 }); 5754 var val = parsed && parsed[meta.vScale.axis]; 5755 if (isNullOrUndef(val) || isNaN(val)) { 5756 return true; 5757 } 5758 }; 5759 var _iterator4 = _createForOfIteratorHelper$1(metasets), 5760 _step4; 5761 try { 5762 for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { 5763 var meta = _step4.value; 5764 if (dataIndex !== undefined && skipNull(meta)) { 5765 continue; 5766 } 5767 if (stacked === false || stacks.indexOf(meta.stack) === -1 || stacked === undefined && meta.stack === undefined) { 5768 stacks.push(meta.stack); 5769 } 5770 if (meta.index === last) { 5771 break; 5772 } 5773 } 5774 } catch (err) { 5775 _iterator4.e(err); 5776 } finally { 5777 _iterator4.f(); 5778 } 5779 if (!stacks.length) { 5780 stacks.push(undefined); 5781 } 5782 return stacks; 5783 } 5784 }, { 5785 key: "_getStackCount", 5786 value: function _getStackCount(index) { 5787 return this._getStacks(undefined, index).length; 5788 } 5789 }, { 5790 key: "_getAxisCount", 5791 value: function _getAxisCount() { 5792 return this._getAxis().length; 5793 } 5794 }, { 5795 key: "getFirstScaleIdForIndexAxis", 5796 value: function getFirstScaleIdForIndexAxis() { 5797 var scales = this.chart.scales; 5798 var indexScaleId = this.chart.options.indexAxis; 5799 return Object.keys(scales).filter(function (key) { 5800 return scales[key].axis === indexScaleId; 5801 }).shift(); 5802 } 5803 }, { 5804 key: "_getAxis", 5805 value: function _getAxis() { 5806 var axis = {}; 5807 var firstScaleAxisId = this.getFirstScaleIdForIndexAxis(); 5808 var _iterator5 = _createForOfIteratorHelper$1(this.chart.data.datasets), 5809 _step5; 5810 try { 5811 for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { 5812 var dataset = _step5.value; 5813 axis[valueOrDefault(this.chart.options.indexAxis === 'x' ? dataset.xAxisID : dataset.yAxisID, firstScaleAxisId)] = true; 5814 } 5815 } catch (err) { 5816 _iterator5.e(err); 5817 } finally { 5818 _iterator5.f(); 5819 } 5820 return Object.keys(axis); 5821 } 5822 }, { 5823 key: "_getStackIndex", 5824 value: function _getStackIndex(datasetIndex, name, dataIndex) { 5825 var stacks = this._getStacks(datasetIndex, dataIndex); 5826 var index = name !== undefined ? stacks.indexOf(name) : -1; 5827 return index === -1 ? stacks.length - 1 : index; 5828 } 5829 }, { 5830 key: "_getRuler", 5831 value: function _getRuler() { 5832 var opts = this.options; 5833 var meta = this._cachedMeta; 5834 var iScale = meta.iScale; 5835 var pixels = []; 5836 var i, ilen; 5837 for (i = 0, ilen = meta.data.length; i < ilen; ++i) { 5838 pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i)); 5839 } 5840 var barThickness = opts.barThickness; 5841 var min = barThickness || computeMinSampleSize(meta); 5842 return { 5843 min: min, 5844 pixels: pixels, 5845 start: iScale._startPixel, 5846 end: iScale._endPixel, 5847 stackCount: this._getStackCount(), 5848 scale: iScale, 5849 grouped: opts.grouped, 5850 ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage 5851 }; 5852 } 5853 }, { 5854 key: "_calculateBarValuePixels", 5855 value: function _calculateBarValuePixels(index) { 5856 var _this$_cachedMeta = this._cachedMeta, 5857 vScale = _this$_cachedMeta.vScale, 5858 _stacked = _this$_cachedMeta._stacked, 5859 datasetIndex = _this$_cachedMeta.index, 5860 _this$options = this.options, 5861 baseValue = _this$options.base, 5862 minBarLength = _this$options.minBarLength; 5863 var actualBase = baseValue || 0; 5864 var parsed = this.getParsed(index); 5865 var custom = parsed._custom; 5866 var floating = isFloatBar(custom);
5867 var value = parsed[vScale.axis]; 5868 var start = 0; 5869 var length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value; 5870 var head, size; 5871 if (length !== value) { 5872 start = length - value; 5873 length = value; 5874 } 5875 if (floating) { 5876 value = custom.barStart; 5877 length = custom.barEnd - custom.barStart; 5878 if (value !== 0 && sign(value) !== sign(custom.barEnd)) { 5879 start = 0; 5880 } 5881 start += value; 5882 } 5883 var startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start; 5884 var base = vScale.getPixelForValue(startValue); 5885 if (this.chart.getDataVisibility(index)) { 5886 head = vScale.getPixelForValue(start + length); 5887 } else { 5888 head = base; 5889 } 5890 size = head - base; 5891 if (Math.abs(size) < minBarLength) { 5892 size = barSign(size, vScale, actualBase) * minBarLength; 5893 if (value === actualBase) { 5894 base -= size / 2; 5895 } 5896 var startPixel = vScale.getPixelForDecimal(0); 5897 var endPixel = vScale.getPixelForDecimal(1); 5898 var min = Math.min(startPixel, endPixel); 5899 var max = Math.max(startPixel, endPixel); 5900 base = Math.max(Math.min(base, max), min); 5901 head = base + size; 5902 if (_stacked && !floating) { 5903 parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base); 5904 } 5905 } 5906 if (base === vScale.getPixelForValue(actualBase)) { 5907 var halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2; 5908 base += halfGrid; 5909 size -= halfGrid; 5910 } 5911 return { 5912 size: size, 5913 base: base, 5914 head: head, 5915 center: head + size / 2 5916 }; 5917 } 5918 }, { 5919 key: "_calculateBarIndexPixels", 5920 value: function _calculateBarIndexPixels(index, ruler) { 5921 var scale = ruler.scale; 5922 var options = this.options; 5923 var skipNull = options.skipNull; 5924 var maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity); 5925 var center, size; 5926 var axisCount = this._getAxisCount(); 5927 if (ruler.grouped) { 5928 var stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount; 5929 var range = options.barThickness === 'flex' ? computeFlexCategoryTraits(index, ruler, options, stackCount * axisCount) : computeFitCategoryTraits(index, ruler, options, stackCount * axisCount); 5930 var axisID = this.chart.options.indexAxis === 'x' ? this.getDataset().xAxisID : this.getDataset().yAxisID; 5931 var axisNumber = this._getAxis().indexOf(valueOrDefault(axisID, this.getFirstScaleIdForIndexAxis())); 5932 var stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined) + axisNumber; 5933 center = range.start + range.chunk * stackIndex + range.chunk / 2; 5934 size = Math.min(maxBarThickness, range.chunk * range.ratio); 5935 } else { 5936 center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index); 5937 size = Math.min(maxBarThickness, ruler.min * ruler.ratio); 5938 } 5939 return { 5940 base: center - size / 2, 5941 head: center + size / 2, 5942 center: center, 5943 size: size 5944 }; 5945 } 5946 }, { 5947 key: "draw", 5948 value: function draw() { 5949 var meta = this._cachedMeta; 5950 var vScale = meta.vScale; 5951 var rects = meta.data; 5952 var ilen = rects.length; 5953 var i = 0; 5954 for (; i < ilen; ++i) { 5955 if (this.getParsed(i)[vScale.axis] !== null && !rects[i].hidden) { 5956 rects[i].draw(this._ctx); 5957 } 5958 } 5959 } 5960 }]); 5961 }(DatasetController); 5962 _defineProperty$1(BarController, "id", 'bar'); 5963 _defineProperty$1(BarController, "defaults", { 5964 datasetElementType: false, 5965 dataElementType: 'bar', 5966 categoryPercentage: 0.8, 5967 barPercentage: 0.9, 5968 grouped: true, 5969 animations: { 5970 numbers: { 5971 type: 'number', 5972 properties: ['x', 'y', 'base', 'width', 'height'] 5973 } 5974 } 5975 }); 5976 _defineProperty$1(BarController, "overrides", { 5977 scales: { 5978 _index_: { 5979 type: 'category', 5980 offset: true, 5981 grid: { 5982 offset: true 5983 } 5984 }, 5985 _value_: { 5986 type: 'linear', 5987 beginAtZero: true 5988 } 5989 } 5990 }); 5991 var BubbleController = /*#__PURE__*/function (_DatasetController3) { 5992 function BubbleController() { 5993 _classCallCheck$1(this, BubbleController); 5994 return _callSuper(this, BubbleController, arguments); 5995 } 5996 _inherits$1(BubbleController, _DatasetController3); 5997 return _createClass$1(BubbleController, [{ 5998 key: "initialize", 5999 value: function initialize() { 6000 this.enableOptionSharing = true; 6001 _superPropGet(BubbleController, "initialize", this, 3)([]); 6002 } 6003 }, {
6004 key: "parsePrimitiveData", 6005 value: function parsePrimitiveData(meta, data, start, count) { 6006 var parsed = _superPropGet(BubbleController, "parsePrimitiveData", this, 3)([meta, data, start, count]); 6007 for (var i = 0; i < parsed.length; i++) { 6008 parsed[i]._custom = this.resolveDataElementOptions(i + start).radius; 6009 } 6010 return parsed; 6011 } 6012 }, { 6013 key: "parseArrayData", 6014 value: function parseArrayData(meta, data, start, count) { 6015 var parsed = _superPropGet(BubbleController, "parseArrayData", this, 3)([meta, data, start, count]); 6016 for (var i = 0; i < parsed.length; i++) { 6017 var item = data[start + i]; 6018 parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius); 6019 } 6020 return parsed; 6021 } 6022 }, { 6023 key: "parseObjectData", 6024 value: function parseObjectData(meta, data, start, count) { 6025 var parsed = _superPropGet(BubbleController, "parseObjectData", this, 3)([meta, data, start, count]); 6026 for (var i = 0; i < parsed.length; i++) { 6027 var item = data[start + i]; 6028 parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius); 6029 } 6030 return parsed; 6031 } 6032 }, { 6033 key: "getMaxOverflow", 6034 value: function getMaxOverflow() { 6035 var data = this._cachedMeta.data; 6036 var max = 0; 6037 for (var i = data.length - 1; i >= 0; --i) { 6038 max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2); 6039 } 6040 return max > 0 && max; 6041 } 6042 }, { 6043 key: "getLabelAndValue", 6044 value: function getLabelAndValue(index) { 6045 var meta = this._cachedMeta; 6046 var labels = this.chart.data.labels || []; 6047 var xScale = meta.xScale, 6048 yScale = meta.yScale; 6049 var parsed = this.getParsed(index); 6050 var x = xScale.getLabelForValue(parsed.x); 6051 var y = yScale.getLabelForValue(parsed.y); 6052 var r = parsed._custom; 6053 return { 6054 label: labels[index] || '', 6055 value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')' 6056 }; 6057 } 6058 }, { 6059 key: "update", 6060 value: function update(mode) { 6061 var points = this._cachedMeta.data; 6062 this.updateElements(points, 0, points.length, mode); 6063 } 6064 }, { 6065 key: "updateElements", 6066 value: function updateElements(points, start, count, mode) { 6067 var reset = mode === 'reset'; 6068 var _this$_cachedMeta2 = this._cachedMeta, 6069 iScale = _this$_cachedMeta2.iScale, 6070 vScale = _this$_cachedMeta2.vScale; 6071 var _this$_getSharedOptio2 = this._getSharedOptions(start, mode), 6072 sharedOptions = _this$_getSharedOptio2.sharedOptions, 6073 includeOptions = _this$_getSharedOptio2.includeOptions; 6074 var iAxis = iScale.axis; 6075 var vAxis = vScale.axis; 6076 for (var i = start; i < start + count; i++) { 6077 var point = points[i]; 6078 var parsed = !reset && this.getParsed(i); 6079 var properties = {}; 6080 var iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]); 6081 var vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]); 6082 properties.skip = isNaN(iPixel) || isNaN(vPixel); 6083 if (includeOptions) { 6084 properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode); 6085 if (reset) { 6086 properties.options.radius = 0; 6087 } 6088 } 6089 this.updateElement(point, i, properties, mode); 6090 } 6091 } 6092 }, { 6093 key: "resolveDataElementOptions", 6094 value: function resolveDataElementOptions(index, mode) { 6095 var parsed = this.getParsed(index); 6096 var values = _superPropGet(BubbleController, "resolveDataElementOptions", this, 3)([index, mode]); 6097 if (values.$shared) { 6098 values = Object.assign({}, values, { 6099 $shared: false 6100 }); 6101 } 6102 var radius = values.radius; 6103 if (mode !== 'active') { 6104 values.radius = 0; 6105 } 6106 values.radius += valueOrDefault(parsed && parsed._custom, radius); 6107 return values; 6108 } 6109 }]); 6110 }(DatasetController); 6111 _defineProperty$1(BubbleController, "id", 'bubble'); 6112 _defineProperty$1(BubbleController, "defaults", { 6113 datasetElementType: false, 6114 dataElementType: 'point', 6115 animations: { 6116 numbers: { 6117 type: 'number', 6118 properties: ['x', 'y', 'borderWidth', 'radius'] 6119 } 6120 } 6121 }); 6122 _defineProperty$1(BubbleController, "overrides", { 6123 scales: { 6124 x: { 6125 type: 'linear' 6126 }, 6127 y: { 6128 type: 'linear' 6129 } 6130 } 6131 }); 6132 function getRatioAndOffset(rotation, circumference, cutout) { 6133 var ratioX = 1; 6134 var ratioY = 1; 6135 var offsetX = 0; 6136 var offsetY = 0; 6137 if (circumference < TAU) { 6138 var startAngle = rotation; 6139 var endAngle = startAngle + circumference; 6140 var startX = Math.cos(startAngle); 6141 var startY = Math.sin(startAngle); 6142 var endX = Math.cos(endAngle); 6143 var endY = Math.sin(endAngle); 6144 var calcMax = function calcMax(angle, a, b) { 6145 return _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout); 6146 }; 6147 var calcMin = function calcMin(angle, a, b) { 6148 return _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout); 6149 }; 6150 var maxX = calcMax(0, startX, endX); 6151 var maxY = calcMax(HALF_PI, startY, endY); 6152 var minX = calcMin(PI, startX, endX); 6153 var minY = calcMin(PI + HALF_PI, startY, endY); 6154 ratioX = (maxX - minX) / 2; 6155 ratioY = (maxY - minY) / 2; 6156 offsetX = -(maxX + minX) / 2; 6157 offsetY = -(maxY + minY) / 2; 6158 } 6159 return { 6160 ratioX: ratioX, 6161 ratioY: ratioY, 6162 offsetX: offsetX, 6163 offsetY: offsetY 6164 }; 6165 } 6166 var DoughnutController = /*#__PURE__*/function (_DatasetController4) { 6167 function DoughnutController(chart, datasetIndex) { 6168 var _this4; 6169 _classCallCheck$1(this, DoughnutController); 6170 _this4 = _callSuper(this, DoughnutController, [chart, datasetIndex]); 6171 _this4.enableOptionSharing = true; 6172 _this4.innerRadius = undefined; 6173 _this4.outerRadius = undefined; 6174 _this4.offsetX = undefined; 6175 _this4.offsetY = undefined; 6176 return _this4; 6177 } 6178 _inherits$1(DoughnutController, _DatasetController4); 6179 return _createClass$1(DoughnutController, [{ 6180 key: "linkScales", 6181 value: function linkScales() {} 6182 }, {
6183 key: "parse", 6184 value: function parse(start, count) { 6185 var data = this.getDataset().data; 6186 var meta = this._cachedMeta; 6187 if (this._parsing === false) { 6188 meta._parsed = data; 6189 } else { 6190 var getter = function getter(i) { 6191 return +data[i]; 6192 }; 6193 if (isObject(data[start])) { 6194 var _this$_parsing$key = this._parsing.key, 6195 key = _this$_parsing$key === void 0 ? 'value' : _this$_parsing$key; 6196 getter = function getter(i) { 6197 return +resolveObjectKey(data[i], key); 6198 }; 6199 } 6200 var i, ilen; 6201 for (i = start, ilen = start + count; i < ilen; ++i) { 6202 meta._parsed[i] = getter(i); 6203 } 6204 } 6205 } 6206 }, { 6207 key: "_getRotation", 6208 value: function _getRotation() { 6209 return toRadians(this.options.rotation - 90); 6210 } 6211 }, { 6212 key: "_getCircumference", 6213 value: function _getCircumference() { 6214 return toRadians(this.options.circumference); 6215 } 6216 }, { 6217 key: "_getRotationExtents", 6218 value: function _getRotationExtents() { 6219 var min = TAU; 6220 var max = -TAU; 6221 for (var i = 0; i < this.chart.data.datasets.length; ++i) { 6222 if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) { 6223 var controller = this.chart.getDatasetMeta(i).controller; 6224 var rotation = controller._getRotation(); 6225 var circumference = controller._getCircumference(); 6226 min = Math.min(min, rotation); 6227 max = Math.max(max, rotation + circumference); 6228 } 6229 } 6230 return { 6231 rotation: min, 6232 circumference: max - min 6233 }; 6234 } 6235 }, { 6236 key: "update", 6237 value: function update(mode) { 6238 var chart = this.chart; 6239 var chartArea = chart.chartArea; 6240 var meta = this._cachedMeta; 6241 var arcs = meta.data; 6242 var spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing; 6243 var maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0); 6244 var cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1); 6245 var chartWeight = this._getRingWeight(this.index); 6246 var _this$_getRotationExt = this._getRotationExtents(), 6247 circumference = _this$_getRotationExt.circumference, 6248 rotation = _this$_getRotationExt.rotation; 6249 var _getRatioAndOffset = getRatioAndOffset(rotation, circumference, cutout), 6250 ratioX = _getRatioAndOffset.ratioX, 6251 ratioY = _getRatioAndOffset.ratioY, 6252 offsetX = _getRatioAndOffset.offsetX, 6253 offsetY = _getRatioAndOffset.offsetY; 6254 var maxWidth = (chartArea.width - spacing) / ratioX; 6255 var maxHeight = (chartArea.height - spacing) / ratioY; 6256 var maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0); 6257 var outerRadius = toDimension(this.options.radius, maxRadius); 6258 var innerRadius = Math.max(outerRadius * cutout, 0); 6259 var radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal(); 6260 this.offsetX = offsetX * outerRadius; 6261 this.offsetY = offsetY * outerRadius; 6262 meta.total = this.calculateTotal(); 6263 this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index); 6264 this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0); 6265 this.updateElements(arcs, 0, arcs.length, mode); 6266 } 6267 }, { 6268 key: "_circumference", 6269 value: function _circumference(i, reset) { 6270 var opts = this.options; 6271 var meta = this._cachedMeta; 6272 var circumference = this._getCircumference(); 6273 if (reset && opts.animation.animateRotate || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) { 6274 return 0; 6275 } 6276 return this.calculateCircumference(meta._parsed[i] * circumference / TAU); 6277 } 6278 }, { 6279 key: "updateElements", 6280 value: function updateElements(arcs, start, count, mode) { 6281 var reset = mode === 'reset'; 6282 var chart = this.chart; 6283 var chartArea = chart.chartArea; 6284 var opts = chart.options; 6285 var animationOpts = opts.animation; 6286 var centerX = (chartArea.left + chartArea.right) / 2; 6287 var centerY = (chartArea.top + chartArea.bottom) / 2; 6288 var animateScale = reset && animationOpts.animateScale; 6289 var innerRadius = animateScale ? 0 : this.innerRadius; 6290 var outerRadius = animateScale ? 0 : this.outerRadius; 6291 var _this$_getSharedOptio3 = this._getSharedOptions(start, mode), 6292 sharedOptions = _this$_getSharedOptio3.sharedOptions, 6293 includeOptions = _this$_getSharedOptio3.includeOptions; 6294 var startAngle = this._getRotation(); 6295 var i; 6296 for (i = 0; i < start; ++i) { 6297 startAngle += this._circumference(i, reset); 6298 } 6299 for (i = start; i < start + count; ++i) { 6300 var circumference = this._circumference(i, reset); 6301 var arc = arcs[i]; 6302 var properties = { 6303 x: centerX + this.offsetX, 6304 y: centerY + this.offsetY, 6305 startAngle: startAngle, 6306 endAngle: startAngle + circumference, 6307 circumference: circumference, 6308 outerRadius: outerRadius, 6309 innerRadius: innerRadius 6310 }; 6311 if (includeOptions) { 6312 properties.options = sharedOptions || this.resolveDataElementOptions(i, ar
6312c.active ? 'active' : mode); 6313 } 6314 startAngle += circumference; 6315 this.updateElement(arc, i, properties, mode); 6316 } 6317 } 6318 }, { 6319 key: "calculateTotal", 6320 value: function calculateTotal() { 6321 var meta = this._cachedMeta; 6322 var metaData = meta.data; 6323 var total = 0; 6324 var i; 6325 for (i = 0; i < metaData.length; i++) { 6326 var value = meta._parsed[i]; 6327 if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) { 6328 total += Math.abs(value); 6329 } 6330 } 6331 return total; 6332 } 6333 }, { 6334 key: "calculateCircumference", 6335 value: function calculateCircumference(value) { 6336 var total = this._cachedMeta.total; 6337 if (total > 0 && !isNaN(value)) { 6338 return TAU * (Math.abs(value) / total); 6339 } 6340 return 0; 6341 } 6342 }, { 6343 key: "getLabelAndValue", 6344 value: function getLabelAndValue(index) { 6345 var meta = this._cachedMeta; 6346 var chart = this.chart; 6347 var labels = chart.data.labels || []; 6348 var value = formatNumber(meta._parsed[index], chart.options.locale); 6349 return { 6350 label: labels[index] || '', 6351 value: value 6352 }; 6353 } 6354 }, { 6355 key: "getMaxBorderWidth", 6356 value: function getMaxBorderWidth(arcs) { 6357 var max = 0; 6358 var chart = this.chart; 6359 var i, ilen, meta, controller, options; 6360 if (!arcs) { 6361 for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) { 6362 if (chart.isDatasetVisible(i)) { 6363 meta = chart.getDatasetMeta(i); 6364 arcs = meta.data; 6365 controller = meta.controller; 6366 break; 6367 } 6368 } 6369 } 6370 if (!arcs) { 6371 return 0; 6372 } 6373 for (i = 0, ilen = arcs.length; i < ilen; ++i) { 6374 options = controller.resolveDataElementOptions(i); 6375 if (options.borderAlign !== 'inner') { 6376 max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0); 6377 } 6378 } 6379 return max; 6380 } 6381 }, { 6382 key: "getMaxOffset", 6383 value: function getMaxOffset(arcs) { 6384 var max = 0; 6385 for (var i = 0, ilen = arcs.length; i < ilen; ++i) { 6386 var options = this.resolveDataElementOptions(i); 6387 max = Math.max(max, options.offset || 0, options.hoverOffset || 0); 6388 } 6389 return max; 6390 } 6391 }, { 6392 key: "_getRingWeightOffset", 6393 value: function _getRingWeightOffset(datasetIndex) { 6394 var ringWeightOffset = 0; 6395 for (var i = 0; i < datasetIndex; ++i) { 6396 if (this.chart.isDatasetVisible(i)) { 6397 ringWeightOffset += this._getRingWeight(i); 6398 } 6399 } 6400 return ringWeightOffset; 6401 } 6402 }, { 6403 key: "_getRingWeight", 6404 value: function _getRingWeight(datasetIndex) { 6405 return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0); 6406 } 6407 }, { 6408 key: "_getVisibleDatasetWeightTotal", 6409 value: function _getVisibleDatasetWeightTotal() { 6410 return this._getRingWeightOffset(this.chart.data.datasets.length) || 1; 6411 } 6412 }]); 6413 }(DatasetController); 6414 _defineProperty$1(DoughnutController, "id", 'doughnut'); 6415 _defineProperty$1(DoughnutController, "defaults", { 6416 datasetElementType: false, 6417 dataElementType: 'arc', 6418 animation: { 6419 animateRotate: true, 6420 animateScale: false 6421 }, 6422 animations: { 6423 numbers: { 6424 type: 'number', 6425 properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing'] 6426 } 6427 }, 6428 cutout: '50%', 6429 rotation: 0, 6430 circumference: 360, 6431 radius: '100%', 6432 spacing: 0, 6433 indexAxis: 'r' 6434 }); 6435 _defineProperty$1(DoughnutController, "descriptors", { 6436 _scriptable: function _scriptable(name) { 6437 return name !== 'spacing'; 6438 }, 6439 _indexable: function _indexable(name) { 6440 return name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash'); 6441 } 6442 }); 6443 _defineProperty$1(DoughnutController, "overrides", { 6444 aspectRatio: 1, 6445 plugins: { 6446 legend: { 6447 labels: { 6448 generateLabels: function generateLabels(chart) { 6449 var data = chart.data; 6450 var _chart$legend$options2 = chart.legend.options.labels, 6451 pointStyle = _chart$legend$options2.pointStyle, 6452 textAlign = _chart$legend$options2.textAlign, 6453 color = _chart$legend$options2.color, 6454 useBorderRadius = _chart$legend$options2.useBorderRadius, 6455 borderRadius = _chart$legend$options2.borderRadius; 6456 if (data.labels.length && data.datasets.length) { 6457 return data.labels.map(function (label, i) { 6458 var meta = chart.getDatasetMeta(0); 6459 var style = meta.controller.getStyle(i); 6460 return { 6461 text: label, 6462 fillStyle: style.backgroundColor, 6463 fontColor: color, 6464 hidden: !chart.getDataVisibility(i), 6465 lineDash: style.borderDash, 6466 lineDashOffset: style.borderDashOffset, 6467 lineJoin: style.borderJoinStyle, 6468 lineWidth: style.borderWidth, 6469 strokeStyle: style.borderColor, 6470 textAlign: textAlign, 6471 pointStyle: pointStyle, 6472 borderRadius: useBorderRadius && (borderRadius || style.borderRadius), 6473 index: i 6474 }; 6475 }); 6476 } 6477 return []; 6478 } 6479 }, 6480 onClick: function onClick(e, legendItem, legend) { 6481 legend.chart.toggleDataVisibility(legendItem.index);
6482 legend.chart.update(); 6483 } 6484 } 6485 } 6486 }); 6487 var LineController = /*#__PURE__*/function (_DatasetController5) { 6488 function LineController() { 6489 _classCallCheck$1(this, LineController); 6490 return _callSuper(this, LineController, arguments); 6491 } 6492 _inherits$1(LineController, _DatasetController5); 6493 return _createClass$1(LineController, [{ 6494 key: "initialize", 6495 value: function initialize() { 6496 this.enableOptionSharing = true; 6497 this.supportsDecimation = true; 6498 _superPropGet(LineController, "initialize", this, 3)([]); 6499 } 6500 }, { 6501 key: "update", 6502 value: function update(mode) { 6503 var meta = this._cachedMeta; 6504 var line = meta.dataset, 6505 _meta$data = meta.data, 6506 points = _meta$data === void 0 ? [] : _meta$data, 6507 _dataset = meta._dataset; 6508 var animationsDisabled = this.chart._animationsDisabled; 6509 var _getStartAndCountOfVi = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled), 6510 start = _getStartAndCountOfVi.start, 6511 count = _getStartAndCountOfVi.count; 6512 this._drawStart = start; 6513 this._drawCount = count; 6514 if (_scaleRangesChanged(meta)) { 6515 start = 0; 6516 count = points.length; 6517 } 6518 line._chart = this.chart; 6519 line._datasetIndex = this.index; 6520 line._decimated = !!_dataset._decimated; 6521 line.points = points; 6522 var options = this.resolveDatasetElementOptions(mode); 6523 if (!this.options.showLine) { 6524 options.borderWidth = 0; 6525 } 6526 options.segment = this.options.segment; 6527 this.updateElement(line, undefined, { 6528 animated: !animationsDisabled, 6529 options: options 6530 }, mode); 6531 this.updateElements(points, start, count, mode); 6532 } 6533 }, { 6534 key: "updateElements", 6535 value: function updateElements(points, start, count, mode) { 6536 var reset = mode === 'reset'; 6537 var _this$_cachedMeta3 = this._cachedMeta, 6538 iScale = _this$_cachedMeta3.iScale, 6539 vScale = _this$_cachedMeta3.vScale, 6540 _stacked = _this$_cachedMeta3._stacked, 6541 _dataset = _this$_cachedMeta3._dataset; 6542 var _this$_getSharedOptio4 = this._getSharedOptions(start, mode), 6543 sharedOptions = _this$_getSharedOptio4.sharedOptions, 6544 includeOptions = _this$_getSharedOptio4.includeOptions; 6545 var iAxis = iScale.axis; 6546 var vAxis = vScale.axis; 6547 var _this$options2 = this.options, 6548 spanGaps = _this$options2.spanGaps, 6549 segment = _this$options2.segment; 6550 var maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY; 6551 var directUpdate = this.chart._animationsDisabled || reset || mode === 'none'; 6552 var end = start + count; 6553 var pointsCount = points.length; 6554 var prevParsed = start > 0 && this.getParsed(start - 1); 6555 for (var i = 0; i < pointsCount; ++i) { 6556 var point = points[i]; 6557 var properties = directUpdate ? point : {}; 6558 if (i < start || i >= end) { 6559 properties.skip = true; 6560 continue; 6561 } 6562 var parsed = this.getParsed(i); 6563 var nullData = isNullOrUndef(parsed[vAxis]); 6564 var iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i); 6565 var vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i); 6566 properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData; 6567 properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength; 6568 if (segment) { 6569 properties.parsed = parsed; 6570 properties.raw = _dataset.data[i]; 6571 } 6572 if (includeOptions) { 6573 properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode); 6574 } 6575 if (!directUpdate) { 6576 this.updateElement(point, i, properties, mode); 6577 } 6578 prevParsed = parsed; 6579 } 6580 } 6581 }, {
6582 key: "getMaxOverflow", 6583 value: function getMaxOverflow() { 6584 var meta = this._cachedMeta; 6585 var dataset = meta.dataset; 6586 var border = dataset.options && dataset.options.borderWidth || 0; 6587 var data = meta.data || []; 6588 if (!data.length) { 6589 return border; 6590 } 6591 var firstPoint = data[0].size(this.resolveDataElementOptions(0)); 6592 var lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1)); 6593 return Math.max(border, firstPoint, lastPoint) / 2; 6594 } 6595 }, { 6596 key: "draw", 6597 value: function draw() { 6598 var meta = this._cachedMeta; 6599 meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis); 6600 _superPropGet(LineController, "draw", this, 3)([]); 6601 } 6602 }]); 6603 }(DatasetController); 6604 _defineProperty$1(LineController, "id", 'line'); 6605 _defineProperty$1(LineController, "defaults", { 6606 datasetElementType: 'line', 6607 dataElementType: 'point', 6608 showLine: true, 6609 spanGaps: false 6610 }); 6611 _defineProperty$1(LineController, "overrides", { 6612 scales: { 6613 _index_: { 6614 type: 'category' 6615 }, 6616 _value_: { 6617 type: 'linear' 6618 } 6619 } 6620 }); 6621 var PolarAreaController = /*#__PURE__*/function (_DatasetController6) { 6622 function PolarAreaController(chart, datasetIndex) { 6623 var _this5; 6624 _classCallCheck$1(this, PolarAreaController); 6625 _this5 = _callSuper(this, PolarAreaController, [chart, datasetIndex]); 6626 _this5.innerRadius = undefined; 6627 _this5.outerRadius = undefined; 6628 return _this5; 6629 } 6630 _inherits$1(PolarAreaController, _DatasetController6); 6631 return _createClass$1(PolarAreaController, [{ 6632 key: "getLabelAndValue", 6633 value: function getLabelAndValue(index) { 6634 var meta = this._cachedMeta; 6635 var chart = this.chart; 6636 var labels = chart.data.labels || []; 6637 var value = formatNumber(meta._parsed[index].r, chart.options.locale); 6638 return { 6639 label: labels[index] || '', 6640 value: value 6641 }; 6642 } 6643 }, { 6644 key: "parseObjectData", 6645 value: function parseObjectData(meta, data, start, count) { 6646 return _parseObjectDataRadialScale.bind(this)(meta, data, start, count); 6647 } 6648 }, { 6649 key: "update", 6650 value: function update(mode) { 6651 var arcs = this._cachedMeta.data; 6652 this._updateRadius(); 6653 this.updateElements(arcs, 0, arcs.length, mode); 6654 } 6655 }, { 6656 key: "getMinMax", 6657 value: function getMinMax() { 6658 var _this6 = this; 6659 var meta = this._cachedMeta; 6660 var range = { 6661 min: Number.POSITIVE_INFINITY, 6662 max: Number.NEGATIVE_INFINITY 6663 }; 6664 meta.data.forEach(function (element, index) { 6665 var parsed = _this6.getParsed(index).r; 6666 if (!isNaN(parsed) && _this6.chart.getDataVisibility(index)) { 6667 if (parsed < range.min) { 6668 range.min = parsed; 6669 } 6670 if (parsed > range.max) { 6671 range.max = parsed; 6672 } 6673 } 6674 }); 6675 return range; 6676 } 6677 }, { 6678 key: "_updateRadius", 6679 value: function _updateRadius() { 6680 var chart = this.chart; 6681 var chartArea = chart.chartArea; 6682 var opts = chart.options; 6683 var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); 6684 var outerRadius = Math.max(minSize / 2, 0); 6685 var innerRadius = Math.max(opts.cutoutPercentage ? outerRadius / 100 * opts.cutoutPercentage : 1, 0); 6686 var radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount(); 6687 this.outerRadius = outerRadius - radiusLength * this.index; 6688 this.innerRadius = this.outerRadius - radiusLength; 6689 } 6690 }, { 6691 key: "updateElements", 6692 value: function updateElements(arcs, start, count, mode) { 6693 var reset = mode === 'reset'; 6694 var chart = this.chart; 6695 var opts = chart.options; 6696 var animationOpts = opts.animation; 6697 var scale = this._cachedMeta.rScale; 6698 var centerX = scale.xCenter; 6699 var centerY = scale.yCenter; 6700 var datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI; 6701 var angle = datasetStartAngle; 6702 var i; 6703 var defaultAngle = 360 / this.countVisibleElements(); 6704 for (i = 0; i < start; ++i) { 6705 angle += this._computeAngle(i, mode, defaultAngle); 6706 } 6707 for (i = start; i < start + count; i++) { 6708 var arc = arcs[i]; 6709 var startAngle = angle; 6710 var endAngle = angle + this._computeAngle(i, mode, defaultAngle); 6711 var outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0; 6712 angle = endAngle; 6713 if (reset) { 6714 if (animationOpts.animateScale) { 6715 outerRadius = 0; 6716 } 6717 if (animationOpts.animateRotate) { 6718 startAngle = endAngle = datasetStartAngle; 6719 } 6720 } 6721 var properties = { 6722 x: centerX, 6723 y: centerY, 6724 innerRadius: 0, 6725 outerRadius: outerRadius, 6726 startAngle: startAngle, 6727 endAngle: endAngle,
6728 options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode) 6729 }; 6730 this.updateElement(arc, i, properties, mode); 6731 } 6732 } 6733 }, { 6734 key: "countVisibleElements", 6735 value: function countVisibleElements() { 6736 var _this7 = this; 6737 var meta = this._cachedMeta; 6738 var count = 0; 6739 meta.data.forEach(function (element, index) { 6740 if (!isNaN(_this7.getParsed(index).r) && _this7.chart.getDataVisibility(index)) { 6741 count++; 6742 } 6743 }); 6744 return count; 6745 } 6746 }, { 6747 key: "_computeAngle", 6748 value: function _computeAngle(index, mode, defaultAngle) { 6749 return this.chart.getDataVisibility(index) ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle) : 0; 6750 } 6751 }]); 6752 }(DatasetController); 6753 _defineProperty$1(PolarAreaController, "id", 'polarArea'); 6754 _defineProperty$1(PolarAreaController, "defaults", { 6755 dataElementType: 'arc', 6756 animation: { 6757 animateRotate: true, 6758 animateScale: true 6759 }, 6760 animations: { 6761 numbers: { 6762 type: 'number', 6763 properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius'] 6764 } 6765 }, 6766 indexAxis: 'r', 6767 startAngle: 0 6768 }); 6769 _defineProperty$1(PolarAreaController, "overrides", { 6770 aspectRatio: 1, 6771 plugins: { 6772 legend: { 6773 labels: { 6774 generateLabels: function generateLabels(chart) { 6775 var data = chart.data; 6776 if (data.labels.length && data.datasets.length) { 6777 var _chart$legend$options3 = chart.legend.options.labels, 6778 pointStyle = _chart$legend$options3.pointStyle, 6779 color = _chart$legend$options3.color; 6780 return data.labels.map(function (label, i) { 6781 var meta = chart.getDatasetMeta(0); 6782 var style = meta.controller.getStyle(i); 6783 return { 6784 text: label, 6785 fillStyle: style.backgroundColor, 6786 strokeStyle: style.borderColor, 6787 fontColor: color, 6788 lineWidth: style.borderWidth, 6789 pointStyle: pointStyle, 6790 hidden: !chart.getDataVisibility(i), 6791 index: i 6792 }; 6793 }); 6794 } 6795 return []; 6796 } 6797 }, 6798 onClick: function onClick(e, legendItem, legend) { 6799 legend.chart.toggleDataVisibility(legendItem.index); 6800 legend.chart.update(); 6801 } 6802 } 6803 }, 6804 scales: { 6805 r: { 6806 type: 'radialLinear', 6807 angleLines: { 6808 display: false 6809 }, 6810 beginAtZero: true, 6811 grid: { 6812 circular: true 6813 }, 6814 pointLabels: { 6815 display: false 6816 }, 6817 startAngle: 0 6818 } 6819 } 6820 }); 6821 var PieController = /*#__PURE__*/function (_DoughnutController2) { 6822 function PieController() { 6823 _classCallCheck$1(this, PieController); 6824 return _callSuper(this, PieController, arguments); 6825 } 6826 _inherits$1(PieController, _DoughnutController2); 6827 return _createClass$1(PieController); 6828 }(DoughnutController); 6829 _defineProperty$1(PieController, "id", 'pie'); 6830 _defineProperty$1(PieController, "defaults", { 6831 cutout: 0, 6832 rotation: 0, 6833 circumference: 360, 6834 radius: '100%' 6835 }); 6836 var RadarController = /*#__PURE__*/function (_DatasetController7) { 6837 function RadarController() { 6838 _classCallCheck$1(this, RadarController); 6839 return _callSuper(this, RadarController, arguments); 6840 } 6841 _inherits$1(RadarController, _DatasetController7); 6842 return _createClass$1(RadarController, [{ 6843 key: "getLabelAndValue", 6844 value: function getLabelAndValue(index) { 6845 var vScale = this._cachedMeta.vScale; 6846 var parsed = this.getParsed(index); 6847 return { 6848 label: vScale.getLabels()[index], 6849 value: '' + vScale.getLabelForValue(parsed[vScale.axis]) 6850 }; 6851 } 6852 }, { 6853 key: "parseObjectData", 6854 value: function parseObjectData(meta, data, start, count) { 6855 return _parseObjectDataRadialScale.bind(this)(meta, data, start, count); 6856 } 6857 }, {
6858 key: "update", 6859 value: function update(mode) { 6860 var meta = this._cachedMeta; 6861 var line = meta.dataset; 6862 var points = meta.data || []; 6863 var labels = meta.iScale.getLabels(); 6864 line.points = points; 6865 if (mode !== 'resize') { 6866 var options = this.resolveDatasetElementOptions(mode); 6867 if (!this.options.showLine) { 6868 options.borderWidth = 0; 6869 } 6870 var properties = { 6871 _loop: true, 6872 _fullLoop: labels.length === points.length, 6873 options: options 6874 }; 6875 this.updateElement(line, undefined, properties, mode); 6876 } 6877 this.updateElements(points, 0, points.length, mode); 6878 } 6879 }, { 6880 key: "updateElements", 6881 value: function updateElements(points, start, count, mode) { 6882 var scale = this._cachedMeta.rScale; 6883 var reset = mode === 'reset'; 6884 for (var i = start; i < start + count; i++) { 6885 var point = points[i]; 6886 var options = this.resolveDataElementOptions(i, point.active ? 'active' : mode); 6887 var pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r); 6888 var x = reset ? scale.xCenter : pointPosition.x; 6889 var y = reset ? scale.yCenter : pointPosition.y; 6890 var properties = { 6891 x: x, 6892 y: y, 6893 angle: pointPosition.angle, 6894 skip: isNaN(x) || isNaN(y), 6895 options: options 6896 }; 6897 this.updateElement(point, i, properties, mode); 6898 } 6899 } 6900 }]); 6901 }(DatasetController); 6902 _defineProperty$1(RadarController, "id", 'radar'); 6903 _defineProperty$1(RadarController, "defaults", { 6904 datasetElementType: 'line', 6905 dataElementType: 'point', 6906 indexAxis: 'r', 6907 showLine: true, 6908 elements: { 6909 line: { 6910 fill: 'start' 6911 } 6912 } 6913 }); 6914 _defineProperty$1(RadarController, "overrides", { 6915 aspectRatio: 1, 6916 scales: { 6917 r: { 6918 type: 'radialLinear' 6919 } 6920 } 6921 }); 6922 var ScatterController = /*#__PURE__*/function (_DatasetController8) { 6923 function ScatterController() { 6924 _classCallCheck$1(this, ScatterController); 6925 return _callSuper(this, ScatterController, arguments); 6926 } 6927 _inherits$1(ScatterController, _DatasetController8); 6928 return _createClass$1(ScatterController, [{ 6929 key: "getLabelAndValue", 6930 value: function getLabelAndValue(index) { 6931 var meta = this._cachedMeta; 6932 var labels = this.chart.data.labels || []; 6933 var xScale = meta.xScale, 6934 yScale = meta.yScale; 6935 var parsed = this.getParsed(index); 6936 var x = xScale.getLabelForValue(parsed.x); 6937 var y = yScale.getLabelForValue(parsed.y); 6938 return { 6939 label: labels[index] || '', 6940 value: '(' + x + ', ' + y + ')' 6941 }; 6942 } 6943 }, { 6944 key: "update", 6945 value: function update(mode) { 6946 var meta = this._cachedMeta; 6947 var _meta$data2 = meta.data, 6948 points = _meta$data2 === void 0 ? [] : _meta$data2; 6949 var animationsDisabled = this.chart._animationsDisabled; 6950 var _getStartAndCountOfVi2 = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled), 6951 start = _getStartAndCountOfVi2.start, 6952 count = _getStartAndCountOfVi2.count; 6953 this._drawStart = start; 6954 this._drawCount = count; 6955 if (_scaleRangesChanged(meta)) { 6956 start = 0; 6957 count = points.length; 6958 } 6959 if (this.options.showLine) { 6960 if (!this.datasetElementType) { 6961 this.addElements(); 6962 } 6963 var line = meta.dataset, 6964 _dataset = meta._dataset; 6965 line._chart = this.chart; 6966 line._datasetIndex = this.index; 6967 line._decimated = !!_dataset._decimated; 6968 line.points = points; 6969 var options = this.resolveDatasetElementOptions(mode); 6970 options.segment = this.options.segment; 6971 this.updateElement(line, undefined, { 6972 animated: !animationsDisabled, 6973 options: options 6974 }, mode); 6975 } else if (this.datasetElementType) { 6976 delete meta.dataset; 6977 this.datasetElementType = false;
6978 } 6979 this.updateElements(points, start, count, mode); 6980 } 6981 }, { 6982 key: "addElements", 6983 value: function addElements() { 6984 var showLine = this.options.showLine; 6985 if (!this.datasetElementType && showLine) { 6986 this.datasetElementType = this.chart.registry.getElement('line'); 6987 } 6988 _superPropGet(ScatterController, "addElements", this, 3)([]); 6989 } 6990 }, { 6991 key: "updateElements", 6992 value: function updateElements(points, start, count, mode) { 6993 var reset = mode === 'reset'; 6994 var _this$_cachedMeta4 = this._cachedMeta, 6995 iScale = _this$_cachedMeta4.iScale, 6996 vScale = _this$_cachedMeta4.vScale, 6997 _stacked = _this$_cachedMeta4._stacked, 6998 _dataset = _this$_cachedMeta4._dataset; 6999 var firstOpts = this.resolveDataElementOptions(start, mode); 7000 var sharedOptions = this.getSharedOptions(firstOpts); 7001 var includeOptions = this.includeOptions(mode, sharedOptions); 7002 var iAxis = iScale.axis; 7003 var vAxis = vScale.axis; 7004 var _this$options3 = this.options, 7005 spanGaps = _this$options3.spanGaps, 7006 segment = _this$options3.segment; 7007 var maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY; 7008 var directUpdate = this.chart._animationsDisabled || reset || mode === 'none'; 7009 var prevParsed = start > 0 && this.getParsed(start - 1); 7010 for (var i = start; i < start + count; ++i) { 7011 var point = points[i]; 7012 var parsed = this.getParsed(i); 7013 var properties = directUpdate ? point : {}; 7014 var nullData = isNullOrUndef(parsed[vAxis]); 7015 var iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i); 7016 var vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i); 7017 properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData; 7018 properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength; 7019 if (segment) { 7020 properties.parsed = parsed; 7021 properties.raw = _dataset.data[i]; 7022 } 7023 if (includeOptions) { 7024 properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode); 7025 } 7026 if (!directUpdate) { 7027 this.updateElement(point, i, properties, mode); 7028 } 7029 prevParsed = parsed; 7030 } 7031 this.updateSharedOptions(sharedOptions, mode, firstOpts); 7032 } 7033 }, { 7034 key: "getMaxOverflow", 7035 value: function getMaxOverflow() { 7036 var meta = this._cachedMeta; 7037 var data = meta.data || []; 7038 if (!this.options.showLine) { 7039 var max = 0; 7040 for (var i = data.length - 1; i >= 0; --i) { 7041 max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2); 7042 } 7043 return max > 0 && max; 7044 } 7045 var dataset = meta.dataset; 7046 var border = dataset.options && dataset.options.borderWidth || 0; 7047 if (!data.length) { 7048 return border; 7049 } 7050 var firstPoint = data[0].size(this.resolveDataElementOptions(0)); 7051 var lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1)); 7052 return Math.max(border, firstPoint, lastPoint) / 2; 7053 } 7054 }]); 7055 }(DatasetController); 7056 _defineProperty$1(ScatterController, "id", 'scatter'); 7057 _defineProperty$1(ScatterController, "defaults", { 7058 datasetElementType: false, 7059 dataElementType: 'point', 7060 showLine: false, 7061 fill: false 7062 }); 7063 _defineProperty$1(ScatterController, "overrides", { 7064 interaction: { 7065 mode: 'point' 7066 }, 7067 scales: { 7068 x: { 7069 type: 'linear' 7070 }, 7071 y: { 7072 type: 'linear' 7073 } 7074 } 7075 }); 7076 var controllers = /*#__PURE__*/Object.freeze({ 7077 __proto__: null, 7078 BarController: BarController, 7079 BubbleController: BubbleController, 7080 DoughnutController: DoughnutController, 7081 LineController: LineController, 7082 PieController: PieController, 7083 PolarAreaController: PolarAreaController, 7084 RadarController: RadarController, 7085 ScatterController: ScatterController 7086 }); 7087 7088 /** 7089 * @namespace Chart._adapters 7090 * @since 2.8.0 7091 * @private 7092 */ 7093 function _abstract() { 7094 throw new Error('This method is not implemented: Check that a complete date adapter is provided.'); 7095 } 7096 /** 7097 * Date adapter (current used by the time scale) 7098 * @namespace Chart._adapters._date 7099 * @memberof Chart._adapters 7100 * @private 7101 */ 7102 var DateAdapterBase = /*#__PURE__*/function () { 7103 function DateAdapterBase(options) { 7104 _classCallCheck$1(this, DateAdapterBase); 7105 _defineProperty$1(this, "options", void 0); 7106 this.options = options || {}; 7107 } 7108 // eslint-disable-next-line @typescript-eslint/no-empty-function 7109 return _createClass$1(DateAdapterBase, [{ 7110 key: "init",
7111 value: function init() {} 7112 }, { 7113 key: "formats", 7114 value: function formats() { 7115 return _abstract(); 7116 } 7117 }, { 7118 key: "parse", 7119 value: function parse() { 7120 return _abstract(); 7121 } 7122 }, { 7123 key: "format", 7124 value: function format() { 7125 return _abstract(); 7126 } 7127 }, { 7128 key: "add", 7129 value: function add() { 7130 return _abstract(); 7131 } 7132 }, { 7133 key: "diff", 7134 value: function diff() { 7135 return _abstract(); 7136 } 7137 }, { 7138 key: "startOf", 7139 value: function startOf() { 7140 return _abstract(); 7141 } 7142 }, { 7143 key: "endOf", 7144 value: function endOf() { 7145 return _abstract(); 7146 } 7147 }], [{ 7148 key: "override", 7149 value: 7150 /** 7151 * Override default date adapter methods. 7152 * Accepts type parameter to define options type. 7153 * @example 7154 * Chart._adapters._date.override<{myAdapterOption: string}>({ 7155 * init() { 7156 * console.log(this.options.myAdapterOption); 7157 * } 7158 * }) 7159 */ 7160 function override(members) { 7161 Object.assign(DateAdapterBase.prototype, members); 7162 } 7163 }]); 7164 }(); 7165 var adapters = { 7166 _date: DateAdapterBase 7167 }; 7168 function binarySearch(metaset, axis, value, intersect) { 7169 var controller = metaset.controller, 7170 data = metaset.data, 7171 _sorted = metaset._sorted; 7172 var iScale = controller._cachedMeta.iScale; 7173 var spanGaps = metaset.dataset ? metaset.dataset.options ? metaset.dataset.options.spanGaps : null : null; 7174 if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) { 7175 var lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey; 7176 if (!intersect) { 7177 var result = lookupMethod(data, axis, value); 7178 if (spanGaps) { 7179 var vScale = controller._cachedMeta.vScale; 7180 var _parsed = metaset._parsed; 7181 var distanceToDefinedLo = _parsed.slice(0, result.lo + 1).reverse().findIndex(function (point) { 7182 return !isNullOrUndef(point[vScale.axis]); 7183 }); 7184 result.lo -= Math.max(0, distanceToDefinedLo); 7185 var distanceToDefinedHi = _parsed.slice(result.hi).findIndex(function (point) { 7186 return !isNullOrUndef(point[vScale.axis]); 7187 }); 7188 result.hi += Math.max(0, distanceToDefinedHi); 7189 } 7190 return result; 7191 } else if (controller._sharedOptions) { 7192 var el = data[0]; 7193 var range = typeof el.getRange === 'function' && el.getRange(axis); 7194 if (range) { 7195 var start = lookupMethod(data, axis, value - range); 7196 var end = lookupMethod(data, axis, value + range); 7197 return { 7198 lo: start.lo, 7199 hi: end.hi 7200 }; 7201 } 7202 } 7203 } 7204 return { 7205 lo: 0, 7206 hi: data.length - 1 7207 }; 7208 } 7209 function evaluateInteractionItems(chart, axis, position, handler, intersect) { 7210 var metasets = chart.getSortedVisibleDatasetMetas(); 7211 var value = position[axis]; 7212 for (var i = 0, ilen = metasets.length; i < ilen; ++i) { 7213 var _metasets$i = metasets[i], 7214 _index2 = _metasets$i.index, 7215 data = _metasets$i.data; 7216 var _binarySearch = binarySearch(metasets[i], axis, value, intersect), 7217 lo = _binarySearch.lo, 7218 hi = _binarySearch.hi; 7219 for (var j = lo; j <= hi; ++j) { 7220 var element = data[j]; 7221 if (!element.skip) { 7222 handler(element, _index2, j); 7223 } 7224 } 7225 } 7226 } 7227 function getDistanceMetricForAxis(axis) { 7228 var useX = axis.indexOf('x') !== -1; 7229 var useY = axis.indexOf('y') !== -1; 7230 return function (pt1, pt2) { 7231 var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0; 7232 var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0; 7233 return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); 7234 }; 7235 } 7236 function getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) { 7237 var items = []; 7238 if (!includeInvisible && !chart.isPointInArea(position)) { 7239 return items; 7240 } 7241 var evaluationFunc = function evaluationFunc(element, datasetIndex, index) { 7242 if (!includeInvisible && !_isPointInArea(element, chart.chartArea, 0)) { 7243 return; 7244 } 7245 if (element.inRange(position.x, position.y, useFinalPosition)) { 7246 items.push({ 7247 element: element, 7248 datasetIndex: datasetIndex, 7249 index: index 7250 }); 7251 } 7252 }; 7253 evaluateInteractionItems(chart, axis, position, evaluationFunc, true); 7254 return items; 7255 } 7256 function getNearestRadialItems(chart, position, axis, useFinalPosition) { 7257 var items = []; 7258 function evaluationFunc(element, datasetIndex, index) { 7259 var _element$getProps = element.getProps(['startAngle', 'endAngle'], useFinalPosition), 7260 startAngle = _element$getProps.startAngle, 7261 endAngle = _element$getProps.endAngle; 7262 var _getAngleFromPoint = getAngleFromPoint(element, { 7263 x: position.x, 7264 y: position.y 7265 }), 7266 angle = _getAngleFromPoint.angle; 7267 if (_angleBetween(angle, startAngle, endAngle)) { 7268 items.push({ 7269 element: element, 7270 datasetIndex: datasetIndex, 7271 index: index 7272 }); 7273 } 7274 } 7275 evaluateInteractionItems(chart, axis, position, evaluationFunc); 7276 return items; 7277 } 7278 function getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) { 7279 var items = []; 7280 var distanceMetric = getDistanceMetricForAxis(axis); 7281 var minDistance = Number.POSITIVE_INFINITY; 7282 function evaluationFunc(element, datasetIndex, index) { 7283 var inRange = element.inRange(position.x, position.y, useFinalPosition); 7284 if (intersect && !inRange) { 7285 return; 7286 } 7287 var center = element.getCenterPoint(useFinalPosition); 7288 var pointInArea = !!includeInvisible || chart.isPointInArea(center); 7289 if (!pointInArea && !inRange) { 7290 return; 7291 } 7292 var distance = distanceMetric(position, center); 7293 if (distance < minDistance) { 7294 items = [{ 7295 element: element, 7296 datasetIndex: datasetIndex, 7297 index: index 7298 }]; 7299 minDistance = distance; 7300 } else if (distance === minDistance) { 7301 items.push({ 7302 element: element, 7303 datasetIndex: datasetIndex, 7304 index: index 7305 }); 7306 } 7307 } 7308 evaluateInteractionItems(chart, axis, position, evaluationFunc); 7309 return items; 7310 } 7311 function getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) { 7312 if (!includeInvisible && !chart.isPointInArea(position)) { 7313 return []; 7314 } 7315 return axis === 'r' && !intersect ? getNearestRadialItems(chart, position, axis, useFinalPosition) : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible); 7316 } 7317 function getAxisItems(chart, position, axis, intersect, useFinalPosition) { 7318 var items = []; 7319 var rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange'; 7320 var intersectsItem = false;
7321 evaluateInteractionItems(chart, axis, position, function (element, datasetIndex, index) { 7322 if (element[rangeMethod] && element[rangeMethod](position[axis], useFinalPosition)) { 7323 items.push({ 7324 element: element, 7325 datasetIndex: datasetIndex, 7326 index: index 7327 }); 7328 intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition); 7329 } 7330 }); 7331 if (intersect && !intersectsItem) { 7332 return []; 7333 } 7334 return items; 7335 } 7336 var Interaction = { 7337 evaluateInteractionItems: evaluateInteractionItems, 7338 modes: { 7339 index: function index(chart, e, options, useFinalPosition) { 7340 var position = getRelativePosition(e, chart); 7341 var axis = options.axis || 'x'; 7342 var includeInvisible = options.includeInvisible || false; 7343 var items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible); 7344 var elements = []; 7345 if (!items.length) { 7346 return []; 7347 } 7348 chart.getSortedVisibleDatasetMetas().forEach(function (meta) { 7349 var index = items[0].index; 7350 var element = meta.data[index]; 7351 if (element && !element.skip) { 7352 elements.push({ 7353 element: element, 7354 datasetIndex: meta.index, 7355 index: index 7356 }); 7357 } 7358 }); 7359 return elements; 7360 }, 7361 dataset: function dataset(chart, e, options, useFinalPosition) { 7362 var position = getRelativePosition(e, chart); 7363 var axis = options.axis || 'xy'; 7364 var includeInvisible = options.includeInvisible || false; 7365 var items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible); 7366 if (items.length > 0) { 7367 var datasetIndex = items[0].datasetIndex; 7368 var data = chart.getDatasetMeta(datasetIndex).data; 7369 items = []; 7370 for (var i = 0; i < data.length; ++i) { 7371 items.push({ 7372 element: data[i], 7373 datasetIndex: datasetIndex, 7374 index: i 7375 }); 7376 } 7377 } 7378 return items; 7379 }, 7380 point: function point(chart, e, options, useFinalPosition) { 7381 var position = getRelativePosition(e, chart); 7382 var axis = options.axis || 'xy'; 7383 var includeInvisible = options.includeInvisible || false; 7384 return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible); 7385 }, 7386 nearest: function nearest(chart, e, options, useFinalPosition) { 7387 var position = getRelativePosition(e, chart); 7388 var axis = options.axis || 'xy'; 7389 var includeInvisible = options.includeInvisible || false; 7390 return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible); 7391 }, 7392 x: function x(chart, e, options, useFinalPosition) { 7393 var position = getRelativePosition(e, chart); 7394 return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition); 7395 }, 7396 y: function y(chart, e, options, useFinalPosition) { 7397 var position = getRelativePosition(e, chart); 7398 return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition); 7399 } 7400 } 7401 }; 7402 var STATIC_POSITIONS = ['left', 'top', 'right', 'bottom']; 7403 function filterByPosition(array, position) { 7404 return array.filter(function (v) { 7405 return v.pos === position; 7406 }); 7407 } 7408 function filterDynamicPositionByAxis(array, axis) { 7409 return array.filter(function (v) { 7410 return STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis; 7411 }); 7412 } 7413 function sortByWeight(array, reverse) { 7414 return array.sort(function (a, b) { 7415 var v0 = reverse ? b : a; 7416 var v1 = reverse ? a : b; 7417 return v0.weight === v1.weight ? v0.index - v1.index : v0.weight - v1.weight; 7418 }); 7419 } 7420 function wrapBoxes(boxes) { 7421 var layoutBoxes = []; 7422 var i, ilen, box, pos, stack, stackWeight; 7423 for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) { 7424 box = boxes[i]; 7425 var _box = box; 7426 pos = _box.position; 7427 var _box$options = _box.options; 7428 stack = _box$options.stack; 7429 var _box$options$stackWei = _box$options.stackWeight; 7430 stackWeight = _box$options$stackWei === void 0 ? 1 : _box$options$stackWei; 7431 layoutBoxes.push({ 7432 index: i, 7433 box: box, 7434 pos: pos, 7435 horizontal: box.isHorizontal(), 7436 weight: box.weight, 7437 stack: stack && pos + stack, 7438 stackWeight: stackWeight 7439 }); 7440 } 7441 return layoutBoxes; 7442 } 7443 function buildStacks(layouts) { 7444 var stacks = {}; 7445 var _iterator6 = _createForOfIteratorHelper$1(layouts), 7446 _step6; 7447 try { 7448 for (_iterator6.s();
7448 !(_step6 = _iterator6.n()).done;) { 7449 var wrap = _step6.value; 7450 var stack = wrap.stack, 7451 pos = wrap.pos, 7452 stackWeight = wrap.stackWeight; 7453 if (!stack || !STATIC_POSITIONS.includes(pos)) { 7454 continue; 7455 } 7456 var _stack = stacks[stack] || (stacks[stack] = { 7457 count: 0, 7458 placed: 0, 7459 weight: 0, 7460 size: 0 7461 }); 7462 _stack.count++; 7463 _stack.weight += stackWeight; 7464 } 7465 } catch (err) { 7466 _iterator6.e(err); 7467 } finally { 7468 _iterator6.f(); 7469 } 7470 return stacks; 7471 } 7472 function setLayoutDims(layouts, params) { 7473 var stacks = buildStacks(layouts); 7474 var vBoxMaxWidth = params.vBoxMaxWidth, 7475 hBoxMaxHeight = params.hBoxMaxHeight; 7476 var i, ilen, layout; 7477 for (i = 0, ilen = layouts.length; i < ilen; ++i) { 7478 layout = layouts[i]; 7479 var fullSize = layout.box.fullSize; 7480 var stack = stacks[layout.stack]; 7481 var factor = stack && layout.stackWeight / stack.weight; 7482 if (layout.horizontal) { 7483 layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth; 7484 layout.height = hBoxMaxHeight; 7485 } else { 7486 layout.width = vBoxMaxWidth; 7487 layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight; 7488 } 7489 } 7490 return stacks; 7491 } 7492 function buildLayoutBoxes(boxes) { 7493 var layoutBoxes = wrapBoxes(boxes); 7494 var fullSize = sortByWeight(layoutBoxes.filter(function (wrap) { 7495 return wrap.box.fullSize; 7496 }), true); 7497 var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true); 7498 var right = sortByWeight(filterByPosition(layoutBoxes, 'right')); 7499 var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true); 7500 var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
vendor: 4,161 bytes, lines 7501-7615
7501 var centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x'); 7502 var centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y'); 7503 return { 7504 fullSize: fullSize, 7505 leftAndTop: left.concat(top), 7506 rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal), 7507 chartArea: filterByPosition(layoutBoxes, 'chartArea'), 7508 vertical: left.concat(right).concat(centerVertical), 7509 horizontal: top.concat(bottom).concat(centerHorizontal) 7510 }; 7511 } 7512 function getCombinedMax(maxPadding, chartArea, a, b) { 7513 return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]); 7514 } 7515 function updateMaxPadding(maxPadding, boxPadding) { 7516 maxPadding.top = Math.max(maxPadding.top, boxPadding.top); 7517 maxPadding.left = Math.max(maxPadding.left, boxPadding.left); 7518 maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom); 7519 maxPadding.right = Math.max(maxPadding.right, boxPadding.right); 7520 } 7521 function updateDims(chartArea, params, layout, stacks) { 7522 var pos = layout.pos, 7523 box = layout.box; 7524 var maxPadding = chartArea.maxPadding; 7525 if (!isObject(pos)) { 7526 if (layout.size) { 7527 chartArea[pos] -= layout.size; 7528 } 7529 var stack = stacks[layout.stack] || { 7530 size: 0, 7531 count: 1 7532 }; 7533 stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width); 7534 layout.size = stack.size / stack.count; 7535 chartArea[pos] += layout.size; 7536 } 7537 if (box.getPadding) { 7538 updateMaxPadding(maxPadding, box.getPadding()); 7539 } 7540 var newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right')); 7541 var newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom')); 7542 var widthChanged = newWidth !== chartArea.w; 7543 var heightChanged = newHeight !== chartArea.h; 7544 chartArea.w = newWidth; 7545 chartArea.h = newHeight; 7546 return layout.horizontal ? { 7547 same: widthChanged, 7548 other: heightChanged 7549 } : { 7550 same: heightChanged, 7551 other: widthChanged 7552 }; 7553 } 7554 function handleMaxPadding(chartArea) { 7555 var maxPadding = chartArea.maxPadding; 7556 function updatePos(pos) { 7557 var change = Math.max(maxPadding[pos] - chartArea[pos], 0); 7558 chartArea[pos] += change; 7559 return change; 7560 } 7561 chartArea.y += updatePos('top'); 7562 chartArea.x += updatePos('left'); 7563 updatePos('right'); 7564 updatePos('bottom'); 7565 } 7566 function getMargins(horizontal, chartArea) { 7567 var maxPadding = chartArea.maxPadding; 7568 function marginForPositions(positions) { 7569 var margin = { 7570 left: 0, 7571 top: 0, 7572 right: 0, 7573 bottom: 0 7574 }; 7575 positions.forEach(function (pos) { 7576 margin[pos] = Math.max(chartArea[pos], maxPadding[pos]); 7577 }); 7578 return margin; 7579 } 7580 return horizontal ? marginForPositions(['left', 'right']) : marginForPositions(['top', 'bottom']); 7581 } 7582 function fitBoxes(boxes, chartArea, params, stacks) { 7583 var refitBoxes = []; 7584 var i, ilen, layout, box, refit, changed; 7585 for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) { 7586 layout = boxes[i]; 7587 box = layout.box; 7588 box.update(layout.width || chartArea.w, layout.height || chartArea.h, getMargins(layout.horizontal, chartArea)); 7589 var _updateDims = updateDims(chartArea, params, layout, stacks), 7590 same = _updateDims.same, 7591 other = _updateDims.other; 7592 refit |= same && refitBoxes.length; 7593 changed = changed || other; 7594 if (!box.fullSize) { 7595 refitBoxes.push(layout); 7596 } 7597 } 7598 return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed; 7599 } 7600 function setBoxDims(box, left, top, width, height) { 7601 box.top = top; 7602 box.left = left; 7603 box.right = left + width; 7604 box.bottom = top + height; 7605 box.width = width; 7606 box.height = height; 7607 } 7608 function placeBoxes(boxes, chartArea, params, stacks) { 7609 var userPadding = params.padding; 7610 var x = chartArea.x, 7611 y = chartArea.y; 7612 var _iterator7 = _createForOfIteratorHelper$1(boxes), 7613 _step7; 7614 try { 7615 for (_iterator7.s();
7615 !(_step7 = _iterator7.n()).done;) { 7616 var layout = _step7.value; 7617 var box = layout.box; 7618 var stack = stacks[layout.stack] || { 7619 count: 1, 7620 placed: 0, 7621 weight: 1 7622 }; 7623 var weight = layout.stackWeight / stack.weight || 1; 7624 if (layout.horizontal) { 7625 var width = chartArea.w * weight; 7626 var height = stack.size || box.height; 7627 if (defined(stack.start)) { 7628 y = stack.start; 7629 } 7630 if (box.fullSize) { 7631 setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height); 7632 } else { 7633 setBoxDims(box, chartArea.left + stack.placed, y, width, height); 7634 } 7635 stack.start = y; 7636 stack.placed += width; 7637 y = box.bottom; 7638 } else { 7639 var _height = chartArea.h * weight; 7640 var _width = stack.size || box.width; 7641 if (defined(stack.start)) { 7642 x = stack.start; 7643 } 7644 if (box.fullSize) { 7645 setBoxDims(box, x, userPadding.top, _width, params.outerHeight - userPadding.bottom - userPadding.top); 7646 } else { 7647 setBoxDims(box, x, chartArea.top + stack.placed, _width, _height); 7648 } 7649 stack.start = x; 7650 stack.placed += _height; 7651 x = box.right; 7652 } 7653 } 7654 } catch (err) { 7655 _iterator7.e(err); 7656 } finally { 7657 _iterator7.f(); 7658 } 7659 chartArea.x = x; 7660 chartArea.y = y; 7661 } 7662 var layouts = { 7663 addBox: function addBox(chart, item) { 7664 if (!chart.boxes) { 7665 chart.boxes = []; 7666 } 7667 item.fullSize = item.fullSize || false; 7668 item.position = item.position || 'top'; 7669 item.weight = item.weight || 0; 7670 item._layers = item._layers || function () { 7671 return [{ 7672 z: 0, 7673 draw: function draw(chartArea) { 7674 item.draw(chartArea); 7675 } 7676 }]; 7677 }; 7678 chart.boxes.push(item); 7679 }, 7680 removeBox: function removeBox(chart, layoutItem) { 7681 var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1; 7682 if (index !== -1) { 7683 chart.boxes.splice(index, 1); 7684 } 7685 }, 7686 configure: function configure(chart, item, options) { 7687 item.fullSize = options.fullSize; 7688 item.position = options.position; 7689 item.weight = options.weight; 7690 }, 7691 update: function update(chart, width, height, minPadding) { 7692 if (!chart) { 7693 return; 7694 } 7695 var padding = toPadding(chart.options.layout.padding); 7696 var availableWidth = Math.max(width - padding.width, 0); 7697 var availableHeight = Math.max(height - padding.height, 0); 7698 var boxes = buildLayoutBoxes(chart.boxes); 7699 var verticalBoxes = boxes.vertical; 7700 var horizontalBoxes = boxes.horizontal; 7701 each(chart.boxes, function (box) { 7702 if (typeof box.beforeLayout === 'function') { 7703 box.beforeLayout(); 7704 } 7705 }); 7706 var visibleVerticalBoxCount = verticalBoxes.reduce(function (total, wrap) { 7707 return wrap.box.options && wrap.box.options.display === false ? total : total + 1; 7708 }, 0) || 1; 7709 var params = Object.freeze({ 7710 outerWidth: width, 7711 outerHeight: height, 7712 padding: padding, 7713 availableWidth: availableWidth, 7714 availableHeight: availableHeight, 7715 vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount, 7716 hBoxMaxHeight: availableHeight / 2 7717 }); 7718 var maxPadding = Object.assign({}, padding); 7719 updateMaxPadding(maxPadding, toPadding(minPadding)); 7720 var chartArea = Object.assign({ 7721 maxPadding: maxPadding, 7722 w: availableWidth, 7723 h: availableHeight, 7724 x: padding.left, 7725 y: padding.top 7726 }, padding); 7727 var stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params); 7728 fitBoxes(boxes.fullSize, chartArea, params, stacks); 7729 fitBoxes(verticalBoxes, chartArea, params, stacks); 7730 if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) { 7731 fitBoxes(verticalBoxes, chartArea, params, stacks); 7732 } 7733 handleMaxPadding(chartArea); 7734 placeBoxes(boxes.leftAndTop, chartArea, params, stacks); 7735 chartArea.x += chartArea.w; 7736 chartArea.y += chartArea.h; 7737 placeBoxes(boxes.rightAndBottom, chartArea, params, stacks); 7738 chart.chartArea = { 7739 left: chartArea.left, 7740 top: chartArea.top, 7741 right: chartArea.left + chartArea.w, 7742 bottom: chartArea.top + chartArea.h, 7743 height: chartArea.h, 7744 width: chartArea.w 7745 }; 7746 each(boxes.chartArea, function (layout) { 7747 var box = layout.box; 7748 Object.assign(box, chart.chartArea); 7749 box.update(chartArea.w, chartArea.h, { 7750 left: 0, 7751 top: 0, 7752 right: 0, 7753 bottom: 0 7754 }); 7755 }); 7756 } 7757 }; 7758 var BasePlatform = /*#__PURE__*/function () { 7759 function BasePlatform() { 7760 _classCallCheck$1(this, BasePlatform); 7761 } 7762 return _createClass$1(BasePlatform, [{ 7763 key: "acquireContext", 7764 value: function acquireContext(canvas, aspectRatio) {} 7765 }, {
7766 key: "releaseContext", 7767 value: function releaseContext(context) { 7768 return false; 7769 } 7770 }, { 7771 key: "addEventListener", 7772 value: function addEventListener(chart, type, listener) {} 7773 }, { 7774 key: "removeEventListener", 7775 value: function removeEventListener(chart, type, listener) {} 7776 }, { 7777 key: "getDevicePixelRatio", 7778 value: function getDevicePixelRatio() { 7779 return 1; 7780 } 7781 }, { 7782 key: "getMaximumSize", 7783 value: function getMaximumSize(element, width, height, aspectRatio) { 7784 width = Math.max(0, width || element.width); 7785 height = height || element.height; 7786 return { 7787 width: width, 7788 height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height) 7789 }; 7790 } 7791 }, { 7792 key: "isAttached", 7793 value: function isAttached(canvas) { 7794 return true; 7795 } 7796 }, { 7797 key: "updateConfig", 7798 value: function updateConfig(config) {} 7799 }]); 7800 }(); 7801 var BasicPlatform = /*#__PURE__*/function (_BasePlatform) { 7802 function BasicPlatform() { 7803 _classCallCheck$1(this, BasicPlatform); 7804 return _callSuper(this, BasicPlatform, arguments); 7805 } 7806 _inherits$1(BasicPlatform, _BasePlatform); 7807 return _createClass$1(BasicPlatform, [{ 7808 key: "acquireContext", 7809 value: function acquireContext(item) { 7810 return item && item.getContext && item.getContext('2d') || null; 7811 } 7812 }, { 7813 key: "updateConfig", 7814 value: function updateConfig(config) { 7815 config.options.animation = false; 7816 } 7817 }]); 7818 }(BasePlatform); 7819 var EXPANDO_KEY = '$chartjs'; 7820 var EVENT_TYPES = { 7821 touchstart: 'mousedown', 7822 touchmove: 'mousemove', 7823 touchend: 'mouseup', 7824 pointerenter: 'mouseenter', 7825 pointerdown: 'mousedown', 7826 pointermove: 'mousemove', 7827 pointerup: 'mouseup', 7828 pointerleave: 'mouseout', 7829 pointerout: 'mouseout' 7830 }; 7831 var isNullOrEmpty = function isNullOrEmpty(value) { 7832 return value === null || value === ''; 7833 }; 7834 function initCanvas(canvas, aspectRatio) { 7835 var style = canvas.style; 7836 var renderHeight = canvas.getAttribute('height'); 7837 var renderWidth = canvas.getAttribute('width'); 7838 canvas[EXPANDO_KEY] = { 7839 initial: { 7840 height: renderHeight, 7841 width: renderWidth, 7842 style: { 7843 display: style.display, 7844 height: style.height, 7845 width: style.width 7846 } 7847 } 7848 }; 7849 style.display = style.display || 'block'; 7850 style.boxSizing = style.boxSizing || 'border-box'; 7851 if (isNullOrEmpty(renderWidth)) { 7852 var displayWidth = readUsedSize(canvas, 'width'); 7853 if (displayWidth !== undefined) { 7854 canvas.width = displayWidth; 7855 } 7856 } 7857 if (isNullOrEmpty(renderHeight)) { 7858 if (canvas.style.height === '') { 7859 canvas.height = canvas.width / (aspectRatio || 2); 7860 } else { 7861 var displayHeight = readUsedSize(canvas, 'height'); 7862 if (displayHeight !== undefined) { 7863 canvas.height = displayHeight; 7864 } 7865 } 7866 } 7867 return canvas; 7868 } 7869 var eventListenerOptions = supportsEventListenerOptions ? { 7870 passive: true 7871 } : false; 7872 function addListener(node, type, listener) { 7873 if (node) { 7874 node.addEventListener(type, listener, eventListenerOptions); 7875 } 7876 } 7877 function removeListener(chart, type, listener) { 7878 if (chart && chart.canvas) { 7879 chart.canvas.removeEventListener(type, listener, eventListenerOptions); 7880 } 7881 } 7882 function fromNativeEvent(event, chart) { 7883 var type = EVENT_TYPES[event.type] || event.type; 7884 var _getRelativePosition = getRelativePosition(event, chart), 7885 x = _getRelativePosition.x, 7886 y = _getRelativePosition.y; 7887 return { 7888 type: type, 7889 chart: chart, 7890 "native": event, 7891 x: x !== undefined ? x : null, 7892 y: y !== undefined ? y : null 7893 }; 7894 } 7895 function nodeListContains(nodeList, canvas) { 7896 var _iterator8 = _createForOfIteratorHelper$1(nodeList), 7897 _step8; 7898 try { 7899 for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) { 7900 var node = _step8.value; 7901 if (node === canvas || node.contains(canvas)) { 7902 return true; 7903 } 7904 } 7905 } catch (err) { 7906 _iterator8.e(err); 7907 } finally { 7908 _iterator8.f(); 7909 } 7910 } 7911 function createAttachObserver(chart, type, listener) { 7912 var canvas = chart.canvas; 7913 var observer = new MutationObserver(function (entries) { 7914 var trigger = false;
7915 var _iterator9 = _createForOfIteratorHelper$1(entries), 7916 _step9; 7917 try { 7918 for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) { 7919 var entry = _step9.value; 7920 trigger = trigger || nodeListContains(entry.addedNodes, canvas); 7921 trigger = trigger && !nodeListContains(entry.removedNodes, canvas); 7922 } 7923 } catch (err) { 7924 _iterator9.e(err); 7925 } finally { 7926 _iterator9.f(); 7927 } 7928 if (trigger) { 7929 listener(); 7930 } 7931 }); 7932 observer.observe(document, { 7933 childList: true, 7934 subtree: true 7935 }); 7936 return observer; 7937 } 7938 function createDetachObserver(chart, type, listener) { 7939 var canvas = chart.canvas; 7940 var observer = new MutationObserver(function (entries) { 7941 var trigger = false; 7942 var _iterator0 = _createForOfIteratorHelper$1(entries), 7943 _step0; 7944 try { 7945 for (_iterator0.s(); !(_step0 = _iterator0.n()).done;) { 7946 var entry = _step0.value; 7947 trigger = trigger || nodeListContains(entry.removedNodes, canvas); 7948 trigger = trigger && !nodeListContains(entry.addedNodes, canvas); 7949 } 7950 } catch (err) { 7951 _iterator0.e(err); 7952 } finally { 7953 _iterator0.f(); 7954 } 7955 if (trigger) { 7956 listener(); 7957 } 7958 }); 7959 observer.observe(document, { 7960 childList: true, 7961 subtree: true 7962 }); 7963 return observer; 7964 } 7965 var drpListeningCharts = new Map(); 7966 var oldDevicePixelRatio = 0; 7967 function onWindowResize() { 7968 var dpr = window.devicePixelRatio; 7969 if (dpr === oldDevicePixelRatio) { 7970 return; 7971 } 7972 oldDevicePixelRatio = dpr; 7973 drpListeningCharts.forEach(function (resize, chart) { 7974 if (chart.currentDevicePixelRatio !== dpr) { 7975 resize(); 7976 } 7977 }); 7978 } 7979 function listenDevicePixelRatioChanges(chart, resize) { 7980 if (!drpListeningCharts.size) { 7981 window.addEventListener('resize', onWindowResize); 7982 } 7983 drpListeningCharts.set(chart, resize); 7984 } 7985 function unlistenDevicePixelRatioChanges(chart) { 7986 drpListeningCharts["delete"](chart); 7987 if (!drpListeningCharts.size) { 7988 window.removeEventListener('resize', onWindowResize); 7989 } 7990 } 7991 function createResizeObserver(chart, type, listener) { 7992 var canvas = chart.canvas; 7993 var container = canvas && _getParentNode(canvas); 7994 if (!container) { 7995 return; 7996 } 7997 var resize = throttled(function (width, height) { 7998 var w = container.clientWidth; 7999 listener(width, height); 8000 if (w < container.clientWidth) { 8001 listener(); 8002 } 8003 }, window); 8004 var observer = new ResizeObserver(function (entries) { 8005 var entry = entries[0]; 8006 var width = entry.contentRect.width; 8007 var height = entry.contentRect.height; 8008 if (width === 0 && height === 0) { 8009 return; 8010 } 8011 resize(width, height); 8012 }); 8013 observer.observe(container); 8014 listenDevicePixelRatioChanges(chart, resize); 8015 return observer; 8016 } 8017 function releaseObserver(chart, type, observer) { 8018 if (observer) { 8019 observer.disconnect(); 8020 } 8021 if (type === 'resize') { 8022 unlistenDevicePixelRatioChanges(chart); 8023 } 8024 } 8025 function createProxyAndListen(chart, type, listener) { 8026 var canvas = chart.canvas; 8027 var proxy = throttled(function (event) { 8028 if (chart.ctx !== null) { 8029 listener(fromNativeEvent(event, chart)); 8030 } 8031 }, chart); 8032 addListener(canvas, type, proxy); 8033 return proxy; 8034 } 8035 var DomPlatform = /*#__PURE__*/function (_BasePlatform2) { 8036 function DomPlatform() { 8037 _classCallCheck$1(this, DomPlatform); 8038 return _callSuper(this, DomPlatform, arguments); 8039 } 8040 _inherits$1(DomPlatform, _BasePlatform2); 8041 return _createClass$1(DomPlatform, [{ 8042 key: "acquireContext", 8043 value: function acquireContext(canvas, aspectRatio) { 8044 var context = canvas && canvas.getContext && canvas.getContext('2d'); 8045 if (context && context.canvas === canvas) { 8046 initCanvas(canvas, aspectRatio); 8047 return context; 8048 } 8049 return null; 8050 } 8051 }, { 8052 key: "releaseContext", 8053 value: function releaseContext(context) { 8054 var canvas = context.canvas; 8055 if (!canvas[EXPANDO_KEY]) { 8056 return false;
8057 } 8058 var initial = canvas[EXPANDO_KEY].initial; 8059 ['height', 'width'].forEach(function (prop) { 8060 var value = initial[prop]; 8061 if (isNullOrUndef(value)) { 8062 canvas.removeAttribute(prop); 8063 } else { 8064 canvas.setAttribute(prop, value); 8065 } 8066 }); 8067 var style = initial.style || {}; 8068 Object.keys(style).forEach(function (key) { 8069 canvas.style[key] = style[key]; 8070 }); 8071 canvas.width = canvas.width; 8072 delete canvas[EXPANDO_KEY]; 8073 return true; 8074 } 8075 }, { 8076 key: "addEventListener", 8077 value: function addEventListener(chart, type, listener) { 8078 this.removeEventListener(chart, type); 8079 var proxies = chart.$proxies || (chart.$proxies = {}); 8080 var handlers = { 8081 attach: createAttachObserver, 8082 detach: createDetachObserver, 8083 resize: createResizeObserver 8084 }; 8085 var handler = handlers[type] || createProxyAndListen; 8086 proxies[type] = handler(chart, type, listener); 8087 } 8088 }, { 8089 key: "removeEventListener", 8090 value: function removeEventListener(chart, type) { 8091 var proxies = chart.$proxies || (chart.$proxies = {}); 8092 var proxy = proxies[type]; 8093 if (!proxy) { 8094 return; 8095 } 8096 var handlers = { 8097 attach: releaseObserver, 8098 detach: releaseObserver, 8099 resize: releaseObserver 8100 }; 8101 var handler = handlers[type] || removeListener; 8102 handler(chart, type, proxy); 8103 proxies[type] = undefined; 8104 } 8105 }, { 8106 key: "getDevicePixelRatio", 8107 value: function getDevicePixelRatio() { 8108 return window.devicePixelRatio; 8109 } 8110 }, { 8111 key: "getMaximumSize", 8112 value: function getMaximumSize$1(canvas, width, height, aspectRatio) { 8113 return getMaximumSize(canvas, width, height, aspectRatio); 8114 } 8115 }, { 8116 key: "isAttached", 8117 value: function isAttached(canvas) { 8118 var container = canvas && _getParentNode(canvas); 8119 return !!(container && container.isConnected); 8120 } 8121 }]); 8122 }(BasePlatform); 8123 function _detectPlatform(canvas) { 8124 if (!_isDomSupported() || typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) { 8125 return BasicPlatform; 8126 } 8127 return DomPlatform; 8128 } 8129 var Element = /*#__PURE__*/function () { 8130 function Element() { 8131 _classCallCheck$1(this, Element); 8132 _defineProperty$1(this, "x", void 0); 8133 _defineProperty$1(this, "y", void 0); 8134 _defineProperty$1(this, "active", false); 8135 _defineProperty$1(this, "options", void 0); 8136 _defineProperty$1(this, "$animations", void 0); 8137 } 8138 return _createClass$1(Element, [{ 8139 key: "tooltipPosition", 8140 value: function tooltipPosition(useFinalPosition) { 8141 var _this$getProps = this.getProps(['x', 'y'], useFinalPosition), 8142 x = _this$getProps.x, 8143 y = _this$getProps.y; 8144 return { 8145 x: x, 8146 y: y 8147 }; 8148 } 8149 }, { 8150 key: "hasValue", 8151 value: function hasValue() { 8152 return isNumber(this.x) && isNumber(this.y); 8153 } 8154 }, { 8155 key: "getProps", 8156 value: function getProps(props, _final) { 8157 var _this8 = this; 8158 var anims = this.$animations; 8159 if (!_final || !anims) { 8160 // let's not create an object, if not needed 8161 return this; 8162 } 8163 var ret = {}; 8164 props.forEach(function (prop) { 8165 ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : _this8[prop]; 8166 }); 8167 return ret; 8168 } 8169 }]); 8170 }(); 8171 _defineProperty$1(Element, "defaults", {}); 8172 _defineProperty$1(Element, "defaultRoutes", undefined); 8173 function autoSkip(scale, ticks) { 8174 var tickOpts = scale.options.ticks; 8175 var determinedMaxTicks = determineMaxTicks(scale); 8176 var ticksLimit = Math.min(tickOpts.maxTicksLimit || determinedMaxTicks, determinedMaxTicks); 8177 var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : []; 8178 var numMajorIndices = majorIndices.length; 8179 var first = majorIndices[0]; 8180 var last = majorIndices[numMajorIndices - 1]; 8181 var newTicks = []; 8182 if (numMajorIndices > ticksLimit) { 8183 skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit); 8184 return newTicks; 8185 } 8186 var spacing = calculateSpacing(majorIndices, ticks, ticksLimit); 8187 if (numMajorIndices > 0) { 8188 var i, ilen; 8189 var avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null; 8190 skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first); 8191 for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) { 8192 skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]); 8193 } 8194 skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing); 8195 return newTicks; 8196 } 8197 skip(ticks, newTicks, spacing); 8198 return newTicks; 8199 } 8200 function determineMaxTicks(scale) { 8201 var offset = scale.options.offset; 8202 var tickLength = scale._tickSize(); 8203 var maxScale = scale._length / tickLength + (offset ? 0 : 1); 8204 var maxChart = scale._maxLength / tickLength; 8205 return Math.floor(Math.min(maxScale, maxChart)); 8206 } 8207 function calculateSpacing(majorIndices, ticks, ticksLimit) { 8208 var evenMajorSpacing = getEvenSpacing(majorIndices); 8209 var spacing = ticks.length / ticksLimit; 8210 if (!evenMajorSpacing) { 8211 return Math.max(spacing, 1); 8212 } 8213 var factors = _factorize(evenMajorSpacing); 8214 for (var i = 0, ilen = factors.length - 1; i < ilen; i++) { 8215 var factor = factors[i]; 8216 if (factor > spacing) { 8217 return factor; 8218 } 8219 } 8220 return Math.max(spacing, 1); 8221 } 8222 function getMajorIndices(ticks) { 8223 var result = []; 8224 var i, ilen; 8225 for (i = 0, ilen = ticks.length; i < ilen; i++) { 8226 if (ticks[i].major) { 8227 result.push(i); 8228 } 8229 } 8230 return result; 8231 } 8232 function skipMajors(ticks, newTicks, majorIndices, spacing) { 8233 var count = 0; 8234 var next = majorIndices[0]; 8235 var i;
8236 spacing = Math.ceil(spacing); 8237 for (i = 0; i < ticks.length; i++) { 8238 if (i === next) { 8239 newTicks.push(ticks[i]); 8240 count++; 8241 next = majorIndices[count * spacing]; 8242 } 8243 } 8244 } 8245 function skip(ticks, newTicks, spacing, majorStart, majorEnd) { 8246 var start = valueOrDefault(majorStart, 0); 8247 var end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length); 8248 var count = 0; 8249 var length, i, next; 8250 spacing = Math.ceil(spacing); 8251 if (majorEnd) { 8252 length = majorEnd - majorStart; 8253 spacing = length / Math.floor(length / spacing); 8254 } 8255 next = start; 8256 while (next < 0) { 8257 count++; 8258 next = Math.round(start + count * spacing); 8259 } 8260 for (i = Math.max(start, 0); i < end; i++) { 8261 if (i === next) { 8262 newTicks.push(ticks[i]); 8263 count++; 8264 next = Math.round(start + count * spacing); 8265 } 8266 } 8267 } 8268 function getEvenSpacing(arr) { 8269 var len = arr.length; 8270 var i, diff; 8271 if (len < 2) { 8272 return false; 8273 } 8274 for (diff = arr[0], i = 1; i < len; ++i) { 8275 if (arr[i] - arr[i - 1] !== diff) { 8276 return false; 8277 } 8278 } 8279 return diff; 8280 } 8281 var reverseAlign = function reverseAlign(align) { 8282 return align === 'left' ? 'right' : align === 'right' ? 'left' : align; 8283 }; 8284 var offsetFromEdge = function offsetFromEdge(scale, edge, offset) { 8285 return edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset; 8286 }; 8287 var getTicksLimit = function getTicksLimit(ticksLength, maxTicksLimit) { 8288 return Math.min(maxTicksLimit || ticksLength, ticksLength); 8289 }; 8290 function sample(arr, numItems) { 8291 var result = []; 8292 var increment = arr.length / numItems; 8293 var len = arr.length; 8294 var i = 0; 8295 for (; i < len; i += increment) { 8296 result.push(arr[Math.floor(i)]); 8297 } 8298 return result; 8299 } 8300 function getPixelForGridLine(scale, index, offsetGridLines) { 8301 var length = scale.ticks.length; 8302 var validIndex = Math.min(index, length - 1); 8303 var start = scale._startPixel; 8304 var end = scale._endPixel; 8305 var epsilon = 1e-6; 8306 var lineValue = scale.getPixelForTick(validIndex); 8307 var offset; 8308 if (offsetGridLines) { 8309 if (length === 1) { 8310 offset = Math.max(lineValue - start, end - lineValue); 8311 } else if (index === 0) { 8312 offset = (scale.getPixelForTick(1) - lineValue) / 2; 8313 } else { 8314 offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2; 8315 } 8316 lineValue += validIndex < index ? offset : -offset; 8317 if (lineValue < start - epsilon || lineValue > end + epsilon) { 8318 return; 8319 } 8320 } 8321 return lineValue; 8322 } 8323 function garbageCollect(caches, length) { 8324 each(caches, function (cache) { 8325 var gc = cache.gc; 8326 var gcLen = gc.length / 2; 8327 var i; 8328 if (gcLen > length) { 8329 for (i = 0; i < gcLen; ++i) { 8330 delete cache.data[gc[i]]; 8331 } 8332 gc.splice(0, gcLen); 8333 } 8334 }); 8335 } 8336 function getTickMarkLength(options) { 8337 return options.drawTicks ? options.tickLength : 0; 8338 } 8339 function getTitleHeight(options, fallback) { 8340 if (!options.display) { 8341 return 0; 8342 } 8343 var font = toFont(options.font, fallback); 8344 var padding = toPadding(options.padding); 8345 var lines = isArray(options.text) ? options.text.length : 1; 8346 return lines * font.lineHeight + padding.height; 8347 } 8348 function createScaleContext(parent, scale) { 8349 return createContext(parent, { 8350 scale: scale, 8351 type: 'scale' 8352 }); 8353 } 8354 function createTickContext(parent, index, tick) { 8355 return createContext(parent, { 8356 tick: tick, 8357 index: index, 8358 type: 'tick' 8359 }); 8360 } 8361 function titleAlign(align, position, reverse) { 8362 var ret = _toLeftRightCenter(align); 8363 if (reverse && position !== 'right' || !reverse && position === 'right') { 8364 ret = reverseAlign(ret); 8365 } 8366 return ret; 8367 } 8368 function titleArgs(scale, offset, position, align) { 8369 var top = scale.top, 8370 left = scale.left, 8371 bottom = scale.bottom, 8372 right = scale.right, 8373 chart = scale.chart; 8374 var chartArea = chart.chartArea, 8375 scales = chart.scales; 8376 var rotation = 0; 8377 var maxWidth, titleX, titleY; 8378 var height = bottom - top; 8379 var width = right - left; 8380 if (scale.isHorizontal()) { 8381 titleX = _alignStartEnd(align, left, right); 8382 if (isObject(position)) { 8383 var positionAxisID = Object.keys(position)[0]; 8384 var value = position[positionAxisID]; 8385 titleY = scales[positionAxisID].getPixelForValue(value) + height - offset; 8386 } else if (position === 'center') { 8387 titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset; 8388 } else { 8389 titleY = offsetFromEdge(scale, position, offset); 8390 } 8391 maxWidth = right - left; 8392 } else { 8393 if (isObject(position)) { 8394 var _positionAxisID = Object.keys(position)[0]; 8395 var _value = position[_positionAxisID]; 8396 titleX = scales[_positionAxisID].getPixelForValue(_value) - width + offset; 8397 } else if (position === 'center') { 8398 titleX = (chartArea.left + chartArea.right) / 2 - width + offset; 8399 } else { 8400 titleX = offsetFromEdge(scale, position, offset); 8401 } 8402 titleY = _alignStartEnd(align, bottom, top); 8403 rotation = position === 'left' ? -HALF_PI : HALF_PI; 8404 } 8405 return { 8406 titleX: titleX, 8407 titleY: titleY, 8408 maxWidth: maxWidth, 8409 rotation: rotation 8410 }; 8411 } 8412 var Scale = /*#__PURE__*/function (_Element2) { 8413 function Scale(cfg) { 8414 var _this9; 8415 _classCallCheck$1(this, Scale); 8416 _this9 = _callSuper(this, Scale); 8417 _this9.id = cfg.id; 8418 _this9.type = cfg.type; 8419 _this9.options = undefined; 8420 _this9.ctx = cfg.ctx; 8421 _this9.chart = cfg.chart; 8422 _this9.top = undefined; 8423 _this9.bottom = undefined; 8424 _this9.left = undefined; 8425 _this9.right = undefined; 8426 _this9.width = undefined; 8427 _this9.height = undefined; 8428 _this9._margins = { 8429 left: 0, 8430 right: 0, 8431 top: 0, 8432 bottom: 0 8433 }; 8434 _this9.maxWidth = undefined; 8435 _this9.maxHeight = undefined; 8436 _this9.paddingTop = undefined; 8437 _this9.paddingBottom = undefined; 8438 _this9.paddingLeft = undefined; 8439 _this9.paddingRight = undefined; 8440 _this9.axis = undefined; 8441 _this9.labelRotation = undefined; 8442 _this9.min = undefined; 8443 _this9.max = undefined; 8444 _this9._range = undefined; 8445 _this9.ticks = []; 8446 _this9._gridLineItems = null; 8447 _this9._labelItems = null; 8448 _this9._labelSizes = null; 8449 _this9._length = 0; 8450 _this9._maxLength = 0; 8451 _this9._longestTextCache = {}; 8452 _this9._startPixel = undefined; 8453 _this9._endPixel = undefined; 8454 _this9._reversePixels = false;
8455 _this9._userMax = undefined; 8456 _this9._userMin = undefined; 8457 _this9._suggestedMax = undefined; 8458 _this9._suggestedMin = undefined; 8459 _this9._ticksLength = 0; 8460 _this9._borderValue = 0; 8461 _this9._cache = {}; 8462 _this9._dataLimitsCached = false; 8463 _this9.$context = undefined; 8464 return _this9; 8465 } 8466 _inherits$1(Scale, _Element2); 8467 return _createClass$1(Scale, [{ 8468 key: "init", 8469 value: function init(options) { 8470 this.options = options.setContext(this.getContext()); 8471 this.axis = options.axis; 8472 this._userMin = this.parse(options.min); 8473 this._userMax = this.parse(options.max); 8474 this._suggestedMin = this.parse(options.suggestedMin); 8475 this._suggestedMax = this.parse(options.suggestedMax); 8476 } 8477 }, { 8478 key: "parse", 8479 value: function parse(raw, index) { 8480 return raw; 8481 } 8482 }, { 8483 key: "getUserBounds", 8484 value: function getUserBounds() { 8485 var _userMin = this._userMin, 8486 _userMax = this._userMax, 8487 _suggestedMin = this._suggestedMin, 8488 _suggestedMax = this._suggestedMax; 8489 _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY); 8490 _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY); 8491 _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY); 8492 _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY); 8493 return { 8494 min: finiteOrDefault(_userMin, _suggestedMin), 8495 max: finiteOrDefault(_userMax, _suggestedMax), 8496 minDefined: isNumberFinite(_userMin), 8497 maxDefined: isNumberFinite(_userMax) 8498 }; 8499 } 8500 }, { 8501 key: "getMinMax", 8502 value: function getMinMax(canStack) { 8503 var _this$getUserBounds = this.getUserBounds(), 8504 min = _this$getUserBounds.min, 8505 max = _this$getUserBounds.max, 8506 minDefined = _this$getUserBounds.minDefined, 8507 maxDefined = _this$getUserBounds.maxDefined; 8508 var range; 8509 if (minDefined && maxDefined) { 8510 return { 8511 min: min, 8512 max: max 8513 }; 8514 } 8515 var metas = this.getMatchingVisibleMetas(); 8516 for (var i = 0, ilen = metas.length; i < ilen; ++i) { 8517 range = metas[i].controller.getMinMax(this, canStack); 8518 if (!minDefined) { 8519 min = Math.min(min, range.min); 8520 } 8521 if (!maxDefined) { 8522 max = Math.max(max, range.max); 8523 } 8524 } 8525 min = maxDefined && min > max ? max : min; 8526 max = minDefined && min > max ? min : max; 8527 return { 8528 min: finiteOrDefault(min, finiteOrDefault(max, min)), 8529 max: finiteOrDefault(max, finiteOrDefault(min, max)) 8530 }; 8531 } 8532 }, { 8533 key: "getPadding", 8534 value: function getPadding() { 8535 return { 8536 left: this.paddingLeft || 0, 8537 top: this.paddingTop || 0, 8538 right: this.paddingRight || 0, 8539 bottom: this.paddingBottom || 0 8540 }; 8541 } 8542 }, { 8543 key: "getTicks", 8544 value: function getTicks() { 8545 return this.ticks; 8546 } 8547 }, { 8548 key: "getLabels", 8549 value: function getLabels() { 8550 var data = this.chart.data; 8551 return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || []; 8552 } 8553 }, { 8554 key: "getLabelItems", 8555 value: function getLabelItems() { 8556 var chartArea = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.chart.chartArea; 8557 var items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea)); 8558 return items; 8559 } 8560 }, { 8561 key: "beforeLayout", 8562 value: function beforeLayout() { 8563 this._cache = {}; 8564 this._dataLimitsCached = false; 8565 } 8566 }, { 8567 key: "beforeUpdate", 8568 value: function beforeUpdate() { 8569 callback(this.options.beforeUpdate, [this]); 8570 } 8571 }, { 8572 key: "update", 8573 value: function update(maxWidth, maxHeight, margins) { 8574 var _this$options4 = this.options, 8575 beginAtZero = _this$options4.beginAtZero, 8576 grace = _this$options4.grace, 8577 tickOpts = _this$options4.ticks; 8578 var sampleSize = tickOpts.sampleSize; 8579 this.beforeUpdate(); 8580 this.maxWidth = maxWidth; 8581 this.maxHeight = maxHeight; 8582 this._margins = margins = Object.assign({ 8583 left: 0, 8584 right: 0, 8585 top: 0, 8586 bottom: 0 8587 }, margins); 8588 this.ticks = null; 8589 this._labelSizes = null; 8590 this._gridLineItems = null; 8591 this._labelItems = null; 8592 this.beforeSetDimensions(); 8593 this.setDimensions(); 8594 this.afterSetDimensions(); 8595 this._maxLength = this.isHorizontal() ? this.width + margins.left + margins.right : this.height + margins.top + margins.bottom; 8596 if (!this._dataLimitsCached) { 8597 this.beforeDataLimits(); 8598 this.determineDataLimits(); 8599 this.afterDataLimits(); 8600 this._range = _addGrace(this, grace, beginAtZero); 8601 this._dataLimitsCached = true; 8602 } 8603 this.beforeBuildTicks(); 8604 this.ticks = this.buildTicks() || []; 8605 this.afterBuildTicks(); 8606 var samplingEnabled = sampleSize < this.ticks.length; 8607 this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks); 8608 this.configure(); 8609 this.beforeCalculateLabelRotation(); 8610 this.calculateLabelRotation(); 8611 this.afterCalculateLabelRotation(); 8612 if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) { 8613 this.ticks = autoSkip(this, this.ticks); 8614 this._labelSizes = null; 8615 this.afterAutoSkip(); 8616 } 8617 if (samplingEnabled) { 8618 this._convertTicksToLabels(this.ticks); 8619 } 8620 this.beforeFit(); 8621 this.fit(); 8622 this.afterFit(); 8623 this.afterUpdate(); 8624 } 8625 }, {
8626 key: "configure", 8627 value: function configure() { 8628 var reversePixels = this.options.reverse; 8629 var startPixel, endPixel; 8630 if (this.isHorizontal()) { 8631 startPixel = this.left; 8632 endPixel = this.right; 8633 } else { 8634 startPixel = this.top; 8635 endPixel = this.bottom; 8636 reversePixels = !reversePixels; 8637 } 8638 this._startPixel = startPixel; 8639 this._endPixel = endPixel; 8640 this._reversePixels = reversePixels; 8641 this._length = endPixel - startPixel; 8642 this._alignToPixels = this.options.alignToPixels; 8643 } 8644 }, { 8645 key: "afterUpdate", 8646 value: function afterUpdate() { 8647 callback(this.options.afterUpdate, [this]); 8648 } 8649 }, { 8650 key: "beforeSetDimensions", 8651 value: function beforeSetDimensions() { 8652 callback(this.options.beforeSetDimensions, [this]); 8653 } 8654 }, { 8655 key: "setDimensions", 8656 value: function setDimensions() { 8657 if (this.isHorizontal()) { 8658 this.width = this.maxWidth; 8659 this.left = 0; 8660 this.right = this.width; 8661 } else { 8662 this.height = this.maxHeight; 8663 this.top = 0; 8664 this.bottom = this.height; 8665 } 8666 this.paddingLeft = 0; 8667 this.paddingTop = 0; 8668 this.paddingRight = 0; 8669 this.paddingBottom = 0; 8670 } 8671 }, { 8672 key: "afterSetDimensions", 8673 value: function afterSetDimensions() { 8674 callback(this.options.afterSetDimensions, [this]); 8675 } 8676 }, { 8677 key: "_callHooks", 8678 value: function _callHooks(name) { 8679 this.chart.notifyPlugins(name, this.getContext()); 8680 callback(this.options[name], [this]); 8681 } 8682 }, { 8683 key: "beforeDataLimits", 8684 value: function beforeDataLimits() { 8685 this._callHooks('beforeDataLimits'); 8686 } 8687 }, { 8688 key: "determineDataLimits", 8689 value: function determineDataLimits() {} 8690 }, { 8691 key: "afterDataLimits", 8692 value: function afterDataLimits() { 8693 this._callHooks('afterDataLimits'); 8694 } 8695 }, { 8696 key: "beforeBuildTicks", 8697 value: function beforeBuildTicks() { 8698 this._callHooks('beforeBuildTicks'); 8699 } 8700 }, { 8701 key: "buildTicks", 8702 value: function buildTicks() { 8703 return []; 8704 } 8705 }, { 8706 key: "afterBuildTicks", 8707 value: function afterBuildTicks() { 8708 this._callHooks('afterBuildTicks'); 8709 } 8710 }, { 8711 key: "beforeTickToLabelConversion", 8712 value: function beforeTickToLabelConversion() { 8713 callback(this.options.beforeTickToLabelConversion, [this]); 8714 } 8715 }, { 8716 key: "generateTickLabels", 8717 value: function generateTickLabels(ticks) { 8718 var tickOpts = this.options.ticks; 8719 var i, ilen, tick; 8720 for (i = 0, ilen = ticks.length; i < ilen; i++) { 8721 tick = ticks[i]; 8722 tick.label = callback(tickOpts.callback, [tick.value, i, ticks], this); 8723 } 8724 } 8725 }, { 8726 key: "afterTickToLabelConversion", 8727 value: function afterTickToLabelConversion() { 8728 callback(this.options.afterTickToLabelConversion, [this]); 8729 } 8730 }, { 8731 key: "beforeCalculateLabelRotation", 8732 value: function beforeCalculateLabelRotation() { 8733 callback(this.options.beforeCalculateLabelRotation, [this]); 8734 } 8735 }, { 8736 key: "calculateLabelRotation", 8737 value: function calculateLabelRotation() { 8738 var options = this.options; 8739 var tickOpts = options.ticks; 8740 var numTicks = getTicksLimit(this.ticks.length, options.ticks.maxTicksLimit); 8741 var minRotation = tickOpts.minRotation || 0; 8742 var maxRotation = tickOpts.maxRotation; 8743 var labelRotation = minRotation; 8744 var tickWidth, maxHeight, maxLabelDiagonal; 8745 if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) { 8746 this.labelRotation = minRotation; 8747 return; 8748 } 8749 var labelSizes = this._getLabelSizes(); 8750 var maxLabelWidth = labelSizes.widest.width; 8751 var maxLabelHeight = labelSizes.highest.height; 8752 var maxWidth = _limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth); 8753 tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1); 8754 if (maxLabelWidth + 6 > tickWidth) { 8755 tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1)); 8756 maxHeight = this.maxHeight - getTickMarkLength(options.grid) - tickOpts.padding - getTitleHeight(options.title, this.chart.options.font); 8757 maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight); 8758 labelRotation = toDegrees(Math.min(Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)), Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1)))); 8759 labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation)); 8760 } 8761 this.labelRotation = labelRotation; 8762 } 8763 }, {
8764 key: "afterCalculateLabelRotation", 8765 value: function afterCalculateLabelRotation() { 8766 callback(this.options.afterCalculateLabelRotation, [this]); 8767 } 8768 }, { 8769 key: "afterAutoSkip", 8770 value: function afterAutoSkip() {} 8771 }, { 8772 key: "beforeFit", 8773 value: function beforeFit() { 8774 callback(this.options.beforeFit, [this]); 8775 } 8776 }, { 8777 key: "fit", 8778 value: function fit() { 8779 var minSize = { 8780 width: 0, 8781 height: 0 8782 }; 8783 var chart = this.chart, 8784 _this$options5 = this.options, 8785 tickOpts = _this$options5.ticks, 8786 titleOpts = _this$options5.title, 8787 gridOpts = _this$options5.grid; 8788 var display = this._isVisible(); 8789 var isHorizontal = this.isHorizontal(); 8790 if (display) { 8791 var titleHeight = getTitleHeight(titleOpts, chart.options.font); 8792 if (isHorizontal) { 8793 minSize.width = this.maxWidth; 8794 minSize.height = getTickMarkLength(gridOpts) + titleHeight; 8795 } else { 8796 minSize.height = this.maxHeight; 8797 minSize.width = getTickMarkLength(gridOpts) + titleHeight; 8798 } 8799 if (tickOpts.display && this.ticks.length) { 8800 var _this$_getLabelSizes = this._getLabelSizes(), 8801 first = _this$_getLabelSizes.first, 8802 last = _this$_getLabelSizes.last, 8803 widest = _this$_getLabelSizes.widest, 8804 highest = _this$_getLabelSizes.highest; 8805 var tickPadding = tickOpts.padding * 2; 8806 var angleRadians = toRadians(this.labelRotation); 8807 var cos = Math.cos(angleRadians); 8808 var sin = Math.sin(angleRadians); 8809 if (isHorizontal) { 8810 var labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height; 8811 minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding); 8812 } else { 8813 var labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height; 8814 minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding); 8815 } 8816 this._calculatePadding(first, last, sin, cos); 8817 } 8818 } 8819 this._handleMargins(); 8820 if (isHorizontal) { 8821 this.width = this._length = chart.width - this._margins.left - this._margins.right; 8822 this.height = minSize.height; 8823 } else { 8824 this.width = minSize.width; 8825 this.height = this._length = chart.height - this._margins.top - this._margins.bottom; 8826 } 8827 } 8828 }, { 8829 key: "_calculatePadding", 8830 value: function _calculatePadding(first, last, sin, cos) { 8831 var _this$options6 = this.options, 8832 _this$options6$ticks = _this$options6.ticks, 8833 align = _this$options6$ticks.align, 8834 padding = _this$options6$ticks.padding, 8835 position = _this$options6.position; 8836 var isRotated = this.labelRotation !== 0; 8837 var labelsBelowTicks = position !== 'top' && this.axis === 'x'; 8838 if (this.isHorizontal()) { 8839 var offsetLeft = this.getPixelForTick(0) - this.left; 8840 var offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1); 8841 var paddingLeft = 0; 8842 var paddingRight = 0; 8843 if (isRotated) { 8844 if (labelsBelowTicks) { 8845 paddingLeft = cos * first.width; 8846 paddingRight = sin * last.height; 8847 } else { 8848 paddingLeft = sin * first.height; 8849 paddingRight = cos * last.width; 8850 } 8851 } else if (align === 'start') { 8852 paddingRight = last.width; 8853 } else if (align === 'end') { 8854 paddingLeft = first.width; 8855 } else if (align !== 'inner') { 8856 paddingLeft = first.width / 2; 8857 paddingRight = last.width / 2; 8858 } 8859 this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0); 8860 this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0); 8861 } else { 8862 var paddingTop = last.height / 2; 8863 var paddingBottom = first.height / 2; 8864 if (align === 'start') { 8865 paddingTop = 0; 8866 paddingBottom = first.height; 8867 } else if (align === 'end') { 8868 paddingTop = last.height; 8869 paddingBottom = 0; 8870 } 8871 this.paddingTop = paddingTop + padding; 8872 this.paddingBottom = paddingBottom + padding; 8873 } 8874 } 8875 }, {
8876 key: "_handleMargins", 8877 value: function _handleMargins() { 8878 if (this._margins) { 8879 this._margins.left = Math.max(this.paddingLeft, this._margins.left); 8880 this._margins.top = Math.max(this.paddingTop, this._margins.top); 8881 this._margins.right = Math.max(this.paddingRight, this._margins.right); 8882 this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom); 8883 } 8884 } 8885 }, { 8886 key: "afterFit", 8887 value: function afterFit() { 8888 callback(this.options.afterFit, [this]); 8889 } 8890 }, { 8891 key: "isHorizontal", 8892 value: function isHorizontal() { 8893 var _this$options7 = this.options, 8894 axis = _this$options7.axis, 8895 position = _this$options7.position; 8896 return position === 'top' || position === 'bottom' || axis === 'x'; 8897 } 8898 }, { 8899 key: "isFullSize", 8900 value: function isFullSize() { 8901 return this.options.fullSize; 8902 } 8903 }, { 8904 key: "_convertTicksToLabels", 8905 value: function _convertTicksToLabels(ticks) { 8906 this.beforeTickToLabelConversion(); 8907 this.generateTickLabels(ticks); 8908 var i, ilen; 8909 for (i = 0, ilen = ticks.length; i < ilen; i++) { 8910 if (isNullOrUndef(ticks[i].label)) { 8911 ticks.splice(i, 1); 8912 ilen--; 8913 i--; 8914 } 8915 } 8916 this.afterTickToLabelConversion(); 8917 } 8918 }, { 8919 key: "_getLabelSizes", 8920 value: function _getLabelSizes() { 8921 var labelSizes = this._labelSizes; 8922 if (!labelSizes) { 8923 var sampleSize = this.options.ticks.sampleSize; 8924 var ticks = this.ticks; 8925 if (sampleSize < ticks.length) { 8926 ticks = sample(ticks, sampleSize); 8927 } 8928 this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length, this.options.ticks.maxTicksLimit); 8929 } 8930 return labelSizes; 8931 } 8932 }, { 8933 key: "_computeLabelSizes", 8934 value: function _computeLabelSizes(ticks, length, maxTicksLimit) { 8935 var ctx = this.ctx, 8936 caches = this._longestTextCache; 8937 var widths = []; 8938 var heights = []; 8939 var increment = Math.floor(length / getTicksLimit(length, maxTicksLimit)); 8940 var widestLabelSize = 0; 8941 var highestLabelSize = 0; 8942 var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel; 8943 for (i = 0; i < length; i += increment) { 8944 label = ticks[i].label; 8945 tickFont = this._resolveTickFontOptions(i); 8946 ctx.font = fontString = tickFont.string; 8947 cache = caches[fontString] = caches[fontString] || { 8948 data: {}, 8949 gc: [] 8950 }; 8951 lineHeight = tickFont.lineHeight; 8952 width = height = 0; 8953 if (!isNullOrUndef(label) && !isArray(label)) { 8954 width = _measureText(ctx, cache.data, cache.gc, width, label); 8955 height = lineHeight; 8956 } else if (isArray(label)) { 8957 for (j = 0, jlen = label.length; j < jlen; ++j) { 8958 nestedLabel = label[j]; 8959 if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) { 8960 width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel); 8961 height += lineHeight; 8962 } 8963 } 8964 } 8965 widths.push(width); 8966 heights.push(height); 8967 widestLabelSize = Math.max(width, widestLabelSize); 8968 highestLabelSize = Math.max(height, highestLabelSize); 8969 } 8970 garbageCollect(caches, length); 8971 var widest = widths.indexOf(widestLabelSize); 8972 var highest = heights.indexOf(highestLabelSize); 8973 var valueAt = function valueAt(idx) { 8974 return { 8975 width: widths[idx] || 0, 8976 height: heights[idx] || 0 8977 }; 8978 }; 8979 return { 8980 first: valueAt(0), 8981 last: valueAt(length - 1), 8982 widest: valueAt(widest), 8983 highest: valueAt(highest), 8984 widths: widths, 8985 heights: heights 8986 }; 8987 } 8988 }, { 8989 key: "getLabelForValue", 8990 value: function getLabelForValue(value) { 8991 return value; 8992 } 8993 }, {
8994 key: "getPixelForValue", 8995 value: function getPixelForValue(value, index) { 8996 return NaN; 8997 } 8998 }, { 8999 key: "getValueForPixel", 9000 value: function getValueForPixel(pixel) {} 9001 }, { 9002 key: "getPixelForTick", 9003 value: function getPixelForTick(index) { 9004 var ticks = this.ticks; 9005 if (index < 0 || index > ticks.length - 1) { 9006 return null; 9007 } 9008 return this.getPixelForValue(ticks[index].value); 9009 } 9010 }, { 9011 key: "getPixelForDecimal", 9012 value: function getPixelForDecimal(decimal) { 9013 if (this._reversePixels) { 9014 decimal = 1 - decimal; 9015 } 9016 var pixel = this._startPixel + decimal * this._length; 9017 return _int16Range(this._alignToPixels ? _alignPixel(this.chart, pixel, 0) : pixel); 9018 } 9019 }, { 9020 key: "getDecimalForPixel", 9021 value: function getDecimalForPixel(pixel) { 9022 var decimal = (pixel - this._startPixel) / this._length; 9023 return this._reversePixels ? 1 - decimal : decimal; 9024 } 9025 }, { 9026 key: "getBasePixel", 9027 value: function getBasePixel() { 9028 return this.getPixelForValue(this.getBaseValue()); 9029 } 9030 }, { 9031 key: "getBaseValue", 9032 value: function getBaseValue() { 9033 var min = this.min, 9034 max = this.max; 9035 return min < 0 && max < 0 ? max : min > 0 && max > 0 ? min : 0; 9036 } 9037 }, { 9038 key: "getContext", 9039 value: function getContext(index) { 9040 var ticks = this.ticks || []; 9041 if (index >= 0 && index < ticks.length) { 9042 var tick = ticks[index]; 9043 return tick.$context || (tick.$context = createTickContext(this.getContext(), index, tick)); 9044 } 9045 return this.$context || (this.$context = createScaleContext(this.chart.getContext(), this)); 9046 } 9047 }, { 9048 key: "_tickSize", 9049 value: function _tickSize() { 9050 var optionTicks = this.options.ticks; 9051 var rot = toRadians(this.labelRotation); 9052 var cos = Math.abs(Math.cos(rot)); 9053 var sin = Math.abs(Math.sin(rot)); 9054 var labelSizes = this._getLabelSizes(); 9055 var padding = optionTicks.autoSkipPadding || 0; 9056 var w = labelSizes ? labelSizes.widest.width + padding : 0; 9057 var h = labelSizes ? labelSizes.highest.height + padding : 0; 9058 return this.isHorizontal() ? h * cos > w * sin ? w / cos : h / sin : h * sin < w * cos ? h / cos : w / sin; 9059 } 9060 }, { 9061 key: "_isVisible", 9062 value: function _isVisible() { 9063 var display = this.options.display; 9064 if (display !== 'auto') { 9065 return !!display; 9066 } 9067 return this.getMatchingVisibleMetas().length > 0; 9068 } 9069 }, { 9070 key: "_computeGridLineItems", 9071 value: function _computeGridLineItems(chartArea) { 9072 var axis = this.axis; 9073 var chart = this.chart; 9074 var options = this.options; 9075 var grid = options.grid, 9076 position = options.position, 9077 border = options.border; 9078 var offset = grid.offset; 9079 var isHorizontal = this.isHorizontal(); 9080 var ticks = this.ticks; 9081 var ticksLength = ticks.length + (offset ? 1 : 0); 9082 var tl = getTickMarkLength(grid); 9083 var items = []; 9084 var borderOpts = border.setContext(this.getContext()); 9085 var axisWidth = borderOpts.display ? borderOpts.width : 0; 9086 var axisHalfWidth = axisWidth / 2; 9087 var alignBorderValue = function alignBorderValue(pixel) { 9088 return _alignPixel(chart, pixel, axisWidth); 9089 }; 9090 var borderValue, i, lineValue, alignedLineValue; 9091 var tx1, ty1, tx2, ty2, x1, y1, x2, y2; 9092 if (position === 'top') { 9093 borderValue = alignBorderValue(this.bottom); 9094 ty1 = this.bottom - tl; 9095 ty2 = borderValue - axisHalfWidth; 9096 y1 = alignBorderValue(chartArea.top) + axisHalfWidth; 9097 y2 = chartArea.bottom; 9098 } else if (position === 'bottom') { 9099 borderValue = alignBorderValue(this.top); 9100 y1 = chartArea.top; 9101 y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth; 9102 ty1 = borderValue + axisHalfWidth; 9103 ty2 = this.top + tl; 9104 } else if (position === 'left') { 9105 borderValue = alignBorderValue(this.right); 9106 tx1 = this.right - tl; 9107 tx2 = borderValue - axisHalfWidth; 9108 x1 = alignBorderValue(chartArea.left) + axisHalfWidth; 9109 x2 = chartArea.right; 9110 } else if (position === 'right') { 9111 borderValue = alignBorderValue(this.left); 9112 x1 = chartArea.left; 9113 x2 = alignBorderValue(chartArea.right) - axisHalfWidth; 9114 tx1 = borderValue + axisHalfWidth; 9115 tx2 = this.left + tl; 9116 } else if (axis === 'x') { 9117 if (position === 'center') { 9118 borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5); 9119 } else if (isObject(position)) { 9120 var positionAxisID = Object.keys(position)[0]; 9121 var value = position[positionAxisID]; 9122 borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value)); 9123 } 9124 y1 = chartArea.top; 9125 y2 = chartArea.bottom; 9126 ty1 = borderValue + axisHalfWidth; 9127 ty2 = ty1 + tl; 9128 } else if (axis === 'y') { 9129 if (position === 'center') { 9130 borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2); 9131 } else if (isObject(position)) { 9132 var _positionAxisID2 = Object.keys(position)[0]; 9133 var _value2 = position[_positionAxisID2]; 9134 borderValue = alignBorderValue(this.chart.scales[_positionAxisID2].getPixelForValue(_value2)); 9135 } 9136 tx1 = borderValue - axisHalfWidth; 9137 tx2 = tx1 - tl; 9138 x1 = chartArea.left; 9139 x2 = chartArea.right; 9140 } 9141 var limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength); 9142 var step = Math.max(1, Math.ceil(ticksLength / limit)); 9143 for (i = 0; i < ticksLength; i += step) { 9144 var context = this.getContext(i); 9145 var optsAtIndex = grid.setContext(context); 9146 var optsAtIndexBorder = border.setContext(context); 9147 var lineWidth = optsAtIndex.lineWidth; 9148 var lineColor = optsAtIndex.color; 9149 var borderDash = optsAtIndexBorder.dash || []; 9150 var borderDashOffset = optsAtIndexBorder.dashOffset; 9151 var tickWidth = optsAtIndex.tickWidth; 9152 var tickColor = optsAtIndex.tickColor; 9153 var tickBorderDash = optsAtIndex.tickBorderDash || []; 9154 var tickBorderDashOffset = optsAtIndex.tickBorderDashOffset; 9155 lineValue = getPixelForGridLine(this, i, offset); 9156 if (lineValue === undefined) { 9157 continue; 9158 } 9159 alignedLineValue = _alignPixel(chart, lineValue, lineWidth); 9160 if (isHorizontal) { 9161 tx1 = tx2 = x1 = x2 = alignedLineValue; 9162 } else { 9163 ty1 = ty2 = y1 = y2 = alignedLineValue; 9164 } 9165 items.push({ 9166 tx1: tx1, 9167 ty1: ty1, 9168 tx2: tx2, 9169 ty2: ty2, 9170 x1: x1, 9171 y1: y1, 9172 x2: x2, 9173 y2: y2, 9174 width: lineWidth, 9175 color: lineColor, 9176 borderDash: borderDash, 9177 borderDashOffset: borderDashOffset, 9178 tickWidth: tickWidth, 9179 tickColor: tickColor, 9180 tickBorderDash: tickBorderDash, 9181 tickBorderDashOffset: tickBorderDashOffset 9182 }); 9183 } 9184 this._ticksLength = ticksLength; 9185 this._borderValue = borderValue; 9186 return items; 9187 } 9188 }, {
9189 key: "_computeLabelItems", 9190 value: function _computeLabelItems(chartArea) { 9191 var axis = this.axis; 9192 var options = this.options; 9193 var position = options.position, 9194 optionTicks = options.ticks; 9195 var isHorizontal = this.isHorizontal(); 9196 var ticks = this.ticks; 9197 var align = optionTicks.align, 9198 crossAlign = optionTicks.crossAlign, 9199 padding = optionTicks.padding, 9200 mirror = optionTicks.mirror; 9201 var tl = getTickMarkLength(options.grid); 9202 var tickAndPadding = tl + padding; 9203 var hTickAndPadding = mirror ? -padding : tickAndPadding; 9204 var rotation = -toRadians(this.labelRotation); 9205 var items = []; 9206 var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset; 9207 var textBaseline = 'middle'; 9208 if (position === 'top') { 9209 y = this.bottom - hTickAndPadding; 9210 textAlign = this._getXAxisLabelAlignment(); 9211 } else if (position === 'bottom') { 9212 y = this.top + hTickAndPadding; 9213 textAlign = this._getXAxisLabelAlignment(); 9214 } else if (position === 'left') { 9215 var ret = this._getYAxisLabelAlignment(tl); 9216 textAlign = ret.textAlign; 9217 x = ret.x; 9218 } else if (position === 'right') { 9219 var _ret = this._getYAxisLabelAlignment(tl); 9220 textAlign = _ret.textAlign; 9221 x = _ret.x; 9222 } else if (axis === 'x') { 9223 if (position === 'center') { 9224 y = (chartArea.top + chartArea.bottom) / 2 + tickAndPadding; 9225 } else if (isObject(position)) { 9226 var positionAxisID = Object.keys(position)[0]; 9227 var value = position[positionAxisID]; 9228 y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding; 9229 } 9230 textAlign = this._getXAxisLabelAlignment(); 9231 } else if (axis === 'y') { 9232 if (position === 'center') { 9233 x = (chartArea.left + chartArea.right) / 2 - tickAndPadding; 9234 } else if (isObject(position)) { 9235 var _positionAxisID3 = Object.keys(position)[0]; 9236 var _value3 = position[_positionAxisID3]; 9237 x = this.chart.scales[_positionAxisID3].getPixelForValue(_value3); 9238 } 9239 textAlign = this._getYAxisLabelAlignment(tl).textAlign; 9240 } 9241 if (axis === 'y') { 9242 if (align === 'start') { 9243 textBaseline = 'top'; 9244 } else if (align === 'end') { 9245 textBaseline = 'bottom'; 9246 } 9247 } 9248 var labelSizes = this._getLabelSizes(); 9249 for (i = 0, ilen = ticks.length; i < ilen; ++i) { 9250 tick = ticks[i]; 9251 label = tick.label; 9252 var optsAtIndex = optionTicks.setContext(this.getContext(i)); 9253 pixel = this.getPixelForTick(i) + optionTicks.labelOffset; 9254 font = this._resolveTickFontOptions(i); 9255 lineHeight = font.lineHeight; 9256 lineCount = isArray(label) ? label.length : 1; 9257 var halfCount = lineCount / 2; 9258 var color = optsAtIndex.color; 9259 var strokeColor = optsAtIndex.textStrokeColor; 9260 var strokeWidth = optsAtIndex.textStrokeWidth; 9261 var tickTextAlign = textAlign; 9262 if (isHorizontal) { 9263 x = pixel; 9264 if (textAlign === 'inner') { 9265 if (i === ilen - 1) { 9266 tickTextAlign = !this.options.reverse ? 'right' : 'left'; 9267 } else if (i === 0) { 9268 tickTextAlign = !this.options.reverse ? 'left' : 'right'; 9269 } else { 9270 tickTextAlign = 'center'; 9271 } 9272 } 9273 if (position === 'top') { 9274 if (crossAlign === 'near' || rotation !== 0) { 9275 textOffset = -lineCount * lineHeight + lineHeight / 2; 9276 } else if (crossAlign === 'center') { 9277 textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight; 9278 } else { 9279 textOffset = -labelSizes.highest.height + lineHeight / 2; 9280 } 9281 } else { 9282 if (crossAlign === 'near' || rotation !== 0) { 9283 textOffset = lineHeight / 2; 9284 } else if (crossAlign === 'center') { 9285 textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight; 9286 } else { 9287 textOffset = labelSizes.highest.height - lineCount * lineHeight; 9288 } 9289 } 9290 if (mirror) { 9291 textOffset *= -1; 9292 } 9293 if (rotation !== 0 && !optsAtIndex.showLabelBackdrop) { 9294 x += lineHeight / 2 * Math.sin(rotation); 9295 } 9296 } else { 9297 y = pixel; 9298 textOffset = (1 - lineCount) * lineHeight / 2; 9299 } 9300 var backdrop = void 0; 9301 if (optsAtIndex.showLabelBackdrop) { 9302 var labelPadding = toPadding(optsAtIndex.backdropPadding); 9303 var height = labelSizes.heights[i]; 9304 var width = labelSizes.widths[i]; 9305 var top = textOffset - labelPadding.top; 9306 var left = 0 - labelPadding.left; 9307 switch (textBaseline) { 9308 case 'middle': 9309 top -= height / 2; 9310 break; 9311 case 'bottom': 9312 top -= height; 9313 break; 9314 } 9315 switch (textAlign) { 9316 case 'center': 9317 left -= width / 2; 9318 break; 9319 case 'right': 9320 left -= width; 9321 break; 9322 case 'inner': 9323 if (i === ilen - 1) { 9324 left -= width; 9325 } else if (i > 0) { 9326 left -= width / 2; 9327 } 9328 break; 9329 } 9330 backdrop = { 9331 left: left, 9332 top: top, 9333 width: width + labelPadding.width, 9334 height: height + labelPadding.height, 9335 color: optsAtIndex.backdropColor 9336 }; 9337 } 9338 items.push({ 9339 label: label, 9340 font: font, 9341 textOffset: textOffset, 9342 options: { 9343 rotation: rotation, 9344 color: color, 9345 strokeColor: strokeColor, 9346 strokeWidth: strokeWidth, 9347 textAlign: tickTextAlign, 9348 textBaseline: textBaseline, 9349 translation: [x, y], 9350 backdrop: backdrop 9351 } 9352 }); 9353 } 9354 return items; 9355 } 9356 }, {
9357 key: "_getXAxisLabelAlignment", 9358 value: function _getXAxisLabelAlignment() { 9359 var _this$options8 = this.options, 9360 position = _this$options8.position, 9361 ticks = _this$options8.ticks; 9362 var rotation = -toRadians(this.labelRotation); 9363 if (rotation) { 9364 return position === 'top' ? 'left' : 'right'; 9365 } 9366 var align = 'center'; 9367 if (ticks.align === 'start') { 9368 align = 'left'; 9369 } else if (ticks.align === 'end') { 9370 align = 'right'; 9371 } else if (ticks.align === 'inner') { 9372 align = 'inner'; 9373 } 9374 return align; 9375 } 9376 }, { 9377 key: "_getYAxisLabelAlignment", 9378 value: function _getYAxisLabelAlignment(tl) { 9379 var _this$options9 = this.options, 9380 position = _this$options9.position, 9381 _this$options9$ticks = _this$options9.ticks, 9382 crossAlign = _this$options9$ticks.crossAlign, 9383 mirror = _this$options9$ticks.mirror, 9384 padding = _this$options9$ticks.padding; 9385 var labelSizes = this._getLabelSizes(); 9386 var tickAndPadding = tl + padding; 9387 var widest = labelSizes.widest.width; 9388 var textAlign; 9389 var x; 9390 if (position === 'left') { 9391 if (mirror) { 9392 x = this.right + padding; 9393 if (crossAlign === 'near') { 9394 textAlign = 'left'; 9395 } else if (crossAlign === 'center') { 9396 textAlign = 'center'; 9397 x += widest / 2; 9398 } else { 9399 textAlign = 'right'; 9400 x += widest; 9401 } 9402 } else { 9403 x = this.right - tickAndPadding; 9404 if (crossAlign === 'near') { 9405 textAlign = 'right'; 9406 } else if (crossAlign === 'center') { 9407 textAlign = 'center'; 9408 x -= widest / 2; 9409 } else { 9410 textAlign = 'left'; 9411 x = this.left; 9412 } 9413 } 9414 } else if (position === 'right') { 9415 if (mirror) { 9416 x = this.left + padding; 9417 if (crossAlign === 'near') { 9418 textAlign = 'right'; 9419 } else if (crossAlign === 'center') { 9420 textAlign = 'center'; 9421 x -= widest / 2; 9422 } else { 9423 textAlign = 'left'; 9424 x -= widest; 9425 } 9426 } else { 9427 x = this.left + tickAndPadding; 9428 if (crossAlign === 'near') { 9429 textAlign = 'left'; 9430 } else if (crossAlign === 'center') { 9431 textAlign = 'center'; 9432 x += widest / 2; 9433 } else { 9434 textAlign = 'right'; 9435 x = this.right; 9436 } 9437 } 9438 } else { 9439 textAlign = 'right'; 9440 } 9441 return { 9442 textAlign: textAlign, 9443 x: x 9444 }; 9445 } 9446 }, { 9447 key: "_computeLabelArea", 9448 value: function _computeLabelArea() { 9449 if (this.options.ticks.mirror) { 9450 return; 9451 } 9452 var chart = this.chart; 9453 var position = this.options.position; 9454 if (position === 'left' || position === 'right') { 9455 return { 9456 top: 0, 9457 left: this.left, 9458 bottom: chart.height, 9459 right: this.right 9460 }; 9461 } 9462 if (position === 'top' || position === 'bottom') { 9463 return { 9464 top: this.top, 9465 left: 0, 9466 bottom: this.bottom, 9467 right: chart.width 9468 }; 9469 } 9470 } 9471 }, { 9472 key: "drawBackground", 9473 value: function drawBackground() { 9474 var ctx = this.ctx, 9475 backgroundColor = this.options.backgroundColor, 9476 left = this.left, 9477 top = this.top, 9478 width = this.width, 9479 height = this.height; 9480 if (backgroundColor) { 9481 ctx.save(); 9482 ctx.fillStyle = backgroundColor; 9483 ctx.fillRect(left, top, width, height); 9484 ctx.restore(); 9485 } 9486 } 9487 }, { 9488 key: "getLineWidthForValue", 9489 value: function getLineWidthForValue(value) { 9490 var grid = this.options.grid; 9491 if (!this._isVisible() || !grid.display) { 9492 return 0; 9493 } 9494 var ticks = this.ticks; 9495 var index = ticks.findIndex(function (t) { 9496 return t.value === value; 9497 }); 9498 if (index >= 0) { 9499 var opts = grid.setContext(this.getContext(index)); 9500 return opts.lineWidth; 9501 } 9502 return 0; 9503 } 9504 }, {
9505 key: "drawGrid", 9506 value: function drawGrid(chartArea) { 9507 var grid = this.options.grid; 9508 var ctx = this.ctx; 9509 var items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea)); 9510 var i, ilen; 9511 var drawLine = function drawLine(p1, p2, style) { 9512 if (!style.width || !style.color) { 9513 return; 9514 } 9515 ctx.save(); 9516 ctx.lineWidth = style.width; 9517 ctx.strokeStyle = style.color; 9518 ctx.setLineDash(style.borderDash || []); 9519 ctx.lineDashOffset = style.borderDashOffset; 9520 ctx.beginPath(); 9521 ctx.moveTo(p1.x, p1.y); 9522 ctx.lineTo(p2.x, p2.y); 9523 ctx.stroke(); 9524 ctx.restore(); 9525 }; 9526 if (grid.display) { 9527 for (i = 0, ilen = items.length; i < ilen; ++i) { 9528 var item = items[i]; 9529 if (grid.drawOnChartArea) { 9530 drawLine({ 9531 x: item.x1, 9532 y: item.y1 9533 }, { 9534 x: item.x2, 9535 y: item.y2 9536 }, item); 9537 } 9538 if (grid.drawTicks) { 9539 drawLine({ 9540 x: item.tx1, 9541 y: item.ty1 9542 }, { 9543 x: item.tx2, 9544 y: item.ty2 9545 }, { 9546 color: item.tickColor, 9547 width: item.tickWidth, 9548 borderDash: item.tickBorderDash, 9549 borderDashOffset: item.tickBorderDashOffset 9550 }); 9551 } 9552 } 9553 } 9554 } 9555 }, { 9556 key: "drawBorder", 9557 value: function drawBorder() { 9558 var chart = this.chart, 9559 ctx = this.ctx, 9560 _this$options0 = this.options, 9561 border = _this$options0.border, 9562 grid = _this$options0.grid; 9563 var borderOpts = border.setContext(this.getContext()); 9564 var axisWidth = border.display ? borderOpts.width : 0; 9565 if (!axisWidth) { 9566 return; 9567 } 9568 var lastLineWidth = grid.setContext(this.getContext(0)).lineWidth; 9569 var borderValue = this._borderValue; 9570 var x1, x2, y1, y2; 9571 if (this.isHorizontal()) { 9572 x1 = _alignPixel(chart, this.left, axisWidth) - axisWidth / 2; 9573 x2 = _alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2; 9574 y1 = y2 = borderValue; 9575 } else { 9576 y1 = _alignPixel(chart, this.top, axisWidth) - axisWidth / 2; 9577 y2 = _alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2; 9578 x1 = x2 = borderValue; 9579 } 9580 ctx.save(); 9581 ctx.lineWidth = borderOpts.width; 9582 ctx.strokeStyle = borderOpts.color; 9583 ctx.beginPath(); 9584 ctx.moveTo(x1, y1); 9585 ctx.lineTo(x2, y2); 9586 ctx.stroke(); 9587 ctx.restore(); 9588 } 9589 }, { 9590 key: "drawLabels", 9591 value: function drawLabels(chartArea) { 9592 var optionTicks = this.options.ticks; 9593 if (!optionTicks.display) { 9594 return; 9595 } 9596 var ctx = this.ctx; 9597 var area = this._computeLabelArea(); 9598 if (area) { 9599 clipArea(ctx, area); 9600 } 9601 var items = this.getLabelItems(chartArea); 9602 var _iterator1 = _createForOfIteratorHelper$1(items), 9603 _step1; 9604 try { 9605 for (_iterator1.s(); !(_step1 = _iterator1.n()).done;) { 9606 var item = _step1.value; 9607 var renderTextOptions = item.options; 9608 var tickFont = item.font; 9609 var label = item.label; 9610 var y = item.textOffset; 9611 renderText(ctx, label, 0, y, tickFont, renderTextOptions); 9612 } 9613 } catch (err) { 9614 _iterator1.e(err); 9615 } finally { 9616 _iterator1.f(); 9617 } 9618 if (area) { 9619 unclipArea(ctx); 9620 } 9621 } 9622 }, { 9623 key: "drawTitle", 9624 value: function drawTitle() { 9625 var ctx = this.ctx, 9626 _this$options1 = this.options, 9627 position = _this$options1.position, 9628 title = _this$options1.title, 9629 reverse = _this$options1.reverse; 9630 if (!title.display) { 9631 return; 9632 } 9633 var font = toFont(title.font); 9634 var padding = toPadding(title.padding); 9635 var align = title.align; 9636 var offset = font.lineHeight / 2; 9637 if (position === 'bottom' || position === 'center' || isObject(position)) { 9638 offset += padding.bottom; 9639 if (isArray(title.text)) { 9640 offset += font.lineHeight * (title.text.length - 1); 9641 } 9642 } else { 9643 offset += padding.top; 9644 } 9645 var _titleArgs = titleArgs(this, offset, position, align), 9646 titleX = _titleArgs.titleX, 9647 titleY = _titleArgs.titleY, 9648 maxWidth = _titleArgs.maxWidth, 9649 rotation = _titleArgs.rotation; 9650 renderText(ctx, title.text, 0, 0, font, { 9651 color: title.color, 9652 maxWidth: maxWidth, 9653 rotation: rotation, 9654 textAlign: titleAlign(align, position, reverse), 9655 textBaseline: 'middle', 9656 translation: [titleX, titleY] 9657 }); 9658 } 9659 }, {
9660 key: "draw", 9661 value: function draw(chartArea) { 9662 if (!this._isVisible()) { 9663 return; 9664 } 9665 this.drawBackground(); 9666 this.drawGrid(chartArea); 9667 this.drawBorder(); 9668 this.drawTitle(); 9669 this.drawLabels(chartArea); 9670 } 9671 }, { 9672 key: "_layers", 9673 value: function _layers() { 9674 var _this0 = this; 9675 var opts = this.options; 9676 var tz = opts.ticks && opts.ticks.z || 0; 9677 var gz = valueOrDefault(opts.grid && opts.grid.z, -1); 9678 var bz = valueOrDefault(opts.border && opts.border.z, 0); 9679 if (!this._isVisible() || this.draw !== Scale.prototype.draw) { 9680 return [{ 9681 z: tz, 9682 draw: function draw(chartArea) { 9683 _this0.draw(chartArea); 9684 } 9685 }]; 9686 } 9687 return [{ 9688 z: gz, 9689 draw: function draw(chartArea) { 9690 _this0.drawBackground(); 9691 _this0.drawGrid(chartArea); 9692 _this0.drawTitle(); 9693 } 9694 }, { 9695 z: bz, 9696 draw: function draw() { 9697 _this0.drawBorder(); 9698 } 9699 }, { 9700 z: tz, 9701 draw: function draw(chartArea) { 9702 _this0.drawLabels(chartArea); 9703 } 9704 }]; 9705 } 9706 }, { 9707 key: "getMatchingVisibleMetas", 9708 value: function getMatchingVisibleMetas(type) { 9709 var metas = this.chart.getSortedVisibleDatasetMetas(); 9710 var axisID = this.axis + 'AxisID'; 9711 var result = []; 9712 var i, ilen; 9713 for (i = 0, ilen = metas.length; i < ilen; ++i) { 9714 var meta = metas[i]; 9715 if (meta[axisID] === this.id && (!type || meta.type === type)) { 9716 result.push(meta); 9717 } 9718 } 9719 return result; 9720 } 9721 }, { 9722 key: "_resolveTickFontOptions", 9723 value: function _resolveTickFontOptions(index) { 9724 var opts = this.options.ticks.setContext(this.getContext(index)); 9725 return toFont(opts.font); 9726 } 9727 }, { 9728 key: "_maxDigits", 9729 value: function _maxDigits() { 9730 var fontSize = this._resolveTickFontOptions(0).lineHeight; 9731 return (this.isHorizontal() ? this.width : this.height) / fontSize; 9732 } 9733 }]); 9734 }(Element); 9735 var TypedRegistry = /*#__PURE__*/function () { 9736 function TypedRegistry(type, scope, override) { 9737 _classCallCheck$1(this, TypedRegistry); 9738 this.type = type; 9739 this.scope = scope; 9740 this.override = override; 9741 this.items = Object.create(null); 9742 } 9743 return _createClass$1(TypedRegistry, [{ 9744 key: "isForType", 9745 value: function isForType(type) { 9746 return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype); 9747 } 9748 }, { 9749 key: "register", 9750 value: function register(item) { 9751 var proto = Object.getPrototypeOf(item); 9752 var parentScope; 9753 if (isIChartComponent(proto)) { 9754 parentScope = this.register(proto); 9755 } 9756 var items = this.items; 9757 var id = item.id; 9758 var scope = this.scope + '.' + id; 9759 if (!id) { 9760 throw new Error('class does not have id: ' + item); 9761 } 9762 if (id in items) { 9763 return scope; 9764 } 9765 items[id] = item; 9766 registerDefaults(item, scope, parentScope); 9767 if (this.override) { 9768 defaults.override(item.id, item.overrides); 9769 } 9770 return scope; 9771 } 9772 }, { 9773 key: "get", 9774 value: function get(id) { 9775 return this.items[id]; 9776 } 9777 }, { 9778 key: "unregister", 9779 value: function unregister(item) { 9780 var items = this.items; 9781 var id = item.id; 9782 var scope = this.scope; 9783 if (id in items) { 9784 delete items[id]; 9785 } 9786 if (scope && id in defaults[scope]) { 9787 delete defaults[scope][id]; 9788 if (this.override) { 9789 delete overrides[id]; 9790 } 9791 } 9792 } 9793 }]); 9794 }(); 9795 function registerDefaults(item, scope, parentScope) { 9796 var itemDefaults = merge(Object.create(null), [parentScope ? defaults.get(parentScope) : {}, defaults.get(scope), item.defaults]); 9797 defaults.set(scope, itemDefaults); 9798 if (item.defaultRoutes) { 9799 routeDefaults(scope, item.defaultRoutes); 9800 } 9801 if (item.descriptors) { 9802 defaults.describe(scope, item.descriptors); 9803 } 9804 } 9805 function routeDefaults(scope, routes) {
9806 Object.keys(routes).forEach(function (property) { 9807 var propertyParts = property.split('.'); 9808 var sourceName = propertyParts.pop(); 9809 var sourceScope = [scope].concat(propertyParts).join('.'); 9810 var parts = routes[property].split('.'); 9811 var targetName = parts.pop(); 9812 var targetScope = parts.join('.'); 9813 defaults.route(sourceScope, sourceName, targetScope, targetName); 9814 }); 9815 } 9816 function isIChartComponent(proto) { 9817 return 'id' in proto && 'defaults' in proto; 9818 } 9819 var Registry = /*#__PURE__*/function () { 9820 function Registry() { 9821 _classCallCheck$1(this, Registry); 9822 this.controllers = new TypedRegistry(DatasetController, 'datasets', true); 9823 this.elements = new TypedRegistry(Element, 'elements'); 9824 this.plugins = new TypedRegistry(Object, 'plugins'); 9825 this.scales = new TypedRegistry(Scale, 'scales'); 9826 this._typedRegistries = [this.controllers, this.scales, this.elements]; 9827 } 9828 return _createClass$1(Registry, [{ 9829 key: "add", 9830 value: function add() { 9831 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 9832 args[_key] = arguments[_key]; 9833 } 9834 this._each('register', args); 9835 } 9836 }, { 9837 key: "remove", 9838 value: function remove() { 9839 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { 9840 args[_key2] = arguments[_key2]; 9841 } 9842 this._each('unregister', args); 9843 } 9844 }, { 9845 key: "addControllers", 9846 value: function addControllers() { 9847 for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { 9848 args[_key3] = arguments[_key3]; 9849 } 9850 this._each('register', args, this.controllers); 9851 } 9852 }, { 9853 key: "addElements", 9854 value: function addElements() { 9855 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { 9856 args[_key4] = arguments[_key4]; 9857 } 9858 this._each('register', args, this.elements); 9859 } 9860 }, { 9861 key: "addPlugins", 9862 value: function addPlugins() { 9863 for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { 9864 args[_key5] = arguments[_key5]; 9865 } 9866 this._each('register', args, this.plugins); 9867 } 9868 }, { 9869 key: "addScales", 9870 value: function addScales() { 9871 for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { 9872 args[_key6] = arguments[_key6]; 9873 } 9874 this._each('register', args, this.scales); 9875 } 9876 }, { 9877 key: "getController", 9878 value: function getController(id) { 9879 return this._get(id, this.controllers, 'controller'); 9880 } 9881 }, { 9882 key: "getElement", 9883 value: function getElement(id) { 9884 return this._get(id, this.elements, 'element'); 9885 } 9886 }, { 9887 key: "getPlugin", 9888 value: function getPlugin(id) { 9889 return this._get(id, this.plugins, 'plugin'); 9890 } 9891 }, { 9892 key: "getScale", 9893 value: function getScale(id) { 9894 return this._get(id, this.scales, 'scale'); 9895 } 9896 }, { 9897 key: "removeControllers", 9898 value: function removeControllers() { 9899 for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { 9900 args[_key7] = arguments[_key7]; 9901 } 9902 this._each('unregister', args, this.controllers); 9903 } 9904 }, { 9905 key: "removeElements", 9906 value: function removeElements() { 9907 for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { 9908 args[_key8] = arguments[_key8]; 9909 } 9910 this._each('unregister', args, this.elements); 9911 } 9912 }, { 9913 key: "removePlugins", 9914 value: function removePlugins() { 9915 for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { 9916 args[_key9] = arguments[_key9]; 9917 } 9918 this._each('unregister', args, this.plugins); 9919 } 9920 }, {
9921 key: "removeScales", 9922 value: function removeScales() { 9923 for (var _len0 = arguments.length, args = new Array(_len0), _key0 = 0; _key0 < _len0; _key0++) { 9924 args[_key0] = arguments[_key0]; 9925 } 9926 this._each('unregister', args, this.scales); 9927 } 9928 }, { 9929 key: "_each", 9930 value: function _each(method, args, typedRegistry) { 9931 var _this1 = this; 9932 _toConsumableArray(args).forEach(function (arg) { 9933 var reg = typedRegistry || _this1._getRegistryForType(arg); 9934 if (typedRegistry || reg.isForType(arg) || reg === _this1.plugins && arg.id) { 9935 _this1._exec(method, reg, arg); 9936 } else { 9937 each(arg, function (item) { 9938 var itemReg = typedRegistry || _this1._getRegistryForType(item); 9939 _this1._exec(method, itemReg, item); 9940 }); 9941 } 9942 }); 9943 } 9944 }, { 9945 key: "_exec", 9946 value: function _exec(method, registry, component) { 9947 var camelMethod = _capitalize(method); 9948 callback(component['before' + camelMethod], [], component); 9949 registry[method](component); 9950 callback(component['after' + camelMethod], [], component); 9951 } 9952 }, { 9953 key: "_getRegistryForType", 9954 value: function _getRegistryForType(type) { 9955 for (var i = 0; i < this._typedRegistries.length; i++) { 9956 var reg = this._typedRegistries[i]; 9957 if (reg.isForType(type)) { 9958 return reg; 9959 } 9960 } 9961 return this.plugins; 9962 } 9963 }, { 9964 key: "_get", 9965 value: function _get(id, typedRegistry, type) { 9966 var item = typedRegistry.get(id); 9967 if (item === undefined) { 9968 throw new Error('"' + id + '" is not a registered ' + type + '.'); 9969 } 9970 return item; 9971 } 9972 }]); 9973 }(); 9974 var registry = /* #__PURE__ */new Registry(); 9975 var PluginService = /*#__PURE__*/function () { 9976 function PluginService() { 9977 _classCallCheck$1(this, PluginService); 9978 this._init = undefined; 9979 } 9980 return _createClass$1(PluginService, [{ 9981 key: "notify", 9982 value: function notify(chart, hook, args, filter) { 9983 if (hook === 'beforeInit') { 9984 this._init = this._createDescriptors(chart, true); 9985 this._notify(this._init, chart, 'install'); 9986 } 9987 if (this._init === undefined) { 9988 return; 9989 } 9990 var descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart); 9991 var result = this._notify(descriptors, chart, hook, args); 9992 if (hook === 'afterDestroy') { 9993 this._notify(descriptors, chart, 'stop'); 9994 this._notify(this._init, chart, 'uninstall'); 9995 this._init = undefined; 9996 } 9997 return result; 9998 } 9999 }, { 10000 key: "_notify", 10001 value: function _notify(descriptors, chart, hook, args) { 10002 args = args || {}; 10003 var _iterator10 = _createForOfIteratorHelper$1(descriptors), 10004 _step10; 10005 try { 10006 for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) { 10007 var descriptor = _step10.value; 10008 var plugin = descriptor.plugin; 10009 var method = plugin[hook]; 10010 var params = [chart, args, descriptor.options]; 10011 if (callback(method, params, plugin) === false && args.cancelable) { 10012 return false; 10013 } 10014 } 10015 } catch (err) { 10016 _iterator10.e(err); 10017 } finally { 10018 _iterator10.f(); 10019 } 10020 return true; 10021 } 10022 }, { 10023 key: "invalidate",
10024 value: function invalidate() { 10025 if (!isNullOrUndef(this._cache)) { 10026 this._oldCache = this._cache; 10027 this._cache = undefined; 10028 } 10029 } 10030 }, { 10031 key: "_descriptors", 10032 value: function _descriptors(chart) { 10033 if (this._cache) { 10034 return this._cache; 10035 } 10036 var descriptors = this._cache = this._createDescriptors(chart); 10037 this._notifyStateChanges(chart); 10038 return descriptors; 10039 } 10040 }, { 10041 key: "_createDescriptors", 10042 value: function _createDescriptors(chart, all) { 10043 var config = chart && chart.config; 10044 var options = valueOrDefault(config.options && config.options.plugins, {}); 10045 var plugins = allPlugins(config); 10046 return options === false && !all ? [] : createDescriptors(chart, plugins, options, all); 10047 } 10048 }, { 10049 key: "_notifyStateChanges", 10050 value: function _notifyStateChanges(chart) { 10051 var previousDescriptors = this._oldCache || []; 10052 var descriptors = this._cache; 10053 var diff = function diff(a, b) { 10054 return a.filter(function (x) { 10055 return !b.some(function (y) { 10056 return x.plugin.id === y.plugin.id; 10057 }); 10058 }); 10059 }; 10060 this._notify(diff(previousDescriptors, descriptors), chart, 'stop'); 10061 this._notify(diff(descriptors, previousDescriptors), chart, 'start'); 10062 } 10063 }]); 10064 }(); 10065 function allPlugins(config) { 10066 var localIds = {}; 10067 var plugins = []; 10068 var keys = Object.keys(registry.plugins.items); 10069 for (var i = 0; i < keys.length; i++) { 10070 plugins.push(registry.getPlugin(keys[i])); 10071 } 10072 var local = config.plugins || []; 10073 for (var _i2 = 0; _i2 < local.length; _i2++) { 10074 var plugin = local[_i2]; 10075 if (plugins.indexOf(plugin) === -1) { 10076 plugins.push(plugin); 10077 localIds[plugin.id] = true; 10078 } 10079 } 10080 return { 10081 plugins: plugins, 10082 localIds: localIds 10083 }; 10084 } 10085 function getOpts(options, all) { 10086 if (!all && options === false) { 10087 return null; 10088 } 10089 if (options === true) { 10090 return {}; 10091 } 10092 return options; 10093 } 10094 function createDescriptors(chart, _ref2, options, all) { 10095 var plugins = _ref2.plugins, 10096 localIds = _ref2.localIds; 10097 var result = []; 10098 var context = chart.getContext(); 10099 var _iterator11 = _createForOfIteratorHelper$1(plugins), 10100 _step11; 10101 try { 10102 for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) { 10103 var plugin = _step11.value; 10104 var id = plugin.id; 10105 var opts = getOpts(options[id], all); 10106 if (opts === null) { 10107 continue; 10108 } 10109 result.push({ 10110 plugin: plugin, 10111 options: pluginOpts(chart.config, { 10112 plugin: plugin, 10113 local: localIds[id] 10114 }, opts, context) 10115 }); 10116 } 10117 } catch (err) { 10118 _iterator11.e(err); 10119 } finally { 10120 _iterator11.f(); 10121 } 10122 return result; 10123 } 10124 function pluginOpts(config, _ref3, opts, context) { 10125 var plugin = _ref3.plugin, 10126 local = _ref3.local; 10127 var keys = config.pluginScopeKeys(plugin); 10128 var scopes = config.getOptionScopes(opts, keys); 10129 if (local && plugin.defaults) { 10130 scopes.push(plugin.defaults); 10131 } 10132 return config.createResolver(scopes, context, [''], { 10133 scriptable: false, 10134 indexable: false, 10135 allKeys: true 10136 }); 10137 } 10138 function getIndexAxis(type, options) { 10139 var datasetDefaults = defaults.datasets[type] || {}; 10140 var datasetOptions = (options.datasets || {})[type] || {}; 10141 return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x'; 10142 } 10143 function getAxisFromDefaultScaleID(id, indexAxis) { 10144 var axis = id; 10145 if (id === '_index_') { 10146 axis = indexAxis; 10147 } else if (id === '_value_') { 10148 axis = indexAxis === 'x' ? 'y' : 'x'; 10149 } 10150 return axis; 10151 } 10152 function getDefaultScaleIDFromAxis(axis, indexAxis) { 10153 return axis === indexAxis ? '_index_' : '_value_'; 10154 } 10155 function idMatchesAxis(id) { 10156 if (id === 'x' || id === 'y' || id === 'r') { 10157 return id; 10158 } 10159 } 10160 function axisFromPosition(position) { 10161 if (position === 'top' || position === 'bottom') { 10162 return 'x'; 10163 } 10164 if (position === 'left' || position === 'right') { 10165 return 'y'; 10166 } 10167 } 10168 function determineAxis(id) { 10169 if (idMatchesAxis(id)) { 10170 return id; 10171 } 10172 for (var _len1 = arguments.length, scaleOptions = new Array(_len1 > 1 ? _len1 - 1 : 0), _key1 = 1; _key1 < _len1; _key1++) {
10173 scaleOptions[_key1 - 1] = arguments[_key1]; 10174 } 10175 for (var _i3 = 0, _scaleOptions = scaleOptions; _i3 < _scaleOptions.length; _i3++) { 10176 var opts = _scaleOptions[_i3]; 10177 var axis = opts.axis || axisFromPosition(opts.position) || id.length > 1 && idMatchesAxis(id[0].toLowerCase()); 10178 if (axis) { 10179 return axis; 10180 } 10181 } 10182 throw new Error("Cannot determine type of '".concat(id, "' axis. Please provide 'axis' or 'position' option.")); 10183 } 10184 function getAxisFromDataset(id, axis, dataset) { 10185 if (dataset[axis + 'AxisID'] === id) { 10186 return { 10187 axis: axis 10188 }; 10189 } 10190 } 10191 function retrieveAxisFromDatasets(id, config) { 10192 if (config.data && config.data.datasets) { 10193 var boundDs = config.data.datasets.filter(function (d) { 10194 return d.xAxisID === id || d.yAxisID === id; 10195 }); 10196 if (boundDs.length) { 10197 return getAxisFromDataset(id, 'x', boundDs[0]) || getAxisFromDataset(id, 'y', boundDs[0]); 10198 } 10199 } 10200 return {}; 10201 } 10202 function mergeScaleConfig(config, options) { 10203 var chartDefaults = overrides[config.type] || { 10204 scales: {} 10205 }; 10206 var configScales = options.scales || {}; 10207 var chartIndexAxis = getIndexAxis(config.type, options); 10208 var scales = Object.create(null); 10209 Object.keys(configScales).forEach(function (id) { 10210 var scaleConf = configScales[id]; 10211 if (!isObject(scaleConf)) { 10212 return console.error("Invalid scale configuration for scale: ".concat(id)); 10213 } 10214 if (scaleConf._proxy) { 10215 return console.warn("Ignoring resolver passed as options for scale: ".concat(id)); 10216 } 10217 var axis = determineAxis(id, scaleConf, retrieveAxisFromDatasets(id, config), defaults.scales[scaleConf.type]); 10218 var defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis); 10219 var defaultScaleOptions = chartDefaults.scales || {}; 10220 scales[id] = mergeIf(Object.create(null), [{ 10221 axis: axis 10222 }, scaleConf, defaultScaleOptions[axis], defaultScaleOptions[defaultId]]); 10223 }); 10224 config.data.datasets.forEach(function (dataset) { 10225 var type = dataset.type || config.type; 10226 var indexAxis = dataset.indexAxis || getIndexAxis(type, options); 10227 var datasetDefaults = overrides[type] || {}; 10228 var defaultScaleOptions = datasetDefaults.scales || {}; 10229 Object.keys(defaultScaleOptions).forEach(function (defaultID) { 10230 var axis = getAxisFromDefaultScaleID(defaultID, indexAxis); 10231 var id = dataset[axis + 'AxisID'] || axis; 10232 scales[id] = scales[id] || Object.create(null); 10233 mergeIf(scales[id], [{ 10234 axis: axis 10235 }, configScales[id], defaultScaleOptions[defaultID]]); 10236 }); 10237 }); 10238 Object.keys(scales).forEach(function (key) { 10239 var scale = scales[key]; 10240 mergeIf(scale, [defaults.scales[scale.type], defaults.scale]); 10241 }); 10242 return scales; 10243 } 10244 function initOptions(config) { 10245 var options = config.options || (config.options = {}); 10246 options.plugins = valueOrDefault(options.plugins, {}); 10247 options.scales = mergeScaleConfig(config, options); 10248 } 10249 function initData(data) { 10250 data = data || {}; 10251 data.datasets = data.datasets || []; 10252 data.labels = data.labels || []; 10253 return data; 10254 } 10255 function initConfig(config) { 10256 config = config || {}; 10257 config.data = initData(config.data); 10258 initOptions(config); 10259 return config; 10260 } 10261 var keyCache = new Map(); 10262 var keysCached = new Set(); 10263 function cachedKeys(cacheKey, generate) { 10264 var keys = keyCache.get(cacheKey); 10265 if (!keys) { 10266 keys = generate(); 10267 keyCache.set(cacheKey, keys); 10268 keysCached.add(keys); 10269 } 10270 return keys; 10271 } 10272 var addIfFound = function addIfFound(set, obj, key) { 10273 var opts = resolveObjectKey(obj, key); 10274 if (opts !== undefined) { 10275 set.add(opts); 10276 } 10277 }; 10278 var Config = /*#__PURE__*/function () { 10279 function Config(config) { 10280 _classCallCheck$1(this, Config); 10281 this._config = initConfig(config); 10282 this._scopeCache = new Map(); 10283 this._resolverCache = new Map(); 10284 } 10285 return _createClass$1(Config, [{ 10286 key: "platform", 10287 get: function get() { 10288 return this._config.platform; 10289 } 10290 }, {
10291 key: "type", 10292 get: function get() { 10293 return this._config.type; 10294 }, 10295 set: function set(type) { 10296 this._config.type = type; 10297 } 10298 }, { 10299 key: "data", 10300 get: function get() { 10301 return this._config.data; 10302 }, 10303 set: function set(data) { 10304 this._config.data = initData(data); 10305 } 10306 }, { 10307 key: "options", 10308 get: function get() { 10309 return this._config.options; 10310 }, 10311 set: function set(options) { 10312 this._config.options = options; 10313 } 10314 }, { 10315 key: "plugins", 10316 get: function get() { 10317 return this._config.plugins; 10318 } 10319 }, { 10320 key: "update", 10321 value: function update() { 10322 var config = this._config; 10323 this.clearCache(); 10324 initOptions(config); 10325 } 10326 }, { 10327 key: "clearCache", 10328 value: function clearCache() { 10329 this._scopeCache.clear(); 10330 this._resolverCache.clear(); 10331 } 10332 }, { 10333 key: "datasetScopeKeys", 10334 value: function datasetScopeKeys(datasetType) { 10335 return cachedKeys(datasetType, function () { 10336 return [["datasets.".concat(datasetType), '']]; 10337 }); 10338 } 10339 }, { 10340 key: "datasetAnimationScopeKeys", 10341 value: function datasetAnimationScopeKeys(datasetType, transition) { 10342 return cachedKeys("".concat(datasetType, ".transition.").concat(transition), function () { 10343 return [["datasets.".concat(datasetType, ".transitions.").concat(transition), "transitions.".concat(transition)], ["datasets.".concat(datasetType), '']]; 10344 }); 10345 } 10346 }, { 10347 key: "datasetElementScopeKeys", 10348 value: function datasetElementScopeKeys(datasetType, elementType) { 10349 return cachedKeys("".concat(datasetType, "-").concat(elementType), function () { 10350 return [["datasets.".concat(datasetType, ".elements.").concat(elementType), "datasets.".concat(datasetType), "elements.".concat(elementType), '']]; 10351 }); 10352 } 10353 }, { 10354 key: "pluginScopeKeys", 10355 value: function pluginScopeKeys(plugin) { 10356 var id = plugin.id; 10357 var type = this.type; 10358 return cachedKeys("".concat(type, "-plugin-").concat(id), function () { 10359 return [["plugins.".concat(id)].concat(_toConsumableArray(plugin.additionalOptionScopes || []))]; 10360 }); 10361 } 10362 }, { 10363 key: "_cachedScopes", 10364 value: function _cachedScopes(mainScope, resetCache) { 10365 var _scopeCache = this._scopeCache;
10366 var cache = _scopeCache.get(mainScope); 10367 if (!cache || resetCache) { 10368 cache = new Map(); 10369 _scopeCache.set(mainScope, cache); 10370 } 10371 return cache; 10372 } 10373 }, { 10374 key: "getOptionScopes", 10375 value: function getOptionScopes(mainScope, keyLists, resetCache) { 10376 var options = this.options, 10377 type = this.type; 10378 var cache = this._cachedScopes(mainScope, resetCache); 10379 var cached = cache.get(keyLists); 10380 if (cached) { 10381 return cached; 10382 } 10383 var scopes = new Set(); 10384 keyLists.forEach(function (keys) { 10385 if (mainScope) { 10386 scopes.add(mainScope); 10387 keys.forEach(function (key) { 10388 return addIfFound(scopes, mainScope, key); 10389 }); 10390 } 10391 keys.forEach(function (key) { 10392 return addIfFound(scopes, options, key); 10393 }); 10394 keys.forEach(function (key) { 10395 return addIfFound(scopes, overrides[type] || {}, key); 10396 }); 10397 keys.forEach(function (key) { 10398 return addIfFound(scopes, defaults, key); 10399 }); 10400 keys.forEach(function (key) { 10401 return addIfFound(scopes, descriptors, key); 10402 }); 10403 }); 10404 var array = Array.from(scopes); 10405 if (array.length === 0) { 10406 array.push(Object.create(null)); 10407 } 10408 if (keysCached.has(keyLists)) { 10409 cache.set(keyLists, array); 10410 } 10411 return array; 10412 } 10413 }, { 10414 key: "chartOptionScopes", 10415 value: function chartOptionScopes() { 10416 var options = this.options, 10417 type = this.type; 10418 return [options, overrides[type] || {}, defaults.datasets[type] || {}, { 10419 type: type 10420 }, defaults, descriptors]; 10421 } 10422 }, { 10423 key: "resolveNamedOptions", 10424 value: function resolveNamedOptions(scopes, names, context) { 10425 var prefixes = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ['']; 10426 var result = { 10427 $shared: true 10428 }; 10429 var _getResolver = getResolver(this._resolverCache, scopes, prefixes), 10430 resolver = _getResolver.resolver, 10431 subPrefixes = _getResolver.subPrefixes; 10432 var options = resolver; 10433 if (needContext(resolver, names)) { 10434 result.$shared = false; 10435 context = isFunction(context) ? context() : context; 10436 var subResolver = this.createResolver(scopes, context, subPrefixes); 10437 options = _attachContext(resolver, context, subResolver); 10438 } 10439 var _iterator12 = _createForOfIteratorHelper$1(names), 10440 _step12; 10441 try { 10442 for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) { 10443 var prop = _step12.value; 10444 result[prop] = options[prop]; 10445 } 10446 } catch (err) { 10447 _iterator12.e(err); 10448 } finally { 10449 _iterator12.f(); 10450 } 10451 return result; 10452 } 10453 }, { 10454 key: "createResolver", 10455 value: function createResolver(scopes, context) { 10456 var prefixes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ['']; 10457 var descriptorDefaults = arguments.length > 3 ? arguments[3] : undefined; 10458 var _getResolver2 = getResolver(this._resolverCache, scopes, prefixes), 10459 resolver = _getResolver2.resolver; 10460 return isObject(context) ? _attachContext(resolver, context, undefined, descriptorDefaults) : resolver; 10461 } 10462 }]); 10463 }(); 10464 function getResolver(resolverCache, scopes, prefixes) { 10465 var cache = resolverCache.get(scopes); 10466 if (!cache) { 10467 cache = new Map(); 10468 resolverCache.set(scopes, cache); 10469 } 10470 var cacheKey = prefixes.join(); 10471 var cached = cache.get(cacheKey); 10472 if (!cached) { 10473 var resolver = _createResolver(scopes, prefixes); 10474 cached = { 10475 resolver: resolver, 10476 subPrefixes: prefixes.filter(function (p) { 10477 return !p.toLowerCase().includes('hover'); 10478 }) 10479 }; 10480 cache.set(cacheKey, cached); 10481 } 10482 return cached; 10483 } 10484 var hasFunction = function hasFunction(value) { 10485 return isObject(value) && Object.getOwnPropertyNames(value).some(function (key) { 10486 return isFunction(value[key]); 10487 }); 10488 }; 10489 function needContext(proxy, names) { 10490 var _descriptors2 = _descriptors(proxy), 10491 isScriptable = _descriptors2.isScriptable, 10492 isIndexable = _descriptors2.isIndexable; 10493 var _iterator13 = _createForOfIteratorHelper$1(names), 10494 _step13; 10495 try { 10496 for (_iterator13.s();
10496 !(_step13 = _iterator13.n()).done;) { 10497 var prop = _step13.value; 10498 var scriptable = isScriptable(prop); 10499 var indexable = isIndexable(prop); 10500 var value = (indexable || scriptable) && proxy[prop]; 10501 if (scriptable && (isFunction(value) || hasFunction(value)) || indexable && isArray(value)) { 10502 return true; 10503 } 10504 } 10505 } catch (err) { 10506 _iterator13.e(err); 10507 } finally { 10508 _iterator13.f(); 10509 } 10510 return false; 10511 } 10512 var version = "4.5.1"; 10513 var KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea']; 10514 function positionIsHorizontal(position, axis) { 10515 return position === 'top' || position === 'bottom' || KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x'; 10516 } 10517 function compare2Level(l1, l2) { 10518 return function (a, b) { 10519 return a[l1] === b[l1] ? a[l2] - b[l2] : a[l1] - b[l1]; 10520 }; 10521 } 10522 function onAnimationsComplete(context) { 10523 var chart = context.chart; 10524 var animationOptions = chart.options.animation; 10525 chart.notifyPlugins('afterRender'); 10526 callback(animationOptions && animationOptions.onComplete, [context], chart); 10527 } 10528 function onAnimationProgress(context) { 10529 var chart = context.chart; 10530 var animationOptions = chart.options.animation; 10531 callback(animationOptions && animationOptions.onProgress, [context], chart); 10532 } 10533 function getCanvas(item) { 10534 if (_isDomSupported() && typeof item === 'string') { 10535 item = document.getElementById(item); 10536 } else if (item && item.length) { 10537 item = item[0]; 10538 } 10539 if (item && item.canvas) { 10540 item = item.canvas; 10541 } 10542 return item; 10543 } 10544 var instances = {}; 10545 var getChart = function getChart(key) { 10546 var canvas = getCanvas(key); 10547 return Object.values(instances).filter(function (c) { 10548 return c.canvas === canvas; 10549 }).pop(); 10550 }; 10551 function moveNumericKeys(obj, start, move) { 10552 var keys = Object.keys(obj); 10553 for (var _i4 = 0, _keys = keys; _i4 < _keys.length; _i4++) { 10554 var key = _keys[_i4]; 10555 var intKey = +key; 10556 if (intKey >= start) { 10557 var value = obj[key]; 10558 delete obj[key]; 10559 if (move > 0 || intKey > start) { 10560 obj[intKey + move] = value; 10561 } 10562 } 10563 } 10564 } 10565 function determineLastEvent(e, lastEvent, inChartArea, isClick) { 10566 if (!inChartArea || e.type === 'mouseout') { 10567 return null; 10568 } 10569 if (isClick) { 10570 return lastEvent; 10571 } 10572 return e; 10573 } 10574 var Chart = /*#__PURE__*/function () { 10575 function Chart(item, userConfig) { 10576 var _this10 = this; 10577 _classCallCheck$1(this, Chart); 10578 var config = this.config = new Config(userConfig); 10579 var initialCanvas = getCanvas(item); 10580 var existingChart = getChart(initialCanvas); 10581 if (existingChart) { 10582 throw new Error('Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' + ' must be destroyed before the canvas with ID \'' + existingChart.canvas.id + '\' can be reused.'); 10583 } 10584 var options = config.createResolver(config.chartOptionScopes(), this.getContext()); 10585 this.platform = new (config.platform || _detectPlatform(initialCanvas))(); 10586 this.platform.updateConfig(config); 10587 var context = this.platform.acquireContext(initialCanvas, options.aspectRatio); 10588 var canvas = context && context.canvas; 10589 var height = canvas && canvas.height; 10590 var width = canvas && canvas.width; 10591 this.id = uid(); 10592 this.ctx = context; 10593 this.canvas = canvas; 10594 this.width = width; 10595 this.height = height; 10596 this._options = options; 10597 this._aspectRatio = this.aspectRatio; 10598 this._layers = []; 10599 this._metasets = []; 10600 this._stacks = undefined; 10601 this.boxes = []; 10602 this.currentDevicePixelRatio = undefined; 10603 this.chartArea = undefined; 10604 this._active = []; 10605 this._lastEvent = undefined; 10606 this._listeners = {}; 10607 this._responsiveListeners = undefined; 10608 this._sortedMetasets = []; 10609 this.scales = {}; 10610 this._plugins = new PluginService(); 10611 this.$proxies = {}; 10612 this._hiddenIndices = {}; 10613 this.attached = false;
10614 this._animationsDisabled = undefined; 10615 this.$context = undefined; 10616 this._doResize = debounce(function (mode) { 10617 return _this10.update(mode); 10618 }, options.resizeDelay || 0); 10619 this._dataChanges = []; 10620 instances[this.id] = this; 10621 if (!context || !canvas) { 10622 console.error("Failed to create chart: can't acquire context from the given item"); 10623 return; 10624 } 10625 animator.listen(this, 'complete', onAnimationsComplete); 10626 animator.listen(this, 'progress', onAnimationProgress); 10627 this._initialize(); 10628 if (this.attached) { 10629 this.update(); 10630 } 10631 } 10632 return _createClass$1(Chart, [{ 10633 key: "aspectRatio", 10634 get: function get() { 10635 var _this$options10 = this.options, 10636 aspectRatio = _this$options10.aspectRatio, 10637 maintainAspectRatio = _this$options10.maintainAspectRatio, 10638 width = this.width, 10639 height = this.height, 10640 _aspectRatio = this._aspectRatio; 10641 if (!isNullOrUndef(aspectRatio)) { 10642 return aspectRatio; 10643 } 10644 if (maintainAspectRatio && _aspectRatio) { 10645 return _aspectRatio; 10646 } 10647 return height ? width / height : null; 10648 } 10649 }, { 10650 key: "data", 10651 get: function get() { 10652 return this.config.data; 10653 }, 10654 set: function set(data) { 10655 this.config.data = data; 10656 } 10657 }, { 10658 key: "options", 10659 get: function get() { 10660 return this._options; 10661 }, 10662 set: function set(options) { 10663 this.config.options = options; 10664 } 10665 }, { 10666 key: "registry", 10667 get: function get() { 10668 return registry; 10669 } 10670 }, { 10671 key: "_initialize", 10672 value: function _initialize() { 10673 this.notifyPlugins('beforeInit'); 10674 if (this.options.responsive) { 10675 this.resize(); 10676 } else { 10677 retinaScale(this, this.options.devicePixelRatio); 10678 } 10679 this.bindEvents(); 10680 this.notifyPlugins('afterInit'); 10681 return this; 10682 } 10683 }, { 10684 key: "clear", 10685 value: function clear() { 10686 clearCanvas(this.canvas, this.ctx); 10687 return this; 10688 } 10689 }, { 10690 key: "stop", 10691 value: function stop() { 10692 animator.stop(this); 10693 return this; 10694 } 10695 }, { 10696 key: "resize", 10697 value: function resize(width, height) { 10698 if (!animator.running(this)) { 10699 this._resize(width, height); 10700 } else { 10701 this._resizeBeforeDraw = { 10702 width: width, 10703 height: height 10704 }; 10705 } 10706 } 10707 }, { 10708 key: "_resize", 10709 value: function _resize(width, height) { 10710 var options = this.options; 10711 var canvas = this.canvas; 10712 var aspectRatio = options.maintainAspectRatio && this.aspectRatio; 10713 var newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio); 10714 var newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio(); 10715 var mode = this.width ? 'resize' : 'attach'; 10716 this.width = newSize.width; 10717 this.height = newSize.height; 10718 this._aspectRatio = this.aspectRatio; 10719 if (!retinaScale(this, newRatio, true)) { 10720 return; 10721 } 10722 this.notifyPlugins('resize', { 10723 size: newSize 10724 }); 10725 callback(options.onResize, [this, newSize], this); 10726 if (this.attached) { 10727 if (this._doResize(mode)) { 10728 this.render(); 10729 } 10730 } 10731 } 10732 }, { 10733 key: "ensureScalesHaveIDs", 10734 value: function ensureScalesHaveIDs() { 10735 var options = this.options; 10736 var scalesOptions = options.scales || {}; 10737 each(scalesOptions, function (axisOptions, axisID) { 10738 axisOptions.id = axisID; 10739 }); 10740 } 10741 }, { 10742 key: "buildOrUpdateScales", 10743 value: function buildOrUpdateScales() { 10744 var _this11 = this; 10745 var options = this.options; 10746 var scaleOpts = options.scales; 10747 var scales = this.scales; 10748 var updated = Object.keys(scales).reduce(function (obj, id) { 10749 obj[id] = false; 10750 return obj; 10751 }, {}); 10752 var items = []; 10753 if (scaleOpts) { 10754 items = items.concat(Object.keys(scaleOpts).map(function (id) { 10755 var scaleOptions = scaleOpts[id]; 10756 var axis = determineAxis(id, scaleOptions); 10757 var isRadial = axis === 'r'; 10758 var isHorizontal = axis === 'x'; 10759 return { 10760 options: scaleOptions, 10761 dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left', 10762 dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear' 10763 }; 10764 })); 10765 } 10766 each(items, function (item) { 10767 var scaleOptions = item.options; 10768 var id = scaleOptions.id; 10769 var axis = determineAxis(id, scaleOptions); 10770 var scaleType = valueOrDefault(scaleOptions.type, item.dtype); 10771 if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) { 10772 scaleOptions.position = item.dposition; 10773 } 10774 updated[id] = true; 10775 var scale = null; 10776 if (id in scales && scales[id].type === scaleType) { 10777 scale = scales[id]; 10778 } else { 10779 var scaleClass = registry.getScale(scaleType); 10780 scale = new scaleClass({ 10781 id: id, 10782 type: scaleType, 10783 ctx: _this11.ctx,
10784 chart: _this11 10785 }); 10786 scales[scale.id] = scale; 10787 } 10788 scale.init(scaleOptions, options); 10789 }); 10790 each(updated, function (hasUpdated, id) { 10791 if (!hasUpdated) { 10792 delete scales[id]; 10793 } 10794 }); 10795 each(scales, function (scale) { 10796 layouts.configure(_this11, scale, scale.options); 10797 layouts.addBox(_this11, scale); 10798 }); 10799 } 10800 }, { 10801 key: "_updateMetasets", 10802 value: function _updateMetasets() { 10803 var metasets = this._metasets; 10804 var numData = this.data.datasets.length; 10805 var numMeta = metasets.length; 10806 metasets.sort(function (a, b) { 10807 return a.index - b.index; 10808 }); 10809 if (numMeta > numData) { 10810 for (var i = numData; i < numMeta; ++i) { 10811 this._destroyDatasetMeta(i); 10812 } 10813 metasets.splice(numData, numMeta - numData); 10814 } 10815 this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index')); 10816 } 10817 }, { 10818 key: "_removeUnreferencedMetasets", 10819 value: function _removeUnreferencedMetasets() { 10820 var _this12 = this; 10821 var metasets = this._metasets, 10822 datasets = this.data.datasets; 10823 if (metasets.length > datasets.length) { 10824 delete this._stacks; 10825 } 10826 metasets.forEach(function (meta, index) { 10827 if (datasets.filter(function (x) { 10828 return x === meta._dataset; 10829 }).length === 0) { 10830 _this12._destroyDatasetMeta(index); 10831 } 10832 }); 10833 } 10834 }, { 10835 key: "buildOrUpdateControllers", 10836 value: function buildOrUpdateControllers() { 10837 var newControllers = []; 10838 var datasets = this.data.datasets; 10839 var i, ilen; 10840 this._removeUnreferencedMetasets(); 10841 for (i = 0, ilen = datasets.length; i < ilen; i++) { 10842 var dataset = datasets[i]; 10843 var meta = this.getDatasetMeta(i); 10844 var type = dataset.type || this.config.type; 10845 if (meta.type && meta.type !== type) { 10846 this._destroyDatasetMeta(i); 10847 meta = this.getDatasetMeta(i); 10848 } 10849 meta.type = type; 10850 meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options); 10851 meta.order = dataset.order || 0; 10852 meta.index = i; 10853 meta.label = '' + dataset.label; 10854 meta.visible = this.isDatasetVisible(i); 10855 if (meta.controller) { 10856 meta.controller.updateIndex(i); 10857 meta.controller.linkScales(); 10858 } else { 10859 var ControllerClass = registry.getController(type); 10860 var _defaults$datasets$ty = defaults.datasets[type], 10861 datasetElementType = _defaults$datasets$ty.datasetElementType, 10862 dataElementType = _defaults$datasets$ty.dataElementType; 10863 Object.assign(ControllerClass, { 10864 dataElementType: registry.getElement(dataElementType), 10865 datasetElementType: datasetElementType && registry.getElement(datasetElementType) 10866 }); 10867 meta.controller = new ControllerClass(this, i); 10868 newControllers.push(meta.controller); 10869 } 10870 } 10871 this._updateMetasets(); 10872 return newControllers; 10873 } 10874 }, { 10875 key: "_resetElements", 10876 value: function _resetElements() { 10877 var _this13 = this; 10878 each(this.data.datasets, function (dataset, datasetIndex) { 10879 _this13.getDatasetMeta(datasetIndex).controller.reset(); 10880 }, this); 10881 } 10882 }, { 10883 key: "reset", 10884 value: function reset() { 10885 this._resetElements(); 10886 this.notifyPlugins('reset'); 10887 } 10888 }, { 10889 key: "update", 10890 value: function update(mode) { 10891 var config = this.config; 10892 config.update(); 10893 var options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext()); 10894 var animsDisabled = this._animationsDisabled = !options.animation; 10895 this._updateScales(); 10896 this._checkEventBindings(); 10897 this._updateHiddenIndices(); 10898 this._plugins.invalidate(); 10899 if (this.notifyPlugins('beforeUpdate', { 10900 mode: mode, 10901 cancelable: true 10902 }) === false) { 10903 return; 10904 } 10905 var newControllers = this.buildOrUpdateControllers(); 10906 this.notifyPlugins('beforeElementsUpdate'); 10907 var minPadding = 0; 10908 for (var i = 0, ilen = this.data.datasets.length; i < ilen; i++) { 10909 var _this$getDatasetMeta = this.getDatasetMeta(i), 10910 controller = _this$getDatasetMeta.controller; 10911 var reset = !animsDisabled && newControllers.indexOf(controller) === -1; 10912 controller.buildOrUpdateElements(reset); 10913 minPadding = Math.max(+controller.getMaxOverflow(), minPadding); 10914 } 10915 minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0; 10916 this._updateLayout(minPadding); 10917 if (!animsDisabled) { 10918 each(newControllers, function (controller) { 10919 controller.reset(); 10920 }); 10921 } 10922 this._updateDatasets(mode); 10923 this.notifyPlugins('afterUpdate', { 10924 mode: mode 10925 }); 10926 this._layers.sort(compare2Level('z', '_idx')); 10927 var _active = this._active, 10928 _lastEvent = this._lastEvent; 10929 if (_lastEvent) { 10930 this._eventHandler(_lastEvent, true); 10931 } else if (_active.length) { 10932 this._updateHoverStyles(_active, _active, true); 10933 } 10934 this.render(); 10935 } 10936 }, {
10937 key: "_updateScales", 10938 value: function _updateScales() { 10939 var _this14 = this; 10940 each(this.scales, function (scale) { 10941 layouts.removeBox(_this14, scale); 10942 }); 10943 this.ensureScalesHaveIDs(); 10944 this.buildOrUpdateScales(); 10945 } 10946 }, { 10947 key: "_checkEventBindings", 10948 value: function _checkEventBindings() { 10949 var options = this.options; 10950 var existingEvents = new Set(Object.keys(this._listeners)); 10951 var newEvents = new Set(options.events); 10952 if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) { 10953 this.unbindEvents(); 10954 this.bindEvents(); 10955 } 10956 } 10957 }, { 10958 key: "_updateHiddenIndices", 10959 value: function _updateHiddenIndices() { 10960 var _hiddenIndices = this._hiddenIndices; 10961 var changes = this._getUniformDataChanges() || []; 10962 var _iterator14 = _createForOfIteratorHelper$1(changes), 10963 _step14; 10964 try { 10965 for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) { 10966 var _step14$value = _step14.value, 10967 method = _step14$value.method, 10968 start = _step14$value.start, 10969 count = _step14$value.count; 10970 var move = method === '_removeElements' ? -count : count; 10971 moveNumericKeys(_hiddenIndices, start, move); 10972 } 10973 } catch (err) { 10974 _iterator14.e(err); 10975 } finally { 10976 _iterator14.f(); 10977 } 10978 } 10979 }, { 10980 key: "_getUniformDataChanges", 10981 value: function _getUniformDataChanges() { 10982 var _dataChanges = this._dataChanges; 10983 if (!_dataChanges || !_dataChanges.length) { 10984 return; 10985 } 10986 this._dataChanges = []; 10987 var datasetCount = this.data.datasets.length; 10988 var makeSet = function makeSet(idx) { 10989 return new Set(_dataChanges.filter(function (c) { 10990 return c[0] === idx; 10991 }).map(function (c, i) { 10992 return i + ',' + c.splice(1).join(','); 10993 })); 10994 }; 10995 var changeSet = makeSet(0); 10996 for (var i = 1; i < datasetCount; i++) { 10997 if (!setsEqual(changeSet, makeSet(i))) { 10998 return; 10999 } 11000 } 11001 return Array.from(changeSet).map(function (c) { 11002 return c.split(','); 11003 }).map(function (a) { 11004 return { 11005 method: a[1], 11006 start: +a[2], 11007 count: +a[3] 11008 }; 11009 }); 11010 } 11011 }, { 11012 key: "_updateLayout", 11013 value: function _updateLayout(minPadding) { 11014 var _this15 = this; 11015 if (this.notifyPlugins('beforeLayout', { 11016 cancelable: true 11017 }) === false) { 11018 return; 11019 } 11020 layouts.update(this, this.width, this.height, minPadding); 11021 var area = this.chartArea; 11022 var noArea = area.width <= 0 || area.height <= 0; 11023 this._layers = []; 11024 each(this.boxes, function (box) { 11025 var _this15$_layers; 11026 if (noArea && box.position === 'chartArea') { 11027 return; 11028 } 11029 if (box.configure) { 11030 box.configure(); 11031 } 11032 (_this15$_layers = _this15._layers).push.apply(_this15$_layers, _toConsumableArray(box._layers())); 11033 }, this); 11034 this._layers.forEach(function (item, index) { 11035 item._idx = index; 11036 }); 11037 this.notifyPlugins('afterLayout'); 11038 } 11039 }, { 11040 key: "_updateDatasets", 11041 value: function _updateDatasets(mode) { 11042 if (this.notifyPlugins('beforeDatasetsUpdate', { 11043 mode: mode, 11044 cancelable: true 11045 }) === false) { 11046 return; 11047 } 11048 for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) { 11049 this.getDatasetMeta(i).controller.configure(); 11050 } 11051 for (var _i5 = 0, _ilen = this.data.datasets.length; _i5 < _ilen; ++_i5) { 11052 this._updateDataset(_i5, isFunction(mode) ? mode({ 11053 datasetIndex: _i5 11054 }) : mode); 11055 } 11056 this.notifyPlugins('afterDatasetsUpdate', { 11057 mode: mode 11058 }); 11059 } 11060 }, {
11061 key: "_updateDataset", 11062 value: function _updateDataset(index, mode) { 11063 var meta = this.getDatasetMeta(index); 11064 var args = { 11065 meta: meta, 11066 index: index, 11067 mode: mode, 11068 cancelable: true 11069 }; 11070 if (this.notifyPlugins('beforeDatasetUpdate', args) === false) { 11071 return; 11072 } 11073 meta.controller._update(mode); 11074 args.cancelable = false; 11075 this.notifyPlugins('afterDatasetUpdate', args); 11076 } 11077 }, { 11078 key: "render", 11079 value: function render() { 11080 if (this.notifyPlugins('beforeRender', { 11081 cancelable: true 11082 }) === false) { 11083 return; 11084 } 11085 if (animator.has(this)) { 11086 if (this.attached && !animator.running(this)) { 11087 animator.start(this); 11088 } 11089 } else { 11090 this.draw(); 11091 onAnimationsComplete({ 11092 chart: this 11093 }); 11094 } 11095 } 11096 }, { 11097 key: "draw", 11098 value: function draw() { 11099 var i; 11100 if (this._resizeBeforeDraw) { 11101 var _this$_resizeBeforeDr = this._resizeBeforeDraw, 11102 width = _this$_resizeBeforeDr.width, 11103 height = _this$_resizeBeforeDr.height; 11104 this._resizeBeforeDraw = null; 11105 this._resize(width, height); 11106 } 11107 this.clear(); 11108 if (this.width <= 0 || this.height <= 0) { 11109 return; 11110 } 11111 if (this.notifyPlugins('beforeDraw', { 11112 cancelable: true 11113 }) === false) { 11114 return; 11115 } 11116 var layers = this._layers; 11117 for (i = 0; i < layers.length && layers[i].z <= 0; ++i) { 11118 layers[i].draw(this.chartArea); 11119 } 11120 this._drawDatasets(); 11121 for (; i < layers.length; ++i) { 11122 layers[i].draw(this.chartArea); 11123 } 11124 this.notifyPlugins('afterDraw'); 11125 } 11126 }, { 11127 key: "_getSortedDatasetMetas", 11128 value: function _getSortedDatasetMetas(filterVisible) { 11129 var metasets = this._sortedMetasets; 11130 var result = []; 11131 var i, ilen; 11132 for (i = 0, ilen = metasets.length; i < ilen; ++i) { 11133 var meta = metasets[i]; 11134 if (!filterVisible || meta.visible) { 11135 result.push(meta); 11136 } 11137 } 11138 return result; 11139 } 11140 }, { 11141 key: "getSortedVisibleDatasetMetas", 11142 value: function getSortedVisibleDatasetMetas() { 11143 return this._getSortedDatasetMetas(true); 11144 } 11145 }, { 11146 key: "_drawDatasets", 11147 value: function _drawDatasets() { 11148 if (this.notifyPlugins('beforeDatasetsDraw', { 11149 cancelable: true 11150 }) === false) { 11151 return; 11152 } 11153 var metasets = this.getSortedVisibleDatasetMetas(); 11154 for (var i = metasets.length - 1; i >= 0; --i) { 11155 this._drawDataset(metasets[i]); 11156 } 11157 this.notifyPlugins('afterDatasetsDraw'); 11158 } 11159 }, { 11160 key: "_drawDataset", 11161 value: function _drawDataset(meta) { 11162 var ctx = this.ctx; 11163 var args = { 11164 meta: meta, 11165 index: meta.index, 11166 cancelable: true 11167 }; 11168 var clip = getDatasetClipArea(this, meta); 11169 if (this.notifyPlugins('beforeDatasetDraw', args) === false) { 11170 return; 11171 } 11172 if (clip) { 11173 clipArea(ctx, clip); 11174 } 11175 meta.controller.draw(); 11176 if (clip) { 11177 unclipArea(ctx); 11178 } 11179 args.cancelable = false; 11180 this.notifyPlugins('afterDatasetDraw', args); 11181 } 11182 }, { 11183 key: "isPointInArea", 11184 value: function isPointInArea(point) { 11185 return _isPointInArea(point, this.chartArea, this._minPadding); 11186 } 11187 }, { 11188 key: "getElementsAtEventForMode", 11189 value: function getElementsAtEventForMode(e, mode, options, useFinalPosition) { 11190 var method = Interaction.modes[mode]; 11191 if (typeof method === 'function') { 11192 return method(this, e, options, useFinalPosition); 11193 } 11194 return []; 11195 } 11196 }, { 11197 key: "getDatasetMeta", 11198 value: function getDatasetMeta(datasetIndex) { 11199 var dataset = this.data.datasets[datasetIndex]; 11200 var metasets = this._metasets; 11201 var meta = metasets.filter(function (x) { 11202 return x && x._dataset === dataset; 11203 }).pop(); 11204 if (!meta) { 11205 meta = { 11206 type: null, 11207 data: [], 11208 dataset: null, 11209 controller: null, 11210 hidden: null, 11211 xAxisID: null, 11212 yAxisID: null, 11213 order: dataset && dataset.order || 0, 11214 index: datasetIndex, 11215 _dataset: dataset, 11216 _parsed: [], 11217 _sorted: false 11218 }; 11219 metasets.push(meta); 11220 } 11221 return meta; 11222 } 11223 }, {
11224 key: "getContext", 11225 value: function getContext() { 11226 return this.$context || (this.$context = createContext(null, { 11227 chart: this, 11228 type: 'chart' 11229 })); 11230 } 11231 }, { 11232 key: "getVisibleDatasetCount", 11233 value: function getVisibleDatasetCount() { 11234 return this.getSortedVisibleDatasetMetas().length; 11235 } 11236 }, { 11237 key: "isDatasetVisible", 11238 value: function isDatasetVisible(datasetIndex) { 11239 var dataset = this.data.datasets[datasetIndex]; 11240 if (!dataset) { 11241 return false; 11242 } 11243 var meta = this.getDatasetMeta(datasetIndex); 11244 return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden; 11245 } 11246 }, { 11247 key: "setDatasetVisibility", 11248 value: function setDatasetVisibility(datasetIndex, visible) { 11249 var meta = this.getDatasetMeta(datasetIndex); 11250 meta.hidden = !visible; 11251 } 11252 }, { 11253 key: "toggleDataVisibility", 11254 value: function toggleDataVisibility(index) { 11255 this._hiddenIndices[index] = !this._hiddenIndices[index]; 11256 } 11257 }, { 11258 key: "getDataVisibility", 11259 value: function getDataVisibility(index) { 11260 return !this._hiddenIndices[index]; 11261 } 11262 }, { 11263 key: "_updateVisibility", 11264 value: function _updateVisibility(datasetIndex, dataIndex, visible) { 11265 var mode = visible ? 'show' : 'hide'; 11266 var meta = this.getDatasetMeta(datasetIndex); 11267 var anims = meta.controller._resolveAnimations(undefined, mode); 11268 if (defined(dataIndex)) { 11269 meta.data[dataIndex].hidden = !visible; 11270 this.update(); 11271 } else { 11272 this.setDatasetVisibility(datasetIndex, visible); 11273 anims.update(meta, { 11274 visible: visible 11275 }); 11276 this.update(function (ctx) { 11277 return ctx.datasetIndex === datasetIndex ? mode : undefined; 11278 }); 11279 } 11280 } 11281 }, { 11282 key: "hide", 11283 value: function hide(datasetIndex, dataIndex) { 11284 this._updateVisibility(datasetIndex, dataIndex, false); 11285 } 11286 }, { 11287 key: "show", 11288 value: function show(datasetIndex, dataIndex) { 11289 this._updateVisibility(datasetIndex, dataIndex, true); 11290 } 11291 }, { 11292 key: "_destroyDatasetMeta", 11293 value: function _destroyDatasetMeta(datasetIndex) { 11294 var meta = this._metasets[datasetIndex]; 11295 if (meta && meta.controller) { 11296 meta.controller._destroy(); 11297 } 11298 delete this._metasets[datasetIndex]; 11299 } 11300 }, { 11301 key: "_stop", 11302 value: function _stop() { 11303 var i, ilen; 11304 this.stop(); 11305 animator.remove(this); 11306 for (i = 0, ilen = this.data.datasets.length; i < ilen; ++i) { 11307 this._destroyDatasetMeta(i); 11308 } 11309 } 11310 }, { 11311 key: "destroy", 11312 value: function destroy() { 11313 this.notifyPlugins('beforeDestroy'); 11314 var canvas = this.canvas, 11315 ctx = this.ctx; 11316 this._stop(); 11317 this.config.clearCache(); 11318 if (canvas) { 11319 this.unbindEvents(); 11320 clearCanvas(canvas, ctx); 11321 this.platform.releaseContext(ctx); 11322 this.canvas = null; 11323 this.ctx = null; 11324 } 11325 delete instances[this.id]; 11326 this.notifyPlugins('afterDestroy'); 11327 } 11328 }, { 11329 key: "toBase64Image", 11330 value: function toBase64Image() { 11331 var _this$canvas; 11332 return (_this$canvas = this.canvas).toDataURL.apply(_this$canvas, arguments); 11333 } 11334 }, { 11335 key: "bindEvents", 11336 value: function bindEvents() { 11337 this.bindUserEvents(); 11338 if (this.options.responsive) { 11339 this.bindResponsiveEvents(); 11340 } else { 11341 this.attached = true; 11342 } 11343 } 11344 }, { 11345 key: "bindUserEvents", 11346 value: function bindUserEvents() { 11347 var _this16 = this; 11348 var listeners = this._listeners; 11349 var platform = this.platform; 11350 var _add = function _add(type, listener) { 11351 platform.addEventListener(_this16, type, listener); 11352 listeners[type] = listener; 11353 }; 11354 var listener = function listener(e, x, y) { 11355 e.offsetX = x; 11356 e.offsetY = y; 11357 _this16._eventHandler(e); 11358 }; 11359 each(this.options.events, function (type) { 11360 return _add(type, listener); 11361 }); 11362 } 11363 }, {
11364 key: "bindResponsiveEvents", 11365 value: function bindResponsiveEvents() { 11366 var _this17 = this; 11367 if (!this._responsiveListeners) { 11368 this._responsiveListeners = {}; 11369 } 11370 var listeners = this._responsiveListeners; 11371 var platform = this.platform; 11372 var _add = function _add(type, listener) { 11373 platform.addEventListener(_this17, type, listener); 11374 listeners[type] = listener; 11375 }; 11376 var _remove = function _remove(type, listener) { 11377 if (listeners[type]) { 11378 platform.removeEventListener(_this17, type, listener); 11379 delete listeners[type]; 11380 } 11381 }; 11382 var listener = function listener(width, height) { 11383 if (_this17.canvas) { 11384 _this17.resize(width, height); 11385 } 11386 }; 11387 var detached; 11388 var _attached = function attached() { 11389 _remove('attach', _attached); 11390 _this17.attached = true; 11391 _this17.resize(); 11392 _add('resize', listener); 11393 _add('detach', detached); 11394 }; 11395 detached = function detached() { 11396 _this17.attached = false; 11397 _remove('resize', listener); 11398 _this17._stop(); 11399 _this17._resize(0, 0); 11400 _add('attach', _attached); 11401 }; 11402 if (platform.isAttached(this.canvas)) { 11403 _attached(); 11404 } else { 11405 detached(); 11406 } 11407 } 11408 }, { 11409 key: "unbindEvents", 11410 value: function unbindEvents() { 11411 var _this18 = this; 11412 each(this._listeners, function (listener, type) { 11413 _this18.platform.removeEventListener(_this18, type, listener); 11414 }); 11415 this._listeners = {}; 11416 each(this._responsiveListeners, function (listener, type) { 11417 _this18.platform.removeEventListener(_this18, type, listener); 11418 }); 11419 this._responsiveListeners = undefined; 11420 } 11421 }, { 11422 key: "updateHoverStyle", 11423 value: function updateHoverStyle(items, mode, enabled) { 11424 var prefix = enabled ? 'set' : 'remove'; 11425 var meta, item, i, ilen; 11426 if (mode === 'dataset') { 11427 meta = this.getDatasetMeta(items[0].datasetIndex); 11428 meta.controller['_' + prefix + 'DatasetHoverStyle'](); 11429 } 11430 for (i = 0, ilen = items.length; i < ilen; ++i) { 11431 item = items[i]; 11432 var controller = item && this.getDatasetMeta(item.datasetIndex).controller; 11433 if (controller) { 11434 controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index); 11435 } 11436 } 11437 } 11438 }, { 11439 key: "getActiveElements", 11440 value: function getActiveElements() { 11441 return this._active || []; 11442 } 11443 }, { 11444 key: "setActiveElements", 11445 value: function setActiveElements(activeElements) { 11446 var _this19 = this; 11447 var lastActive = this._active || []; 11448 var active = activeElements.map(function (_ref4) { 11449 var datasetIndex = _ref4.datasetIndex, 11450 index = _ref4.index; 11451 var meta = _this19.getDatasetMeta(datasetIndex); 11452 if (!meta) { 11453 throw new Error('No dataset found at index ' + datasetIndex); 11454 } 11455 return { 11456 datasetIndex: datasetIndex, 11457 element: meta.data[index], 11458 index: index 11459 }; 11460 }); 11461 var changed = !_elementsEqual(active, lastActive); 11462 if (changed) { 11463 this._active = active; 11464 this._lastEvent = null; 11465 this._updateHoverStyles(active, lastActive); 11466 } 11467 } 11468 }, { 11469 key: "notifyPlugins", 11470 value: function notifyPlugins(hook, args, filter) { 11471 return this._plugins.notify(this, hook, args, filter); 11472 } 11473 }, { 11474 key: "isPluginEnabled", 11475 value: function isPluginEnabled(pluginId) { 11476 return this._plugins._cache.filter(function (p) { 11477 return p.plugin.id === pluginId; 11478 }).length === 1; 11479 } 11480 }, { 11481 key: "_updateHoverStyles", 11482 value: function _updateHoverStyles(active, lastActive, replay) { 11483 var hoverOptions = this.options.hover; 11484 var diff = function diff(a, b) { 11485 return a.filter(function (x) { 11486 return !b.some(function (y) { 11487 return x.datasetIndex === y.datasetIndex && x.index === y.index; 11488 }); 11489 }); 11490 }; 11491 var deactivated = diff(lastActive, active); 11492 var activated = replay ? active : diff(active, lastActive); 11493 if (deactivated.length) { 11494 this.updateHoverStyle(deactivated, hoverOptions.mode, false); 11495 } 11496 if (activated.length && hoverOptions.mode) { 11497 this.updateHoverStyle(activated, hoverOptions.mode, true); 11498 } 11499 } 11500 }, {
11501 key: "_eventHandler", 11502 value: function _eventHandler(e, replay) { 11503 var _this20 = this; 11504 var args = { 11505 event: e, 11506 replay: replay, 11507 cancelable: true, 11508 inChartArea: this.isPointInArea(e) 11509 }; 11510 var eventFilter = function eventFilter(plugin) { 11511 return (plugin.options.events || _this20.options.events).includes(e["native"].type); 11512 }; 11513 if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) { 11514 return; 11515 } 11516 var changed = this._handleEvent(e, replay, args.inChartArea); 11517 args.cancelable = false; 11518 this.notifyPlugins('afterEvent', args, eventFilter); 11519 if (changed || args.changed) { 11520 this.render(); 11521 } 11522 return this; 11523 } 11524 }, { 11525 key: "_handleEvent", 11526 value: function _handleEvent(e, replay, inChartArea) { 11527 var _this$_active = this._active, 11528 lastActive = _this$_active === void 0 ? [] : _this$_active, 11529 options = this.options; 11530 var useFinalPosition = replay; 11531 var active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition); 11532 var isClick = _isClickEvent(e); 11533 var lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick); 11534 if (inChartArea) { 11535 this._lastEvent = null; 11536 callback(options.onHover, [e, active, this], this); 11537 if (isClick) { 11538 callback(options.onClick, [e, active, this], this); 11539 } 11540 } 11541 var changed = !_elementsEqual(active, lastActive); 11542 if (changed || replay) { 11543 this._active = active; 11544 this._updateHoverStyles(active, lastActive, replay); 11545 } 11546 this._lastEvent = lastEvent; 11547 return changed; 11548 } 11549 }, { 11550 key: "_getActiveElements", 11551 value: function _getActiveElements(e, lastActive, inChartArea, useFinalPosition) { 11552 if (e.type === 'mouseout') { 11553 return []; 11554 } 11555 if (!inChartArea) { 11556 return lastActive; 11557 } 11558 var hoverOptions = this.options.hover; 11559 return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition); 11560 } 11561 }], [{ 11562 key: "register", 11563 value: function register() { 11564 registry.add.apply(registry, arguments); 11565 invalidatePlugins(); 11566 } 11567 }, { 11568 key: "unregister", 11569 value: function unregister() { 11570 registry.remove.apply(registry, arguments); 11571 invalidatePlugins(); 11572 } 11573 }]); 11574 }(); 11575 _defineProperty$1(Chart, "defaults", defaults); 11576 _defineProperty$1(Chart, "instances", instances); 11577 _defineProperty$1(Chart, "overrides", overrides); 11578 _defineProperty$1(Chart, "registry", registry); 11579 _defineProperty$1(Chart, "version", version); 11580 _defineProperty$1(Chart, "getChart", getChart);
11581 function invalidatePlugins() { 11582 return each(Chart.instances, function (chart) { 11583 return chart._plugins.invalidate(); 11584 }); 11585 } 11586 function clipSelf(ctx, element, endAngle) { 11587 var startAngle = element.startAngle, 11588 x = element.x, 11589 y = element.y, 11590 outerRadius = element.outerRadius, 11591 innerRadius = element.innerRadius, 11592 options = element.options; 11593 var borderWidth = options.borderWidth, 11594 borderJoinStyle = options.borderJoinStyle; 11595 var outerAngleClip = Math.min(borderWidth / outerRadius, _normalizeAngle(startAngle - endAngle)); 11596 ctx.beginPath(); 11597 ctx.arc(x, y, outerRadius - borderWidth / 2, startAngle + outerAngleClip / 2, endAngle - outerAngleClip / 2); 11598 if (innerRadius > 0) { 11599 var innerAngleClip = Math.min(borderWidth / innerRadius, _normalizeAngle(startAngle - endAngle)); 11600 ctx.arc(x, y, innerRadius + borderWidth / 2, endAngle - innerAngleClip / 2, startAngle + innerAngleClip / 2, true); 11601 } else { 11602 var clipWidth = Math.min(borderWidth / 2, outerRadius * _normalizeAngle(startAngle - endAngle)); 11603 if (borderJoinStyle === 'round') { 11604 ctx.arc(x, y, clipWidth, endAngle - PI / 2, startAngle + PI / 2, true); 11605 } else if (borderJoinStyle === 'bevel') { 11606 var r = 2 * clipWidth * clipWidth; 11607 var endX = -r * Math.cos(endAngle + PI / 2) + x; 11608 var endY = -r * Math.sin(endAngle + PI / 2) + y; 11609 var startX = r * Math.cos(startAngle + PI / 2) + x; 11610 var startY = r * Math.sin(startAngle + PI / 2) + y; 11611 ctx.lineTo(endX, endY); 11612 ctx.lineTo(startX, startY); 11613 } 11614 } 11615 ctx.closePath(); 11616 ctx.moveTo(0, 0); 11617 ctx.rect(0, 0, ctx.canvas.width, ctx.canvas.height); 11618 ctx.clip('evenodd'); 11619 } 11620 function clipArc(ctx, element, endAngle) { 11621 var startAngle = element.startAngle, 11622 pixelMargin = element.pixelMargin, 11623 x = element.x, 11624 y = element.y, 11625 outerRadius = element.outerRadius, 11626 innerRadius = element.innerRadius; 11627 var angleMargin = pixelMargin / outerRadius; 11628 // Draw an inner border by clipping the arc and drawing a double-width border 11629 // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders 11630 ctx.beginPath(); 11631 ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin); 11632 if (innerRadius > pixelMargin) { 11633 angleMargin = pixelMargin / innerRadius; 11634 ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true); 11635 } else { 11636 ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI); 11637 } 11638 ctx.closePath(); 11639 ctx.clip(); 11640 } 11641 function toRadiusCorners(value) { 11642 return _readValueToProps(value, ['outerStart', 'outerEnd', 'innerStart', 'innerEnd']); 11643 } 11644 /** 11645 * Parse border radius from the provided options 11646 */ 11647 function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) { 11648 var o = toRadiusCorners(arc.options.borderRadius); 11649 var halfThickness = (outerRadius - innerRadius) / 2; 11650 var innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2); 11651 // Outer limits are complicated. We want to compute the available angular distance at 11652 // a radius of outerRadius - borderRadius because for small angular distances, this term limits. 11653 // We compute at r = outerRadius - borderRadius because this circle defines the center of the border corners. 11654 // 11655 // If the borderRadius is large, that value can become negative. 11656 // This causes the outer borders to lose their radius entirely, which is rather unexpected. To solve that, if borderRadius > outerRadius 11657 // we know that the thickness term will dominate and compute the limits at that point 11658 var computeOuterLimit = function computeOuterLimit(val) { 11659 var outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2; 11660 return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit)); 11661 }; 11662 return { 11663 outerStart: computeOuterLimit(o.outerStart), 11664 outerEnd: computeOuterLimit(o.outerEnd), 11665 innerStart: _limitValue(o.innerStart, 0, innerLimit), 11666 innerEnd: _limitValue(o.innerEnd, 0, innerLimit) 11667 }; 11668 } 11669 /** 11670 * Convert (r, ð) to (x, y) 11671 */ 11672 function rThetaToXY(r, theta, x, y) { 11673 return { 11674 x: x + r * Math.cos(theta), 11675 y: y + r * Math.sin(theta) 11676 }; 11677 } 11678 /** 11679 * Path the arc, respecting border radius by separating into left and right halves. 11680 * 11681 * Start End 11682 * 11683 * 1--->a--->2 Outer 11684 * / \ 11685 * 8 3 11686 * | | 11687 * | | 11688 * 7 4 11689 * \ / 11690 * 6<---b<---5 Inner 11691 */ 11692 function pathArc(ctx, element, offset, spacing, end, circular) { 11693 var x = element.x, 11694 y = element.y, 11695 start = element.startAngle, 11696 pixelMargin = element.pixelMargin, 11697 innerR = element.innerRadius; 11698 var outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0); 11699 var innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0; 11700 var spacingOffset = 0; 11701 var alpha = end - start; 11702 if (spacing) { 11703 // When spacing is present, it is the same for all items 11704 // So we adjust the start and end angle of the arc such that 11705 // the distance is the same as it would be without the spacing 11706 var noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0; 11707 var noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0; 11708 var avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2; 11709 var adjustedAngle = avNogSpacingRadius !== 0 ? alpha * avNogSpacingRadius / (avNogSpacingRadius + spacing) : alpha; 11710 spacingOffset = (alpha - adjustedAngle) / 2; 11711 } 11712 var beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius; 11713 var angleOffset = (alpha - beta) / 2; 11714 var startAngle = start + angleOffset + spacingOffset; 11715 var endAngle = end - angleOffset - spacingOffset; 11716 var _parseBorderRadius$ = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle), 11717 outerStart = _parseBorderRadius$.outerStart, 11718 outerEnd = _parseBorderRadius$.outerEnd, 11719 innerStart = _parseBorderRadius$.innerStart, 11720 innerEnd = _parseBorderRadius$.innerEnd; 11721 var outerStartAdjustedRadius = outerRadius - outerStart; 11722 var outerEndAdjustedRadius = outerRadius - outerEnd; 11723 var outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius; 11724 var outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius; 11725 var innerStartAdjustedRadius = innerRadius + innerStart; 11726 var innerEndAdjustedRadius = innerRadius + innerEnd; 11727 var innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius; 11728 var innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius; 11729 ctx.beginPath(); 11730 if (circular) { 11731 // The first arc segments from point 1 to point a to point 2 11732 var outerMidAdjustedAngle = (outerStartAdjustedAngle + outerEndAdjustedAngle) / 2; 11733 ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerMidAdjustedAngle); 11734 ctx.arc(x, y, outerRadius, outerMidAdjustedAngle, outerEndAdjustedAngle); 11735 // The corner segment from point 2 to point 3 11736 if (outerEnd > 0) { 11737 var pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y); 11738 ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI); 11739 } 11740 // The line from point 3 to point 4 11741 var p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);
vendor: 4,093 bytes, lines 11742-11841
11742 ctx.lineTo(p4.x, p4.y); 11743 // The corner segment from point 4 to point 5 11744 if (innerEnd > 0) { 11745 var _pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y); 11746 ctx.arc(_pCenter.x, _pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI); 11747 } 11748 // The inner arc from point 5 to point b to point 6 11749 var innerMidAdjustedAngle = (endAngle - innerEnd / innerRadius + (startAngle + innerStart / innerRadius)) / 2; 11750 ctx.arc(x, y, innerRadius, endAngle - innerEnd / innerRadius, innerMidAdjustedAngle, true); 11751 ctx.arc(x, y, innerRadius, innerMidAdjustedAngle, startAngle + innerStart / innerRadius, true); 11752 // The corner segment from point 6 to point 7 11753 if (innerStart > 0) { 11754 var _pCenter2 = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y); 11755 ctx.arc(_pCenter2.x, _pCenter2.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI); 11756 } 11757 // The line from point 7 to point 8 11758 var p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y); 11759 ctx.lineTo(p8.x, p8.y); 11760 // The corner segment from point 8 to point 1 11761 if (outerStart > 0) { 11762 var _pCenter3 = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y); 11763 ctx.arc(_pCenter3.x, _pCenter3.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle); 11764 } 11765 } else { 11766 ctx.moveTo(x, y); 11767 var outerStartX = Math.cos(outerStartAdjustedAngle) * outerRadius + x; 11768 var outerStartY = Math.sin(outerStartAdjustedAngle) * outerRadius + y; 11769 ctx.lineTo(outerStartX, outerStartY); 11770 var outerEndX = Math.cos(outerEndAdjustedAngle) * outerRadius + x; 11771 var outerEndY = Math.sin(outerEndAdjustedAngle) * outerRadius + y; 11772 ctx.lineTo(outerEndX, outerEndY); 11773 } 11774 ctx.closePath(); 11775 } 11776 function drawArc(ctx, element, offset, spacing, circular) { 11777 var fullCircles = element.fullCircles, 11778 startAngle = element.startAngle, 11779 circumference = element.circumference; 11780 var endAngle = element.endAngle; 11781 if (fullCircles) { 11782 pathArc(ctx, element, offset, spacing, endAngle, circular); 11783 for (var i = 0; i < fullCircles; ++i) { 11784 ctx.fill(); 11785 } 11786 if (!isNaN(circumference)) { 11787 endAngle = startAngle + (circumference % TAU || TAU); 11788 } 11789 } 11790 pathArc(ctx, element, offset, spacing, endAngle, circular); 11791 ctx.fill(); 11792 return endAngle; 11793 } 11794 function drawBorder(ctx, element, offset, spacing, circular) { 11795 var fullCircles = element.fullCircles, 11796 startAngle = element.startAngle, 11797 circumference = element.circumference, 11798 options = element.options; 11799 var borderWidth = options.borderWidth, 11800 borderJoinStyle = options.borderJoinStyle, 11801 borderDash = options.borderDash, 11802 borderDashOffset = options.borderDashOffset, 11803 borderRadius = options.borderRadius; 11804 var inner = options.borderAlign === 'inner'; 11805 if (!borderWidth) { 11806 return; 11807 } 11808 ctx.setLineDash(borderDash || []); 11809 ctx.lineDashOffset = borderDashOffset; 11810 if (inner) { 11811 ctx.lineWidth = borderWidth * 2; 11812 ctx.lineJoin = borderJoinStyle || 'round'; 11813 } else { 11814 ctx.lineWidth = borderWidth; 11815 ctx.lineJoin = borderJoinStyle || 'bevel'; 11816 } 11817 var endAngle = element.endAngle; 11818 if (fullCircles) { 11819 pathArc(ctx, element, offset, spacing, endAngle, circular); 11820 for (var i = 0; i < fullCircles; ++i) { 11821 ctx.stroke(); 11822 } 11823 if (!isNaN(circumference)) { 11824 endAngle = startAngle + (circumference % TAU || TAU); 11825 } 11826 } 11827 if (inner) { 11828 clipArc(ctx, element, endAngle); 11829 } 11830 if (options.selfJoin && endAngle - startAngle >= PI && borderRadius === 0 && borderJoinStyle !== 'miter') { 11831 clipSelf(ctx, element, endAngle); 11832 } 11833 if (!fullCircles) { 11834 pathArc(ctx, element, offset, spacing, endAngle, circular); 11835 ctx.stroke(); 11836 } 11837 } 11838 var ArcElement = /*#__PURE__*/function (_Element3) { 11839 function ArcElement(cfg) { 11840 var _this21; 11841 _classCallCheck$1(this, ArcElement);
11842 _this21 = _callSuper(this, ArcElement); 11843 _defineProperty$1(_this21, "circumference", void 0); 11844 _defineProperty$1(_this21, "endAngle", void 0); 11845 _defineProperty$1(_this21, "fullCircles", void 0); 11846 _defineProperty$1(_this21, "innerRadius", void 0); 11847 _defineProperty$1(_this21, "outerRadius", void 0); 11848 _defineProperty$1(_this21, "pixelMargin", void 0); 11849 _defineProperty$1(_this21, "startAngle", void 0); 11850 _this21.options = undefined; 11851 _this21.circumference = undefined; 11852 _this21.startAngle = undefined; 11853 _this21.endAngle = undefined; 11854 _this21.innerRadius = undefined; 11855 _this21.outerRadius = undefined; 11856 _this21.pixelMargin = 0; 11857 _this21.fullCircles = 0; 11858 if (cfg) { 11859 Object.assign(_this21, cfg); 11860 } 11861 return _this21; 11862 } 11863 _inherits$1(ArcElement, _Element3); 11864 return _createClass$1(ArcElement, [{ 11865 key: "inRange", 11866 value: function inRange(chartX, chartY, useFinalPosition) { 11867 var point = this.getProps(['x', 'y'], useFinalPosition); 11868 var _getAngleFromPoint2 = getAngleFromPoint(point, { 11869 x: chartX, 11870 y: chartY 11871 }), 11872 angle = _getAngleFromPoint2.angle, 11873 distance = _getAngleFromPoint2.distance; 11874 var _this$getProps2 = this.getProps(['startAngle', 'endAngle', 'innerRadius', 'outerRadius', 'circumference'], useFinalPosition), 11875 startAngle = _this$getProps2.startAngle, 11876 endAngle = _this$getProps2.endAngle, 11877 innerRadius = _this$getProps2.innerRadius, 11878 outerRadius = _this$getProps2.outerRadius, 11879 circumference = _this$getProps2.circumference; 11880 var rAdjust = (this.options.spacing + this.options.borderWidth) / 2; 11881 var _circumference = valueOrDefault(circumference, endAngle - startAngle); 11882 var nonZeroBetween = _angleBetween(angle, startAngle, endAngle) && startAngle !== endAngle; 11883 var betweenAngles = _circumference >= TAU || nonZeroBetween; 11884 var withinRadius = _isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust); 11885 return betweenAngles && withinRadius; 11886 } 11887 }, { 11888 key: "getCenterPoint", 11889 value: function getCenterPoint(useFinalPosition) { 11890 var _this$getProps3 = this.getProps(['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius'], useFinalPosition), 11891 x = _this$getProps3.x, 11892 y = _this$getProps3.y, 11893 startAngle = _this$getProps3.startAngle, 11894 endAngle = _this$getProps3.endAngle, 11895 innerRadius = _this$getProps3.innerRadius, 11896 outerRadius = _this$getProps3.outerRadius; 11897 var _this$options11 = this.options, 11898 offset = _this$options11.offset, 11899 spacing = _this$options11.spacing; 11900 var halfAngle = (startAngle + endAngle) / 2; 11901 var halfRadius = (innerRadius + outerRadius + spacing + offset) / 2; 11902 return { 11903 x: x + Math.cos(halfAngle) * halfRadius, 11904 y: y + Math.sin(halfAngle) * halfRadius 11905 }; 11906 } 11907 }, { 11908 key: "tooltipPosition", 11909 value: function tooltipPosition(useFinalPosition) { 11910 return this.getCenterPoint(useFinalPosition); 11911 } 11912 }, { 11913 key: "draw", 11914 value: function draw(ctx) { 11915 var options = this.options, 11916 circumference = this.circumference; 11917 var offset = (options.offset || 0) / 4; 11918 var spacing = (options.spacing || 0) / 2; 11919 var circular = options.circular; 11920 this.pixelMargin = options.borderAlign === 'inner' ? 0.33 : 0; 11921 this.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0; 11922 if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) { 11923 return; 11924 } 11925 ctx.save(); 11926 var halfAngle = (this.startAngle + this.endAngle) / 2; 11927 ctx.translate(Math.cos(halfAngle) * offset, Math.sin(halfAngle) * offset); 11928 var fix = 1 - Math.sin(Math.min(PI, circumference || 0)); 11929 var radiusOffset = offset * fix; 11930 ctx.fillStyle = options.backgroundColor; 11931 ctx.strokeStyle = options.borderColor; 11932 drawArc(ctx, this, radiusOffset, spacing, circular); 11933 drawBorder(ctx, this, radiusOffset, spacing, circular);
11934 ctx.restore(); 11935 } 11936 }]); 11937 }(Element); 11938 _defineProperty$1(ArcElement, "id", 'arc'); 11939 _defineProperty$1(ArcElement, "defaults", { 11940 borderAlign: 'center', 11941 borderColor: '#fff', 11942 borderDash: [], 11943 borderDashOffset: 0, 11944 borderJoinStyle: undefined, 11945 borderRadius: 0, 11946 borderWidth: 2, 11947 offset: 0, 11948 spacing: 0, 11949 angle: undefined, 11950 circular: true, 11951 selfJoin: false 11952 }); 11953 _defineProperty$1(ArcElement, "defaultRoutes", { 11954 backgroundColor: 'backgroundColor' 11955 }); 11956 _defineProperty$1(ArcElement, "descriptors", { 11957 _scriptable: true, 11958 _indexable: function _indexable(name) { 11959 return name !== 'borderDash'; 11960 } 11961 }); 11962 function setStyle(ctx, options) { 11963 var style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : options; 11964 ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle); 11965 ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash)); 11966 ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset); 11967 ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle); 11968 ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth); 11969 ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor); 11970 } 11971 function lineTo(ctx, previous, target) { 11972 ctx.lineTo(target.x, target.y); 11973 } 11974 function getLineMethod(options) { 11975 if (options.stepped) { 11976 return _steppedLineTo; 11977 } 11978 if (options.tension || options.cubicInterpolationMode === 'monotone') { 11979 return _bezierCurveTo; 11980 } 11981 return lineTo; 11982 } 11983 function pathVars(points, segment) { 11984 var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; 11985 var count = points.length; 11986 var _params$start = params.start, 11987 paramsStart = _params$start === void 0 ? 0 : _params$start, 11988 _params$end = params.end, 11989 paramsEnd = _params$end === void 0 ? count - 1 : _params$end; 11990 var segmentStart = segment.start, 11991 segmentEnd = segment.end; 11992 var start = Math.max(paramsStart, segmentStart); 11993 var end = Math.min(paramsEnd, segmentEnd); 11994 var outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd; 11995 return { 11996 count: count, 11997 start: start, 11998 loop: segment.loop, 11999 ilen: end < start && !outside ? count + end - start : end - start 12000 }; 12001 } 12002 function pathSegment(ctx, line, segment, params) { 12003 var points = line.points, 12004 options = line.options; 12005 var _pathVars = pathVars(points, segment, params), 12006 count = _pathVars.count, 12007 start = _pathVars.start, 12008 loop = _pathVars.loop, 12009 ilen = _pathVars.ilen; 12010 var lineMethod = getLineMethod(options); 12011 var _ref5 = params || {}, 12012 _ref5$move = _ref5.move, 12013 move = _ref5$move === void 0 ? true : _ref5$move, 12014 reverse = _ref5.reverse; 12015 var i, point, prev; 12016 for (i = 0; i <= ilen; ++i) { 12017 point = points[(start + (reverse ? ilen - i : i)) % count]; 12018 if (point.skip) { 12019 continue; 12020 } else if (move) { 12021 ctx.moveTo(point.x, point.y); 12022 move = false; 12023 } else { 12024 lineMethod(ctx, prev, point, reverse, options.stepped); 12025 } 12026 prev = point; 12027 } 12028 if (loop) { 12029 point = points[(start + (reverse ? ilen : 0)) % count]; 12030 lineMethod(ctx, prev, point, reverse, options.stepped); 12031 } 12032 return !!loop; 12033 } 12034 function fastPathSegment(ctx, line, segment, params) { 12035 var points = line.points; 12036 var _pathVars2 = pathVars(points, segment, params), 12037 count = _pathVars2.count, 12038 start = _pathVars2.start, 12039 ilen = _pathVars2.ilen; 12040 var _ref6 = params || {}, 12041 _ref6$move = _ref6.move, 12042 move = _ref6$move === void 0 ? true : _ref6$move, 12043 reverse = _ref6.reverse; 12044 var avgX = 0; 12045 var countX = 0; 12046 var i, point, prevX, minY, maxY, lastY; 12047 var pointIndex = function pointIndex(index) { 12048 return (start + (reverse ? ilen - index : index)) % count; 12049 }; 12050 var drawX = function drawX() { 12051 if (minY !== maxY) { 12052 ctx.lineTo(avgX, maxY); 12053 ctx.lineTo(avgX, minY); 12054 ctx.lineTo(avgX, lastY); 12055 } 12056 }; 12057 if (move) { 12058 point = points[pointIndex(0)]; 12059 ctx.moveTo(point.x, point.y); 12060 } 12061 for (i = 0; i <= ilen; ++i) { 12062 point = points[pointIndex(i)]; 12063 if (point.skip) { 12064 continue; 12065 } 12066 var x = point.x; 12067 var y = point.y; 12068 var truncX = x | 0; 12069 if (truncX === prevX) { 12070 if (y < minY) { 12071 minY = y; 12072 } else if (y > maxY) { 12073 maxY = y; 12074 } 12075 avgX = (countX * avgX + x) / ++countX; 12076 } else { 12077 drawX(); 12078 ctx.lineTo(x, y); 12079 prevX = truncX; 12080 countX = 0; 12081 minY = maxY = y; 12082 } 12083 lastY = y; 12084 } 12085 drawX(); 12086 } 12087 function _getSegmentMethod(line) { 12088 var opts = line.options; 12089 var borderDash = opts.borderDash && opts.borderDash.length; 12090 var useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash; 12091 return useFastPath ? fastPathSegment : pathSegment; 12092 } 12093 function _getInterpolationMethod(options) { 12094 if (options.stepped) { 12095 return _steppedInterpolation; 12096 } 12097 if (options.tension || options.cubicInterpolationMode === 'monotone') { 12098 return _bezierInterpolation; 12099 } 12100 return _pointInLine; 12101 } 12102 function strokePathWithCache(ctx, line, start, count) { 12103 var path = line._path; 12104 if (!path) { 12105 path = line._path = new Path2D(); 12106 if (line.path(path, start, count)) {
12107 path.closePath(); 12108 } 12109 } 12110 setStyle(ctx, line.options); 12111 ctx.stroke(path); 12112 } 12113 function strokePathDirect(ctx, line, start, count) { 12114 var segments = line.segments, 12115 options = line.options; 12116 var segmentMethod = _getSegmentMethod(line); 12117 var _iterator15 = _createForOfIteratorHelper$1(segments), 12118 _step15; 12119 try { 12120 for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) { 12121 var segment = _step15.value; 12122 setStyle(ctx, options, segment.style); 12123 ctx.beginPath(); 12124 if (segmentMethod(ctx, line, segment, { 12125 start: start, 12126 end: start + count - 1 12127 })) { 12128 ctx.closePath(); 12129 } 12130 ctx.stroke(); 12131 } 12132 } catch (err) { 12133 _iterator15.e(err); 12134 } finally { 12135 _iterator15.f(); 12136 } 12137 } 12138 var usePath2D = typeof Path2D === 'function'; 12139 function _draw(ctx, line, start, count) { 12140 if (usePath2D && !line.options.segment) { 12141 strokePathWithCache(ctx, line, start, count); 12142 } else { 12143 strokePathDirect(ctx, line, start, count); 12144 } 12145 } 12146 var LineElement = /*#__PURE__*/function (_Element4) { 12147 function LineElement(cfg) { 12148 var _this22; 12149 _classCallCheck$1(this, LineElement); 12150 _this22 = _callSuper(this, LineElement); 12151 _this22.animated = true; 12152 _this22.options = undefined; 12153 _this22._chart = undefined; 12154 _this22._loop = undefined; 12155 _this22._fullLoop = undefined; 12156 _this22._path = undefined; 12157 _this22._points = undefined; 12158 _this22._segments = undefined; 12159 _this22._decimated = false; 12160 _this22._pointsUpdated = false; 12161 _this22._datasetIndex = undefined; 12162 if (cfg) { 12163 Object.assign(_this22, cfg); 12164 } 12165 return _this22; 12166 } 12167 _inherits$1(LineElement, _Element4); 12168 return _createClass$1(LineElement, [{ 12169 key: "updateControlPoints", 12170 value: function updateControlPoints(chartArea, indexAxis) { 12171 var options = this.options; 12172 if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) { 12173 var loop = options.spanGaps ? this._loop : this._fullLoop; 12174 _updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis); 12175 this._pointsUpdated = true; 12176 } 12177 } 12178 }, { 12179 key: "points", 12180 get: function get() { 12181 return this._points; 12182 }, 12183 set: function set(points) { 12184 this._points = points; 12185 delete this._segments; 12186 delete this._path; 12187 this._pointsUpdated = false; 12188 } 12189 }, { 12190 key: "segments", 12191 get: function get() { 12192 return this._segments || (this._segments = _computeSegments(this, this.options.segment)); 12193 } 12194 }, { 12195 key: "first", 12196 value: function first() { 12197 var segments = this.segments; 12198 var points = this.points; 12199 return segments.length && points[segments[0].start]; 12200 } 12201 }, { 12202 key: "last", 12203 value: function last() { 12204 var segments = this.segments; 12205 var points = this.points; 12206 var count = segments.length; 12207 return count && points[segments[count - 1].end]; 12208 } 12209 }, { 12210 key: "interpolate", 12211 value: function interpolate(point, property) { 12212 var options = this.options; 12213 var value = point[property]; 12214 var points = this.points; 12215 var segments = _boundSegments(this, { 12216 property: property, 12217 start: value, 12218 end: value 12219 }); 12220 if (!segments.length) { 12221 return; 12222 } 12223 var result = []; 12224 var _interpolate = _getInterpolationMethod(options); 12225 var i, ilen; 12226 for (i = 0, ilen = segments.length; i < ilen; ++i) { 12227 var _segments$i = segments[i], 12228 start = _segments$i.start, 12229 end = _segments$i.end; 12230 var p1 = points[start]; 12231 var p2 = points[end]; 12232 if (p1 === p2) { 12233 result.push(p1); 12234 continue; 12235 } 12236 var t = Math.abs((value - p1[property]) / (p2[property] - p1[property])); 12237 var interpolated = _interpolate(p1, p2, t, options.stepped); 12238 interpolated[property] = point[property]; 12239 result.push(interpolated); 12240 } 12241 return result.length === 1 ? result[0] : result; 12242 } 12243 }, {
12244 key: "pathSegment", 12245 value: function pathSegment(ctx, segment, params) { 12246 var segmentMethod = _getSegmentMethod(this); 12247 return segmentMethod(ctx, this, segment, params); 12248 } 12249 }, { 12250 key: "path", 12251 value: function path(ctx, start, count) { 12252 var segments = this.segments; 12253 var segmentMethod = _getSegmentMethod(this); 12254 var loop = this._loop; 12255 start = start || 0; 12256 count = count || this.points.length - start; 12257 var _iterator16 = _createForOfIteratorHelper$1(segments), 12258 _step16; 12259 try { 12260 for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) { 12261 var segment = _step16.value; 12262 loop &= segmentMethod(ctx, this, segment, { 12263 start: start, 12264 end: start + count - 1 12265 }); 12266 } 12267 } catch (err) { 12268 _iterator16.e(err); 12269 } finally { 12270 _iterator16.f(); 12271 } 12272 return !!loop; 12273 } 12274 }, { 12275 key: "draw", 12276 value: function draw(ctx, chartArea, start, count) { 12277 var options = this.options || {}; 12278 var points = this.points || []; 12279 if (points.length && options.borderWidth) { 12280 ctx.save(); 12281 _draw(ctx, this, start, count); 12282 ctx.restore(); 12283 } 12284 if (this.animated) { 12285 this._pointsUpdated = false; 12286 this._path = undefined; 12287 } 12288 } 12289 }]); 12290 }(Element); 12291 _defineProperty$1(LineElement, "id", 'line'); 12292 _defineProperty$1(LineElement, "defaults", { 12293 borderCapStyle: 'butt', 12294 borderDash: [], 12295 borderDashOffset: 0, 12296 borderJoinStyle: 'miter', 12297 borderWidth: 3, 12298 capBezierPoints: true, 12299 cubicInterpolationMode: 'default', 12300 fill: false, 12301 spanGaps: false, 12302 stepped: false, 12303 tension: 0 12304 }); 12305 _defineProperty$1(LineElement, "defaultRoutes", { 12306 backgroundColor: 'backgroundColor', 12307 borderColor: 'borderColor' 12308 }); 12309 _defineProperty$1(LineElement, "descriptors", { 12310 _scriptable: true, 12311 _indexable: function _indexable(name) { 12312 return name !== 'borderDash' && name !== 'fill'; 12313 } 12314 }); 12315 function inRange$1(el, pos, axis, useFinalPosition) { 12316 var options = el.options; 12317 var _el$getProps = el.getProps([axis], useFinalPosition), 12318 value = _el$getProps[axis]; 12319 return Math.abs(pos - value) < options.radius + options.hitRadius; 12320 } 12321 var PointElement = /*#__PURE__*/function (_Element5) { 12322 function PointElement(cfg) { 12323 var _this23; 12324 _classCallCheck$1(this, PointElement); 12325 _this23 = _callSuper(this, PointElement); 12326 _defineProperty$1(_this23, "parsed", void 0); 12327 _defineProperty$1(_this23, "skip", void 0); 12328 _defineProperty$1(_this23, "stop", void 0); 12329 _this23.options = undefined; 12330 _this23.parsed = undefined; 12331 _this23.skip = undefined; 12332 _this23.stop = undefined; 12333 if (cfg) { 12334 Object.assign(_this23, cfg); 12335 } 12336 return _this23; 12337 } 12338 _inherits$1(PointElement, _Element5); 12339 return _createClass$1(PointElement, [{ 12340 key: "inRange", 12341 value: function inRange(mouseX, mouseY, useFinalPosition) { 12342 var options = this.options; 12343 var _this$getProps4 = this.getProps(['x', 'y'], useFinalPosition), 12344 x = _this$getProps4.x, 12345 y = _this$getProps4.y; 12346 return Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2) < Math.pow(options.hitRadius + options.radius, 2); 12347 } 12348 }, { 12349 key: "inXRange", 12350 value: function inXRange(mouseX, useFinalPosition) { 12351 return inRange$1(this, mouseX, 'x', useFinalPosition); 12352 } 12353 }, { 12354 key: "inYRange", 12355 value: function inYRange(mouseY, useFinalPosition) { 12356 return inRange$1(this, mouseY, 'y', useFinalPosition); 12357 } 12358 }, { 12359 key: "getCenterPoint", 12360 value: function getCenterPoint(useFinalPosition) { 12361 var _this$getProps5 = this.getProps(['x', 'y'], useFinalPosition), 12362 x = _this$getProps5.x, 12363 y = _this$getProps5.y; 12364 return { 12365 x: x, 12366 y: y 12367 }; 12368 } 12369 }, { 12370 key: "size", 12371 value: function size(options) { 12372 options = options || this.options || {}; 12373 var radius = options.radius || 0; 12374 radius = Math.max(radius, radius && options.hoverRadius || 0);
12375 var borderWidth = radius && options.borderWidth || 0; 12376 return (radius + borderWidth) * 2; 12377 } 12378 }, { 12379 key: "draw", 12380 value: function draw(ctx, area) { 12381 var options = this.options; 12382 if (this.skip || options.radius < 0.1 || !_isPointInArea(this, area, this.size(options) / 2)) { 12383 return; 12384 } 12385 ctx.strokeStyle = options.borderColor; 12386 ctx.lineWidth = options.borderWidth; 12387 ctx.fillStyle = options.backgroundColor; 12388 drawPoint(ctx, options, this.x, this.y); 12389 } 12390 }, { 12391 key: "getRange", 12392 value: function getRange() { 12393 var options = this.options || {}; 12394 // @ts-expect-error Fallbacks should never be hit in practice 12395 return options.radius + options.hitRadius; 12396 } 12397 }]); 12398 }(Element); 12399 _defineProperty$1(PointElement, "id", 'point'); 12400 /** 12401 * @type {any} 12402 */ 12403 _defineProperty$1(PointElement, "defaults", { 12404 borderWidth: 1, 12405 hitRadius: 1, 12406 hoverBorderWidth: 1, 12407 hoverRadius: 4, 12408 pointStyle: 'circle', 12409 radius: 3, 12410 rotation: 0 12411 }); 12412 /** 12413 * @type {any} 12414 */ 12415 _defineProperty$1(PointElement, "defaultRoutes", { 12416 backgroundColor: 'backgroundColor', 12417 borderColor: 'borderColor' 12418 }); 12419 function getBarBounds(bar, useFinalPosition) { 12420 var _bar$getProps = bar.getProps(['x', 'y', 'base', 'width', 'height'], useFinalPosition), 12421 x = _bar$getProps.x, 12422 y = _bar$getProps.y, 12423 base = _bar$getProps.base, 12424 width = _bar$getProps.width, 12425 height = _bar$getProps.height; 12426 var left, right, top, bottom, half; 12427 if (bar.horizontal) { 12428 half = height / 2; 12429 left = Math.min(x, base); 12430 right = Math.max(x, base); 12431 top = y - half; 12432 bottom = y + half; 12433 } else { 12434 half = width / 2; 12435 left = x - half; 12436 right = x + half; 12437 top = Math.min(y, base); 12438 bottom = Math.max(y, base); 12439 } 12440 return { 12441 left: left, 12442 top: top, 12443 right: right, 12444 bottom: bottom 12445 }; 12446 } 12447 function skipOrLimit(skip, value, min, max) { 12448 return skip ? 0 : _limitValue(value, min, max); 12449 } 12450 function parseBorderWidth(bar, maxW, maxH) { 12451 var value = bar.options.borderWidth; 12452 var skip = bar.borderSkipped; 12453 var o = toTRBL(value); 12454 return { 12455 t: skipOrLimit(skip.top, o.top, 0, maxH), 12456 r: skipOrLimit(skip.right, o.right, 0, maxW), 12457 b: skipOrLimit(skip.bottom, o.bottom, 0, maxH), 12458 l: skipOrLimit(skip.left, o.left, 0, maxW) 12459 }; 12460 } 12461 function parseBorderRadius(bar, maxW, maxH) { 12462 var _bar$getProps2 = bar.getProps(['enableBorderRadius']), 12463 enableBorderRadius = _bar$getProps2.enableBorderRadius; 12464 var value = bar.options.borderRadius; 12465 var o = toTRBLCorners(value); 12466 var maxR = Math.min(maxW, maxH); 12467 var skip = bar.borderSkipped; 12468 var enableBorder = enableBorderRadius || isObject(value); 12469 return { 12470 topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR), 12471 topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR), 12472 bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR), 12473 bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR) 12474 }; 12475 } 12476 function boundingRects(bar) { 12477 var bounds = getBarBounds(bar); 12478 var width = bounds.right - bounds.left; 12479 var height = bounds.bottom - bounds.top; 12480 var border = parseBorderWidth(bar, width / 2, height / 2); 12481 var radius = parseBorderRadius(bar, width / 2, height / 2); 12482 return { 12483 outer: { 12484 x: bounds.left, 12485 y: bounds.top, 12486 w: width, 12487 h: height, 12488 radius: radius 12489 }, 12490 inner: { 12491 x: bounds.left + border.l, 12492 y: bounds.top + border.t, 12493 w: width - border.l - border.r, 12494 h: height - border.t - border.b, 12495 radius: { 12496 topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)), 12497 topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)), 12498 bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)), 12499 bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r)) 12500 } 12501 } 12502 }; 12503 } 12504 function _inRange(bar, x, y, useFinalPosition) { 12505 var skipX = x === null; 12506 var skipY = y === null; 12507 var skipBoth = skipX && skipY; 12508 var bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition); 12509 return bounds && (skipX || _isBetween(x, bounds.left, bounds.right)) && (skipY || _isBetween(y, bounds.top, bounds.bottom)); 12510 } 12511 function hasRadius(radius) {
12512 return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight; 12513 } 12514 function addNormalRectPath(ctx, rect) { 12515 ctx.rect(rect.x, rect.y, rect.w, rect.h); 12516 } 12517 function inflateRect(rect, amount) { 12518 var refRect = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; 12519 var x = rect.x !== refRect.x ? -amount : 0; 12520 var y = rect.y !== refRect.y ? -amount : 0; 12521 var w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x; 12522 var h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y; 12523 return { 12524 x: rect.x + x, 12525 y: rect.y + y, 12526 w: rect.w + w, 12527 h: rect.h + h, 12528 radius: rect.radius 12529 }; 12530 } 12531 var BarElement = /*#__PURE__*/function (_Element6) { 12532 function BarElement(cfg) { 12533 var _this24; 12534 _classCallCheck$1(this, BarElement); 12535 _this24 = _callSuper(this, BarElement); 12536 _this24.options = undefined; 12537 _this24.horizontal = undefined; 12538 _this24.base = undefined; 12539 _this24.width = undefined; 12540 _this24.height = undefined; 12541 _this24.inflateAmount = undefined; 12542 if (cfg) { 12543 Object.assign(_this24, cfg); 12544 } 12545 return _this24; 12546 } 12547 _inherits$1(BarElement, _Element6); 12548 return _createClass$1(BarElement, [{ 12549 key: "draw", 12550 value: function draw(ctx) { 12551 var inflateAmount = this.inflateAmount, 12552 _this$options12 = this.options, 12553 borderColor = _this$options12.borderColor, 12554 backgroundColor = _this$options12.backgroundColor; 12555 var _boundingRects = boundingRects(this), 12556 inner = _boundingRects.inner, 12557 outer = _boundingRects.outer; 12558 var addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath; 12559 ctx.save(); 12560 if (outer.w !== inner.w || outer.h !== inner.h) { 12561 ctx.beginPath(); 12562 addRectPath(ctx, inflateRect(outer, inflateAmount, inner)); 12563 ctx.clip(); 12564 addRectPath(ctx, inflateRect(inner, -inflateAmount, outer)); 12565 ctx.fillStyle = borderColor; 12566 ctx.fill('evenodd'); 12567 } 12568 ctx.beginPath(); 12569 addRectPath(ctx, inflateRect(inner, inflateAmount)); 12570 ctx.fillStyle = backgroundColor; 12571 ctx.fill(); 12572 ctx.restore(); 12573 } 12574 }, { 12575 key: "inRange", 12576 value: function inRange(mouseX, mouseY, useFinalPosition) { 12577 return _inRange(this, mouseX, mouseY, useFinalPosition); 12578 } 12579 }, { 12580 key: "inXRange", 12581 value: function inXRange(mouseX, useFinalPosition) { 12582 return _inRange(this, mouseX, null, useFinalPosition); 12583 } 12584 }, { 12585 key: "inYRange", 12586 value: function inYRange(mouseY, useFinalPosition) { 12587 return _inRange(this, null, mouseY, useFinalPosition); 12588 } 12589 }, { 12590 key: "getCenterPoint", 12591 value: function getCenterPoint(useFinalPosition) { 12592 var _this$getProps6 = this.getProps(['x', 'y', 'base', 'horizontal'], useFinalPosition), 12593 x = _this$getProps6.x, 12594 y = _this$getProps6.y, 12595 base = _this$getProps6.base, 12596 horizontal = _this$getProps6.horizontal; 12597 return { 12598 x: horizontal ? (x + base) / 2 : x, 12599 y: horizontal ? y : (y + base) / 2 12600 }; 12601 } 12602 }, { 12603 key: "getRange", 12604 value: function getRange(axis) { 12605 return axis === 'x' ? this.width / 2 : this.height / 2; 12606 } 12607 }]); 12608 }(Element); 12609 _defineProperty$1(BarElement, "id", 'bar'); 12610 _defineProperty$1(BarElement, "defaults", { 12611 borderSkipped: 'start', 12612 borderWidth: 0, 12613 borderRadius: 0, 12614 inflateAmount: 'auto', 12615 pointStyle: undefined 12616 }); 12617 _defineProperty$1(BarElement, "defaultRoutes", { 12618 backgroundColor: 'backgroundColor', 12619 borderColor: 'borderColor' 12620 }); 12621 var elements = /*#__PURE__*/Object.freeze({ 12622 __proto__: null, 12623 ArcElement: ArcElement, 12624 BarElement: BarElement, 12625 LineElement: LineElement, 12626 PointElement: PointElement 12627 }); 12628 var BORDER_COLORS = ['rgb(54, 162, 235)', 'rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(153, 102, 255)', 'rgb(201, 203, 207)' // grey 12629 ]; 12630 // Border colors with 50% transparency 12631 var BACKGROUND_COLORS = /* #__PURE__ */BORDER_COLORS.map(function (color) { 12632 return color.replace('rgb(', 'rgba(').replace(')', ', 0.5)'); 12633 }); 12634 function getBorderColor(i) { 12635 return BORDER_COLORS[i % BORDER_COLORS.length]; 12636 }
12637 function getBackgroundColor(i) { 12638 return BACKGROUND_COLORS[i % BACKGROUND_COLORS.length]; 12639 } 12640 function colorizeDefaultDataset(dataset, i) { 12641 dataset.borderColor = getBorderColor(i); 12642 dataset.backgroundColor = getBackgroundColor(i); 12643 return ++i; 12644 } 12645 function colorizeDoughnutDataset(dataset, i) { 12646 dataset.backgroundColor = dataset.data.map(function () { 12647 return getBorderColor(i++); 12648 }); 12649 return i; 12650 } 12651 function colorizePolarAreaDataset(dataset, i) { 12652 dataset.backgroundColor = dataset.data.map(function () { 12653 return getBackgroundColor(i++); 12654 }); 12655 return i; 12656 } 12657 function getColorizer(chart) { 12658 var i = 0; 12659 return function (dataset, datasetIndex) { 12660 var controller = chart.getDatasetMeta(datasetIndex).controller; 12661 if (controller instanceof DoughnutController) { 12662 i = colorizeDoughnutDataset(dataset, i); 12663 } else if (controller instanceof PolarAreaController) { 12664 i = colorizePolarAreaDataset(dataset, i); 12665 } else if (controller) { 12666 i = colorizeDefaultDataset(dataset, i); 12667 } 12668 }; 12669 } 12670 function containsColorsDefinitions(descriptors) { 12671 var k; 12672 for (k in descriptors) { 12673 if (descriptors[k].borderColor || descriptors[k].backgroundColor) { 12674 return true; 12675 } 12676 } 12677 return false; 12678 } 12679 function containsColorsDefinition(descriptor) { 12680 return descriptor && (descriptor.borderColor || descriptor.backgroundColor); 12681 } 12682 function containsDefaultColorsDefenitions() { 12683 return defaults.borderColor !== 'rgba(0,0,0,0.1)' || defaults.backgroundColor !== 'rgba(0,0,0,0.1)'; 12684 } 12685 var plugin_colors = { 12686 id: 'colors', 12687 defaults: { 12688 enabled: true, 12689 forceOverride: false 12690 }, 12691 beforeLayout: function beforeLayout(chart, _args, options) { 12692 if (!options.enabled) { 12693 return; 12694 } 12695 var _chart$config = chart.config, 12696 datasets = _chart$config.data.datasets, 12697 chartOptions = _chart$config.options; 12698 var elements = chartOptions.elements; 12699 var containsColorDefenition = containsColorsDefinitions(datasets) || containsColorsDefinition(chartOptions) || elements && containsColorsDefinitions(elements) || containsDefaultColorsDefenitions(); 12700 if (!options.forceOverride && containsColorDefenition) { 12701 return; 12702 } 12703 var colorizer = getColorizer(chart); 12704 datasets.forEach(colorizer); 12705 } 12706 }; 12707 function lttbDecimation(data, start, count, availableWidth, options) { 12708 var samples = options.samples || availableWidth; 12709 if (samples >= count) { 12710 return data.slice(start, start + count); 12711 } 12712 var decimated = []; 12713 var bucketWidth = (count - 2) / (samples - 2); 12714 var sampledIndex = 0; 12715 var endIndex = start + count - 1; 12716 var a = start; 12717 var i, maxAreaPoint, maxArea, area, nextA; 12718 decimated[sampledIndex++] = data[a]; 12719 for (i = 0; i < samples - 2; i++) { 12720 var avgX = 0; 12721 var avgY = 0; 12722 var j = void 0; 12723 var avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start; 12724 var avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start; 12725 var avgRangeLength = avgRangeEnd - avgRangeStart; 12726 for (j = avgRangeStart; j < avgRangeEnd; j++) { 12727 avgX += data[j].x; 12728 avgY += data[j].y; 12729 } 12730 avgX /= avgRangeLength; 12731 avgY /= avgRangeLength; 12732 var rangeOffs = Math.floor(i * bucketWidth) + 1 + start; 12733 var rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start; 12734 var _data$a = data[a], 12735 pointAx = _data$a.x, 12736 pointAy = _data$a.y; 12737 maxArea = area = -1; 12738 for (j = rangeOffs; j < rangeTo; j++) { 12739 area = 0.5 * Math.abs((pointAx - avgX) * (data[j].y - pointAy) - (pointAx - data[j].x) * (avgY - pointAy)); 12740 if (area > maxArea) { 12741 maxArea = area; 12742 maxAreaPoint = data[j]; 12743 nextA = j; 12744 } 12745 } 12746 decimated[sampledIndex++] = maxAreaPoint; 12747 a = nextA; 12748 } 12749 decimated[sampledIndex++] = data[endIndex]; 12750 return decimated; 12751 } 12752 function minMaxDecimation(data, start, count, availableWidth) { 12753 var avgX = 0; 12754 var countX = 0; 12755 var i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY; 12756 var decimated = []; 12757 var endIndex = start + count - 1; 12758 var xMin = data[start].x; 12759 var xMax = data[endIndex].x; 12760 var dx = xMax - xMin; 12761 for (i = start; i < start + count; ++i) { 12762 point = data[i]; 12763 x = (point.x - xMin) / dx * availableWidth; 12764 y = point.y; 12765 var truncX = x | 0; 12766 if (truncX === prevX) { 12767 if (y < minY) { 12768 minY = y; 12769 minIndex = i; 12770 } else if (y > maxY) { 12771 maxY = y; 12772 maxIndex = i; 12773 } 12774 avgX = (countX * avgX + point.x) / ++countX; 12775 } else { 12776 var lastIndex = i - 1; 12777 if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) { 12778 var intermediateIndex1 = Math.min(minIndex, maxIndex); 12779 var intermediateIndex2 = Math.max(minIndex, maxIndex); 12780 if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {
12781 decimated.push(_objectSpread2(_objectSpread2({}, data[intermediateIndex1]), {}, { 12782 x: avgX 12783 })); 12784 } 12785 if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) { 12786 decimated.push(_objectSpread2(_objectSpread2({}, data[intermediateIndex2]), {}, { 12787 x: avgX 12788 })); 12789 } 12790 } 12791 if (i > 0 && lastIndex !== startIndex) { 12792 decimated.push(data[lastIndex]); 12793 } 12794 decimated.push(point); 12795 prevX = truncX; 12796 countX = 0; 12797 minY = maxY = y; 12798 minIndex = maxIndex = startIndex = i; 12799 } 12800 } 12801 return decimated; 12802 } 12803 function cleanDecimatedDataset(dataset) { 12804 if (dataset._decimated) { 12805 var data = dataset._data; 12806 delete dataset._decimated; 12807 delete dataset._data; 12808 Object.defineProperty(dataset, 'data', { 12809 configurable: true, 12810 enumerable: true, 12811 writable: true, 12812 value: data 12813 }); 12814 } 12815 } 12816 function cleanDecimatedData(chart) { 12817 chart.data.datasets.forEach(function (dataset) { 12818 cleanDecimatedDataset(dataset); 12819 }); 12820 } 12821 function getStartAndCountOfVisiblePointsSimplified(meta, points) { 12822 var pointCount = points.length; 12823 var start = 0; 12824 var count; 12825 var iScale = meta.iScale; 12826 var _iScale$getUserBounds = iScale.getUserBounds(), 12827 min = _iScale$getUserBounds.min, 12828 max = _iScale$getUserBounds.max, 12829 minDefined = _iScale$getUserBounds.minDefined, 12830 maxDefined = _iScale$getUserBounds.maxDefined; 12831 if (minDefined) { 12832 start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1); 12833 } 12834 if (maxDefined) { 12835 count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start; 12836 } else { 12837 count = pointCount - start; 12838 } 12839 return { 12840 start: start, 12841 count: count 12842 }; 12843 } 12844 var plugin_decimation = { 12845 id: 'decimation', 12846 defaults: { 12847 algorithm: 'min-max', 12848 enabled: false 12849 }, 12850 beforeElementsUpdate: function beforeElementsUpdate(chart, args, options) { 12851 if (!options.enabled) { 12852 cleanDecimatedData(chart); 12853 return; 12854 } 12855 var availableWidth = chart.width; 12856 chart.data.datasets.forEach(function (dataset, datasetIndex) { 12857 var _data = dataset._data, 12858 indexAxis = dataset.indexAxis; 12859 var meta = chart.getDatasetMeta(datasetIndex); 12860 var data = _data || dataset.data; 12861 if (resolve([indexAxis, chart.options.indexAxis]) === 'y') { 12862 return; 12863 } 12864 if (!meta.controller.supportsDecimation) { 12865 return; 12866 } 12867 var xAxis = chart.scales[meta.xAxisID]; 12868 if (xAxis.type !== 'linear' && xAxis.type !== 'time') { 12869 return; 12870 } 12871 if (chart.options.parsing) { 12872 return; 12873 } 12874 var _getStartAndCountOfVi3 = getStartAndCountOfVisiblePointsSimplified(meta, data), 12875 start = _getStartAndCountOfVi3.start, 12876 count = _getStartAndCountOfVi3.count; 12877 var threshold = options.threshold || 4 * availableWidth; 12878 if (count <= threshold) { 12879 cleanDecimatedDataset(dataset); 12880 return; 12881 } 12882 if (isNullOrUndef(_data)) { 12883 dataset._data = data; 12884 delete dataset.data; 12885 Object.defineProperty(dataset, 'data', { 12886 configurable: true, 12887 enumerable: true, 12888 get: function get() { 12889 return this._decimated; 12890 }, 12891 set: function set(d) { 12892 this._data = d; 12893 } 12894 }); 12895 } 12896 var decimated; 12897 switch (options.algorithm) { 12898 case 'lttb': 12899 decimated = lttbDecimation(data, start, count, availableWidth, options); 12900 break; 12901 case 'min-max': 12902 decimated = minMaxDecimation(data, start, count, availableWidth); 12903 break; 12904 default: 12905 throw new Error("Unsupported decimation algorithm '".concat(options.algorithm, "'")); 12906 } 12907 dataset._decimated = decimated; 12908 }); 12909 }, 12910 destroy: function destroy(chart) { 12911 cleanDecimatedData(chart); 12912 } 12913 }; 12914 function _segments(line, target, property) { 12915 var segments = line.segments; 12916 var points = line.points; 12917 var tpoints = target.points; 12918 var parts = []; 12919 var _iterator17 = _createForOfIteratorHelper$1(segments), 12920 _step17; 12921 try { 12922 for (_iterator17.s();
12922 !(_step17 = _iterator17.n()).done;) { 12923 var segment = _step17.value; 12924 var start = segment.start, 12925 end = segment.end; 12926 end = _findSegmentEnd(start, end, points); 12927 var bounds = _getBounds(property, points[start], points[end], segment.loop); 12928 if (!target.segments) { 12929 parts.push({ 12930 source: segment, 12931 target: bounds, 12932 start: points[start], 12933 end: points[end] 12934 }); 12935 continue; 12936 } 12937 var targetSegments = _boundSegments(target, bounds); 12938 var _iterator18 = _createForOfIteratorHelper$1(targetSegments), 12939 _step18; 12940 try { 12941 for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) { 12942 var tgt = _step18.value; 12943 var subBounds = _getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop); 12944 var fillSources = _boundSegment(segment, points, subBounds); 12945 var _iterator19 = _createForOfIteratorHelper$1(fillSources), 12946 _step19; 12947 try { 12948 for (_iterator19.s(); !(_step19 = _iterator19.n()).done;) { 12949 var fillSource = _step19.value; 12950 parts.push({ 12951 source: fillSource, 12952 target: tgt, 12953 start: _defineProperty$1({}, property, _getEdge(bounds, subBounds, 'start', Math.max)), 12954 end: _defineProperty$1({}, property, _getEdge(bounds, subBounds, 'end', Math.min)) 12955 }); 12956 } 12957 } catch (err) { 12958 _iterator19.e(err); 12959 } finally { 12960 _iterator19.f(); 12961 } 12962 } 12963 } catch (err) { 12964 _iterator18.e(err); 12965 } finally { 12966 _iterator18.f(); 12967 } 12968 } 12969 } catch (err) { 12970 _iterator17.e(err); 12971 } finally { 12972 _iterator17.f(); 12973 } 12974 return parts; 12975 } 12976 function _getBounds(property, first, last, loop) { 12977 if (loop) { 12978 return; 12979 } 12980 var start = first[property]; 12981 var end = last[property]; 12982 if (property === 'angle') { 12983 start = _normalizeAngle(start); 12984 end = _normalizeAngle(end); 12985 } 12986 return { 12987 property: property, 12988 start: start, 12989 end: end 12990 }; 12991 } 12992 function _pointsFromSegments(boundary, line) { 12993 var _ref7 = boundary || {}, 12994 _ref7$x = _ref7.x, 12995 x = _ref7$x === void 0 ? null : _ref7$x, 12996 _ref7$y = _ref7.y, 12997 y = _ref7$y === void 0 ? null : _ref7$y; 12998 var linePoints = line.points; 12999 var points = []; 13000 line.segments.forEach(function (_ref8) { 13001 var start = _ref8.start, 13002 end = _ref8.end; 13003 end = _findSegmentEnd(start, end, linePoints); 13004 var first = linePoints[start]; 13005 var last = linePoints[end]; 13006 if (y !== null) { 13007 points.push({ 13008 x: first.x, 13009 y: y 13010 }); 13011 points.push({ 13012 x: last.x, 13013 y: y 13014 }); 13015 } else if (x !== null) { 13016 points.push({ 13017 x: x, 13018 y: first.y 13019 }); 13020 points.push({ 13021 x: x, 13022 y: last.y 13023 }); 13024 } 13025 }); 13026 return points; 13027 } 13028 function _findSegmentEnd(start, end, points) { 13029 for (; end > start; end--) { 13030 var point = points[end]; 13031 if (!isNaN(point.x) && !isNaN(point.y)) { 13032 break; 13033 } 13034 } 13035 return end; 13036 } 13037 function _getEdge(a, b, prop, fn) { 13038 if (a && b) { 13039 return fn(a[prop], b[prop]); 13040 } 13041 return a ? a[prop] : b ? b[prop] : 0; 13042 } 13043 function _createBoundaryLine(boundary, line) { 13044 var points = []; 13045 var _loop = false; 13046 if (isArray(boundary)) { 13047 _loop = true; 13048 points = boundary; 13049 } else { 13050 points = _pointsFromSegments(boundary, line); 13051 } 13052 return points.length ? new LineElement({ 13053 points: points, 13054 options: { 13055 tension: 0 13056 }, 13057 _loop: _loop, 13058 _fullLoop: _loop 13059 }) : null; 13060 } 13061 function _shouldApplyFill(source) { 13062 return source && source.fill !== false; 13063 } 13064 function _resolveTarget(sources, index, propagate) { 13065 var source = sources[index]; 13066 var fill = source.fill; 13067 var visited = [index]; 13068 var target; 13069 if (!propagate) { 13070 return fill; 13071 } 13072 while (fill !== false && visited.indexOf(fill) === -1) { 13073 if (!isNumberFinite(fill)) { 13074 return fill; 13075 } 13076 target = sources[fill]; 13077 if (!target) { 13078 return false;
13079 } 13080 if (target.visible) { 13081 return fill; 13082 } 13083 visited.push(fill); 13084 fill = target.fill; 13085 } 13086 return false; 13087 } 13088 function _decodeFill(line, index, count) { 13089 var fill = parseFillOption(line); 13090 if (isObject(fill)) { 13091 return isNaN(fill.value) ? false : fill; 13092 } 13093 var target = parseFloat(fill); 13094 if (isNumberFinite(target) && Math.floor(target) === target) { 13095 return decodeTargetIndex(fill[0], index, target, count); 13096 } 13097 return ['origin', 'start', 'end', 'stack', 'shape'].indexOf(fill) >= 0 && fill; 13098 } 13099 function decodeTargetIndex(firstCh, index, target, count) { 13100 if (firstCh === '-' || firstCh === '+') { 13101 target = index + target; 13102 } 13103 if (target === index || target < 0 || target >= count) { 13104 return false; 13105 } 13106 return target; 13107 } 13108 function _getTargetPixel(fill, scale) { 13109 var pixel = null; 13110 if (fill === 'start') { 13111 pixel = scale.bottom; 13112 } else if (fill === 'end') { 13113 pixel = scale.top; 13114 } else if (isObject(fill)) { 13115 pixel = scale.getPixelForValue(fill.value); 13116 } else if (scale.getBasePixel) { 13117 pixel = scale.getBasePixel(); 13118 } 13119 return pixel; 13120 } 13121 function _getTargetValue(fill, scale, startValue) { 13122 var value; 13123 if (fill === 'start') { 13124 value = startValue; 13125 } else if (fill === 'end') { 13126 value = scale.options.reverse ? scale.min : scale.max; 13127 } else if (isObject(fill)) { 13128 value = fill.value; 13129 } else { 13130 value = scale.getBaseValue(); 13131 } 13132 return value; 13133 } 13134 function parseFillOption(line) { 13135 var options = line.options; 13136 var fillOption = options.fill; 13137 var fill = valueOrDefault(fillOption && fillOption.target, fillOption); 13138 if (fill === undefined) { 13139 fill = !!options.backgroundColor; 13140 } 13141 if (fill === false || fill === null) { 13142 return false; 13143 } 13144 if (fill === true) { 13145 return 'origin'; 13146 } 13147 return fill; 13148 } 13149 function _buildStackLine(source) { 13150 var scale = source.scale, 13151 index = source.index, 13152 line = source.line; 13153 var points = []; 13154 var segments = line.segments; 13155 var sourcePoints = line.points; 13156 var linesBelow = getLinesBelow(scale, index); 13157 linesBelow.push(_createBoundaryLine({ 13158 x: null, 13159 y: scale.bottom 13160 }, line)); 13161 for (var i = 0; i < segments.length; i++) { 13162 var segment = segments[i]; 13163 for (var j = segment.start; j <= segment.end; j++) { 13164 addPointsBelow(points, sourcePoints[j], linesBelow); 13165 } 13166 } 13167 return new LineElement({ 13168 points: points, 13169 options: {} 13170 }); 13171 } 13172 function getLinesBelow(scale, index) { 13173 var below = []; 13174 var metas = scale.getMatchingVisibleMetas('line'); 13175 for (var i = 0; i < metas.length; i++) { 13176 var meta = metas[i]; 13177 if (meta.index === index) { 13178 break; 13179 } 13180 if (!meta.hidden) { 13181 below.unshift(meta.dataset); 13182 } 13183 } 13184 return below; 13185 } 13186 function addPointsBelow(points, sourcePoint, linesBelow) { 13187 var postponed = []; 13188 for (var j = 0; j < linesBelow.length; j++) { 13189 var line = linesBelow[j]; 13190 var _findPoint = findPoint(line, sourcePoint, 'x'), 13191 first = _findPoint.first, 13192 last = _findPoint.last, 13193 point = _findPoint.point; 13194 if (!point || first && last) { 13195 continue; 13196 } 13197 if (first) { 13198 postponed.unshift(point); 13199 } else { 13200 points.push(point); 13201 if (!last) { 13202 break; 13203 } 13204 } 13205 } 13206 points.push.apply(points, postponed); 13207 } 13208 function findPoint(line, sourcePoint, property) { 13209 var point = line.interpolate(sourcePoint, property); 13210 if (!point) { 13211 return {}; 13212 } 13213 var pointValue = point[property]; 13214 var segments = line.segments; 13215 var linePoints = line.points; 13216 var first = false; 13217 var last = false; 13218 for (var i = 0; i < segments.length; i++) { 13219 var segment = segments[i]; 13220 var firstValue = linePoints[segment.start][property]; 13221 var lastValue = linePoints[segment.end][property]; 13222 if (_isBetween(pointValue, firstValue, lastValue)) { 13223 first = pointValue === firstValue; 13224 last = pointValue === lastValue; 13225 break; 13226 } 13227 } 13228 return { 13229 first: first, 13230 last: last, 13231 point: point 13232 }; 13233 } 13234 var simpleArc = /*#__PURE__*/function () { 13235 function simpleArc(opts) { 13236 _classCallCheck$1(this, simpleArc); 13237 this.x = opts.x; 13238 this.y = opts.y; 13239 this.radius = opts.radius; 13240 } 13241 return _createClass$1(simpleArc, [{ 13242 key: "pathSegment", 13243 value: function pathSegment(ctx, bounds, opts) { 13244 var x = this.x, 13245 y = this.y, 13246 radius = this.radius; 13247 bounds = bounds || { 13248 start: 0, 13249 end: TAU 13250 }; 13251 ctx.arc(x, y, radius, bounds.end, bounds.start, true); 13252 return !opts.bounds; 13253 } 13254 }, {
13255 key: "interpolate", 13256 value: function interpolate(point) { 13257 var x = this.x, 13258 y = this.y, 13259 radius = this.radius; 13260 var angle = point.angle; 13261 return { 13262 x: x + Math.cos(angle) * radius, 13263 y: y + Math.sin(angle) * radius, 13264 angle: angle 13265 }; 13266 } 13267 }]); 13268 }(); 13269 function _getTarget(source) { 13270 var chart = source.chart, 13271 fill = source.fill, 13272 line = source.line; 13273 if (isNumberFinite(fill)) { 13274 return getLineByIndex(chart, fill); 13275 } 13276 if (fill === 'stack') { 13277 return _buildStackLine(source); 13278 } 13279 if (fill === 'shape') { 13280 return true; 13281 } 13282 var boundary = computeBoundary(source); 13283 if (boundary instanceof simpleArc) { 13284 return boundary; 13285 } 13286 return _createBoundaryLine(boundary, line); 13287 } 13288 function getLineByIndex(chart, index) { 13289 var meta = chart.getDatasetMeta(index); 13290 var visible = meta && chart.isDatasetVisible(index); 13291 return visible ? meta.dataset : null; 13292 } 13293 function computeBoundary(source) { 13294 var scale = source.scale || {}; 13295 if (scale.getPointPositionForValue) { 13296 return computeCircularBoundary(source); 13297 } 13298 return computeLinearBoundary(source); 13299 } 13300 function computeLinearBoundary(source) { 13301 var _source$scale = source.scale, 13302 scale = _source$scale === void 0 ? {} : _source$scale, 13303 fill = source.fill; 13304 var pixel = _getTargetPixel(fill, scale); 13305 if (isNumberFinite(pixel)) { 13306 var horizontal = scale.isHorizontal(); 13307 return { 13308 x: horizontal ? pixel : null, 13309 y: horizontal ? null : pixel 13310 }; 13311 } 13312 return null; 13313 } 13314 function computeCircularBoundary(source) { 13315 var scale = source.scale, 13316 fill = source.fill; 13317 var options = scale.options; 13318 var length = scale.getLabels().length; 13319 var start = options.reverse ? scale.max : scale.min; 13320 var value = _getTargetValue(fill, scale, start); 13321 var target = []; 13322 if (options.grid.circular) { 13323 var center = scale.getPointPositionForValue(0, start); 13324 return new simpleArc({ 13325 x: center.x, 13326 y: center.y, 13327 radius: scale.getDistanceFromCenterForValue(value) 13328 }); 13329 } 13330 for (var i = 0; i < length; ++i) { 13331 target.push(scale.getPointPositionForValue(i, value)); 13332 } 13333 return target; 13334 } 13335 function _drawfill(ctx, source, area) { 13336 var target = _getTarget(source); 13337 var chart = source.chart, 13338 index = source.index, 13339 line = source.line, 13340 scale = source.scale, 13341 axis = source.axis; 13342 var lineOpts = line.options; 13343 var fillOption = lineOpts.fill; 13344 var color = lineOpts.backgroundColor; 13345 var _ref9 = fillOption || {}, 13346 _ref9$above = _ref9.above, 13347 above = _ref9$above === void 0 ? color : _ref9$above, 13348 _ref9$below = _ref9.below, 13349 below = _ref9$below === void 0 ? color : _ref9$below; 13350 var meta = chart.getDatasetMeta(index); 13351 var clip = getDatasetClipArea(chart, meta); 13352 if (target && line.points.length) { 13353 clipArea(ctx, area); 13354 doFill(ctx, { 13355 line: line, 13356 target: target, 13357 above: above, 13358 below: below, 13359 area: area, 13360 scale: scale, 13361 axis: axis, 13362 clip: clip 13363 }); 13364 unclipArea(ctx); 13365 } 13366 } 13367 function doFill(ctx, cfg) { 13368 var line = cfg.line, 13369 target = cfg.target, 13370 above = cfg.above, 13371 below = cfg.below, 13372 area = cfg.area, 13373 scale = cfg.scale, 13374 clip = cfg.clip; 13375 var property = line._loop ? 'angle' : cfg.axis; 13376 ctx.save(); 13377 var fillColor = below; 13378 if (below !== above) { 13379 if (property === 'x') { 13380 clipVertical(ctx, target, area.top); 13381 fill(ctx, { 13382 line: line, 13383 target: target, 13384 color: above, 13385 scale: scale, 13386 property: property, 13387 clip: clip 13388 }); 13389 ctx.restore(); 13390 ctx.save(); 13391 clipVertical(ctx, target, area.bottom); 13392 } else if (property === 'y') { 13393 clipHorizontal(ctx, target, area.left); 13394 fill(ctx, { 13395 line: line, 13396 target: target, 13397 color: below, 13398 scale: scale, 13399 property: property, 13400 clip: clip 13401 });
13402 ctx.restore(); 13403 ctx.save(); 13404 clipHorizontal(ctx, target, area.right); 13405 fillColor = above; 13406 } 13407 } 13408 fill(ctx, { 13409 line: line, 13410 target: target, 13411 color: fillColor, 13412 scale: scale, 13413 property: property, 13414 clip: clip 13415 }); 13416 ctx.restore(); 13417 } 13418 function clipVertical(ctx, target, clipY) { 13419 var segments = target.segments, 13420 points = target.points; 13421 var first = true; 13422 var lineLoop = false; 13423 ctx.beginPath(); 13424 var _iterator20 = _createForOfIteratorHelper$1(segments), 13425 _step20; 13426 try { 13427 for (_iterator20.s(); !(_step20 = _iterator20.n()).done;) { 13428 var segment = _step20.value; 13429 var start = segment.start, 13430 end = segment.end; 13431 var firstPoint = points[start]; 13432 var lastPoint = points[_findSegmentEnd(start, end, points)]; 13433 if (first) { 13434 ctx.moveTo(firstPoint.x, firstPoint.y); 13435 first = false; 13436 } else { 13437 ctx.lineTo(firstPoint.x, clipY); 13438 ctx.lineTo(firstPoint.x, firstPoint.y); 13439 } 13440 lineLoop = !!target.pathSegment(ctx, segment, { 13441 move: lineLoop 13442 }); 13443 if (lineLoop) { 13444 ctx.closePath(); 13445 } else { 13446 ctx.lineTo(lastPoint.x, clipY); 13447 } 13448 } 13449 } catch (err) { 13450 _iterator20.e(err); 13451 } finally { 13452 _iterator20.f(); 13453 } 13454 ctx.lineTo(target.first().x, clipY); 13455 ctx.closePath(); 13456 ctx.clip(); 13457 } 13458 function clipHorizontal(ctx, target, clipX) { 13459 var segments = target.segments, 13460 points = target.points; 13461 var first = true; 13462 var lineLoop = false; 13463 ctx.beginPath(); 13464 var _iterator21 = _createForOfIteratorHelper$1(segments), 13465 _step21; 13466 try { 13467 for (_iterator21.s(); !(_step21 = _iterator21.n()).done;) { 13468 var segment = _step21.value; 13469 var start = segment.start, 13470 end = segment.end; 13471 var firstPoint = points[start]; 13472 var lastPoint = points[_findSegmentEnd(start, end, points)]; 13473 if (first) { 13474 ctx.moveTo(firstPoint.x, firstPoint.y); 13475 first = false; 13476 } else { 13477 ctx.lineTo(clipX, firstPoint.y); 13478 ctx.lineTo(firstPoint.x, firstPoint.y); 13479 } 13480 lineLoop = !!target.pathSegment(ctx, segment, { 13481 move: lineLoop 13482 }); 13483 if (lineLoop) { 13484 ctx.closePath(); 13485 } else { 13486 ctx.lineTo(clipX, lastPoint.y); 13487 } 13488 } 13489 } catch (err) { 13490 _iterator21.e(err); 13491 } finally { 13492 _iterator21.f(); 13493 } 13494 ctx.lineTo(clipX, target.first().y); 13495 ctx.closePath(); 13496 ctx.clip(); 13497 } 13498 function fill(ctx, cfg) { 13499 var line = cfg.line, 13500 target = cfg.target, 13501 property = cfg.property, 13502 color = cfg.color, 13503 scale = cfg.scale, 13504 clip = cfg.clip; 13505 var segments = _segments(line, target, property); 13506 var _iterator22 = _createForOfIteratorHelper$1(segments), 13507 _step22; 13508 try { 13509 for (_iterator22.s();
13509 !(_step22 = _iterator22.n()).done;) { 13510 var _step22$value = _step22.value, 13511 src = _step22$value.source, 13512 tgt = _step22$value.target, 13513 start = _step22$value.start, 13514 end = _step22$value.end; 13515 var _src$style = src.style, 13516 _src$style2 = _src$style === void 0 ? {} : _src$style, 13517 _src$style2$backgroun = _src$style2.backgroundColor, 13518 backgroundColor = _src$style2$backgroun === void 0 ? color : _src$style2$backgroun; 13519 var notShape = target !== true; 13520 ctx.save(); 13521 ctx.fillStyle = backgroundColor; 13522 clipBounds(ctx, scale, clip, notShape && _getBounds(property, start, end)); 13523 ctx.beginPath(); 13524 var lineLoop = !!line.pathSegment(ctx, src); 13525 var loop = void 0; 13526 if (notShape) { 13527 if (lineLoop) { 13528 ctx.closePath(); 13529 } else { 13530 interpolatedLineTo(ctx, target, end, property); 13531 } 13532 var targetLoop = !!target.pathSegment(ctx, tgt, { 13533 move: lineLoop, 13534 reverse: true 13535 }); 13536 loop = lineLoop && targetLoop; 13537 if (!loop) { 13538 interpolatedLineTo(ctx, target, start, property); 13539 } 13540 } 13541 ctx.closePath(); 13542 ctx.fill(loop ? 'evenodd' : 'nonzero'); 13543 ctx.restore(); 13544 } 13545 } catch (err) { 13546 _iterator22.e(err); 13547 } finally { 13548 _iterator22.f(); 13549 } 13550 } 13551 function clipBounds(ctx, scale, clip, bounds) { 13552 var chartArea = scale.chart.chartArea; 13553 var _ref0 = bounds || {}, 13554 property = _ref0.property, 13555 start = _ref0.start, 13556 end = _ref0.end; 13557 if (property === 'x' || property === 'y') { 13558 var left, top, right, bottom; 13559 if (property === 'x') { 13560 left = start; 13561 top = chartArea.top; 13562 right = end; 13563 bottom = chartArea.bottom; 13564 } else { 13565 left = chartArea.left; 13566 top = start; 13567 right = chartArea.right; 13568 bottom = end; 13569 } 13570 ctx.beginPath(); 13571 if (clip) { 13572 left = Math.max(left, clip.left); 13573 right = Math.min(right, clip.right); 13574 top = Math.max(top, clip.top); 13575 bottom = Math.min(bottom, clip.bottom); 13576 } 13577 ctx.rect(left, top, right - left, bottom - top); 13578 ctx.clip(); 13579 } 13580 } 13581 function interpolatedLineTo(ctx, target, point, property) { 13582 var interpolatedPoint = target.interpolate(point, property); 13583 if (interpolatedPoint) { 13584 ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y); 13585 } 13586 } 13587 var index = { 13588 id: 'filler', 13589 afterDatasetsUpdate: function afterDatasetsUpdate(chart, _args, options) { 13590 var count = (chart.data.datasets || []).length; 13591 var sources = []; 13592 var meta, i, line, source; 13593 for (i = 0; i < count; ++i) { 13594 meta = chart.getDatasetMeta(i); 13595 line = meta.dataset; 13596 source = null; 13597 if (line && line.options && line instanceof LineElement) { 13598 source = { 13599 visible: chart.isDatasetVisible(i), 13600 index: i, 13601 fill: _decodeFill(line, i, count), 13602 chart: chart, 13603 axis: meta.controller.options.indexAxis, 13604 scale: meta.vScale, 13605 line: line 13606 }; 13607 } 13608 meta.$filler = source; 13609 sources.push(source); 13610 } 13611 for (i = 0; i < count; ++i) { 13612 source = sources[i]; 13613 if (!source || source.fill === false) { 13614 continue; 13615 } 13616 source.fill = _resolveTarget(sources, i, options.propagate); 13617 } 13618 }, 13619 beforeDraw: function beforeDraw(chart, _args, options) { 13620 var draw = options.drawTime === 'beforeDraw'; 13621 var metasets = chart.getSortedVisibleDatasetMetas(); 13622 var area = chart.chartArea; 13623 for (var i = metasets.length - 1; i >= 0; --i) { 13624 var source = metasets[i].$filler; 13625 if (!source) { 13626 continue; 13627 } 13628 source.line.updateControlPoints(area, source.axis); 13629 if (draw && source.fill) { 13630 _drawfill(chart.ctx, source, area); 13631 } 13632 } 13633 }, 13634 beforeDatasetsDraw: function beforeDatasetsDraw(chart, _args, options) { 13635 if (options.drawTime !== 'beforeDatasetsDraw') { 13636 return; 13637 } 13638 var metasets = chart.getSortedVisibleDatasetMetas(); 13639 for (var i = metasets.length - 1; i >= 0; --i) { 13640 var source = metasets[i].$filler; 13641 if (_shouldApplyFill(source)) { 13642 _drawfill(chart.ctx, source, chart.chartArea); 13643 } 13644 } 13645 }, 13646 beforeDatasetDraw: function beforeDatasetDraw(chart, args, options) { 13647 var source = args.meta.$filler; 13648 if (!_shouldApplyFill(source) || options.drawTime !== 'beforeDatasetDraw') { 13649 return; 13650 } 13651 _drawfill(chart.ctx, source, chart.chartArea); 13652 }, 13653 defaults: { 13654 propagate: true, 13655 drawTime: 'beforeDatasetDraw' 13656 } 13657 }; 13658 var getBoxSize = function getBoxSize(labelOpts, fontSize) { 13659 var _labelOpts$boxHeight = labelOpts.boxHeight, 13660 boxHeight = _labelOpts$boxHeight === void 0 ? fontSize : _labelOpts$boxHeight, 13661 _labelOpts$boxWidth = labelOpts.boxWidth, 13662 boxWidth = _labelOpts$boxWidth === void 0 ? fontSize : _labelOpts$boxWidth; 13663 if (labelOpts.usePointStyle) { 13664 boxHeight = Math.min(boxHeight, fontSize); 13665 boxWidth = labelOpts.pointStyleWidth || Math.min(boxWidth, fontSize); 13666 } 13667 return { 13668 boxWidth: boxWidth, 13669 boxHeight: boxHeight, 13670 itemHeight: Math.max(fontSize, boxHeight) 13671 }; 13672 }; 13673 var itemsEqual = function itemsEqual(a, b) { 13674 return a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index; 13675 }; 13676 var Legend = /*#__PURE__*/function (_Element7) { 13677 function Legend(config) { 13678 var _this25; 13679 _classCallCheck$1(this, Legend); 13680 _this25 = _callSuper(this, Legend); 13681 _this25._added = false;
13682 _this25.legendHitBoxes = []; 13683 _this25._hoveredItem = null; 13684 _this25.doughnutMode = false; 13685 _this25.chart = config.chart; 13686 _this25.options = config.options; 13687 _this25.ctx = config.ctx; 13688 _this25.legendItems = undefined; 13689 _this25.columnSizes = undefined; 13690 _this25.lineWidths = undefined; 13691 _this25.maxHeight = undefined; 13692 _this25.maxWidth = undefined; 13693 _this25.top = undefined; 13694 _this25.bottom = undefined; 13695 _this25.left = undefined; 13696 _this25.right = undefined; 13697 _this25.height = undefined; 13698 _this25.width = undefined; 13699 _this25._margins = undefined; 13700 _this25.position = undefined; 13701 _this25.weight = undefined; 13702 _this25.fullSize = undefined; 13703 return _this25; 13704 } 13705 _inherits$1(Legend, _Element7); 13706 return _createClass$1(Legend, [{ 13707 key: "update", 13708 value: function update(maxWidth, maxHeight, margins) { 13709 this.maxWidth = maxWidth; 13710 this.maxHeight = maxHeight; 13711 this._margins = margins; 13712 this.setDimensions(); 13713 this.buildLabels(); 13714 this.fit(); 13715 } 13716 }, { 13717 key: "setDimensions", 13718 value: function setDimensions() { 13719 if (this.isHorizontal()) { 13720 this.width = this.maxWidth; 13721 this.left = this._margins.left; 13722 this.right = this.width; 13723 } else { 13724 this.height = this.maxHeight; 13725 this.top = this._margins.top; 13726 this.bottom = this.height; 13727 } 13728 } 13729 }, { 13730 key: "buildLabels", 13731 value: function buildLabels() { 13732 var _this26 = this; 13733 var labelOpts = this.options.labels || {}; 13734 var legendItems = callback(labelOpts.generateLabels, [this.chart], this) || []; 13735 if (labelOpts.filter) { 13736 legendItems = legendItems.filter(function (item) { 13737 return labelOpts.filter(item, _this26.chart.data); 13738 }); 13739 } 13740 if (labelOpts.sort) { 13741 legendItems = legendItems.sort(function (a, b) { 13742 return labelOpts.sort(a, b, _this26.chart.data); 13743 }); 13744 } 13745 if (this.options.reverse) { 13746 legendItems.reverse(); 13747 } 13748 this.legendItems = legendItems; 13749 } 13750 }, { 13751 key: "fit", 13752 value: function fit() { 13753 var options = this.options, 13754 ctx = this.ctx; 13755 if (!options.display) { 13756 this.width = this.height = 0; 13757 return; 13758 } 13759 var labelOpts = options.labels; 13760 var labelFont = toFont(labelOpts.font); 13761 var fontSize = labelFont.size; 13762 var titleHeight = this._computeTitleHeight(); 13763 var _getBoxSize = getBoxSize(labelOpts, fontSize), 13764 boxWidth = _getBoxSize.boxWidth, 13765 itemHeight = _getBoxSize.itemHeight; 13766 var width, height; 13767 ctx.font = labelFont.string; 13768 if (this.isHorizontal()) { 13769 width = this.maxWidth; 13770 height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10; 13771 } else { 13772 height = this.maxHeight; 13773 width = this._fitCols(titleHeight, labelFont, boxWidth, itemHeight) + 10; 13774 } 13775 this.width = Math.min(width, options.maxWidth || this.maxWidth); 13776 this.height = Math.min(height, options.maxHeight || this.maxHeight); 13777 } 13778 }, { 13779 key: "_fitRows", 13780 value: function _fitRows(titleHeight, fontSize, boxWidth, itemHeight) { 13781 var ctx = this.ctx, 13782 maxWidth = this.maxWidth, 13783 padding = this.options.labels.padding; 13784 var hitboxes = this.legendHitBoxes = []; 13785 var lineWidths = this.lineWidths = [0]; 13786 var lineHeight = itemHeight + padding; 13787 var totalHeight = titleHeight; 13788 ctx.textAlign = 'left'; 13789 ctx.textBaseline = 'middle'; 13790 var row = -1; 13791 var top = -lineHeight; 13792 this.legendItems.forEach(function (legendItem, i) { 13793 var itemWidth = boxWidth + fontSize / 2 + ctx.measureText(legendItem.text).width; 13794 if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) { 13795 totalHeight += lineHeight; 13796 lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0; 13797 top += lineHeight; 13798 row++; 13799 } 13800 hitboxes[i] = { 13801 left: 0, 13802 top: top, 13803 row: row, 13804 width: itemWidth, 13805 height: itemHeight 13806 }; 13807 lineWidths[lineWidths.length - 1] += itemWidth + padding; 13808 }); 13809 return totalHeight; 13810 } 13811 }, {
13812 key: "_fitCols", 13813 value: function _fitCols(titleHeight, labelFont, boxWidth, _itemHeight) { 13814 var ctx = this.ctx, 13815 maxHeight = this.maxHeight, 13816 padding = this.options.labels.padding; 13817 var hitboxes = this.legendHitBoxes = []; 13818 var columnSizes = this.columnSizes = []; 13819 var heightLimit = maxHeight - titleHeight; 13820 var totalWidth = padding; 13821 var currentColWidth = 0; 13822 var currentColHeight = 0; 13823 var left = 0; 13824 var col = 0; 13825 this.legendItems.forEach(function (legendItem, i) { 13826 var _calculateItemSize = calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight), 13827 itemWidth = _calculateItemSize.itemWidth, 13828 itemHeight = _calculateItemSize.itemHeight; 13829 if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) { 13830 totalWidth += currentColWidth + padding; 13831 columnSizes.push({ 13832 width: currentColWidth, 13833 height: currentColHeight 13834 }); 13835 left += currentColWidth + padding; 13836 col++; 13837 currentColWidth = currentColHeight = 0; 13838 } 13839 hitboxes[i] = { 13840 left: left, 13841 top: currentColHeight, 13842 col: col, 13843 width: itemWidth, 13844 height: itemHeight 13845 }; 13846 currentColWidth = Math.max(currentColWidth, itemWidth); 13847 currentColHeight += itemHeight + padding; 13848 }); 13849 totalWidth += currentColWidth; 13850 columnSizes.push({ 13851 width: currentColWidth, 13852 height: currentColHeight 13853 }); 13854 return totalWidth; 13855 } 13856 }, { 13857 key: "adjustHitBoxes", 13858 value: function adjustHitBoxes() { 13859 if (!this.options.display) { 13860 return; 13861 } 13862 var titleHeight = this._computeTitleHeight(); 13863 var hitboxes = this.legendHitBoxes, 13864 _this$options13 = this.options, 13865 align = _this$options13.align, 13866 padding = _this$options13.labels.padding, 13867 rtl = _this$options13.rtl; 13868 var rtlHelper = getRtlAdapter(rtl, this.left, this.width); 13869 if (this.isHorizontal()) { 13870 var row = 0; 13871 var left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]); 13872 var _iterator23 = _createForOfIteratorHelper$1(hitboxes), 13873 _step23; 13874 try { 13875 for (_iterator23.s(); !(_step23 = _iterator23.n()).done;) { 13876 var hitbox = _step23.value; 13877 if (row !== hitbox.row) { 13878 row = hitbox.row; 13879 left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]); 13880 } 13881 hitbox.top += this.top + titleHeight + padding; 13882 hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width); 13883 left += hitbox.width + padding; 13884 } 13885 } catch (err) { 13886 _iterator23.e(err); 13887 } finally { 13888 _iterator23.f(); 13889 } 13890 } else { 13891 var col = 0; 13892 var top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height); 13893 var _iterator24 = _createForOfIteratorHelper$1(hitboxes), 13894 _step24; 13895 try { 13896 for (_iterator24.s(); !(_step24 = _iterator24.n()).done;) { 13897 var _hitbox = _step24.value; 13898 if (_hitbox.col !== col) { 13899 col = _hitbox.col; 13900 top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height); 13901 } 13902 _hitbox.top = top; 13903 _hitbox.left += this.left + padding; 13904 _hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(_hitbox.left), _hitbox.width); 13905 top += _hitbox.height + padding; 13906 } 13907 } catch (err) { 13908 _iterator24.e(err); 13909 } finally { 13910 _iterator24.f(); 13911 } 13912 } 13913 } 13914 }, { 13915 key: "isHorizontal", 13916 value: function isHorizontal() { 13917 return this.options.position === 'top' || this.options.position === 'bottom'; 13918 } 13919 }, {
13920 key: "draw", 13921 value: function draw() { 13922 if (this.options.display) { 13923 var ctx = this.ctx; 13924 clipArea(ctx, this); 13925 this._draw(); 13926 unclipArea(ctx); 13927 } 13928 } 13929 }, { 13930 key: "_draw", 13931 value: function _draw() { 13932 var _this27 = this; 13933 var opts = this.options, 13934 columnSizes = this.columnSizes, 13935 lineWidths = this.lineWidths, 13936 ctx = this.ctx; 13937 var align = opts.align, 13938 labelOpts = opts.labels; 13939 var defaultColor = defaults.color; 13940 var rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width); 13941 var labelFont = toFont(labelOpts.font); 13942 var padding = labelOpts.padding; 13943 var fontSize = labelFont.size; 13944 var halfFontSize = fontSize / 2; 13945 var cursor; 13946 this.drawTitle(); 13947 ctx.textAlign = rtlHelper.textAlign('left'); 13948 ctx.textBaseline = 'middle'; 13949 ctx.lineWidth = 0.5; 13950 ctx.font = labelFont.string; 13951 var _getBoxSize2 = getBoxSize(labelOpts, fontSize), 13952 boxWidth = _getBoxSize2.boxWidth, 13953 boxHeight = _getBoxSize2.boxHeight, 13954 itemHeight = _getBoxSize2.itemHeight; 13955 var drawLegendBox = function drawLegendBox(x, y, legendItem) { 13956 if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) { 13957 return; 13958 } 13959 ctx.save(); 13960 var lineWidth = valueOrDefault(legendItem.lineWidth, 1); 13961 ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor); 13962 ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt'); 13963 ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0); 13964 ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter'); 13965 ctx.lineWidth = lineWidth; 13966 ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor); 13967 ctx.setLineDash(valueOrDefault(legendItem.lineDash, [])); 13968 if (labelOpts.usePointStyle) { 13969 var drawOptions = { 13970 radius: boxHeight * Math.SQRT2 / 2, 13971 pointStyle: legendItem.pointStyle, 13972 rotation: legendItem.rotation, 13973 borderWidth: lineWidth 13974 }; 13975 var centerX = rtlHelper.xPlus(x, boxWidth / 2); 13976 var centerY = y + halfFontSize; 13977 drawPointLegend(ctx, drawOptions, centerX, centerY, labelOpts.pointStyleWidth && boxWidth); 13978 } else { 13979 var yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0); 13980 var xBoxLeft = rtlHelper.leftForLtr(x, boxWidth); 13981 var borderRadius = toTRBLCorners(legendItem.borderRadius); 13982 ctx.beginPath(); 13983 if (Object.values(borderRadius).some(function (v) { 13984 return v !== 0; 13985 })) { 13986 addRoundedRectPath(ctx, { 13987 x: xBoxLeft, 13988 y: yBoxTop, 13989 w: boxWidth, 13990 h: boxHeight, 13991 radius: borderRadius 13992 }); 13993 } else { 13994 ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight); 13995 } 13996 ctx.fill(); 13997 if (lineWidth !== 0) { 13998 ctx.stroke(); 13999 } 14000 } 14001 ctx.restore(); 14002 }; 14003 var fillText = function fillText(x, y, legendItem) { 14004 renderText(ctx, legendItem.text, x, y + itemHeight / 2, labelFont, { 14005 strikethrough: legendItem.hidden, 14006 textAlign: rtlHelper.textAlign(legendItem.textAlign) 14007 }); 14008 }; 14009 var isHorizontal = this.isHorizontal(); 14010 var titleHeight = this._computeTitleHeight(); 14011 if (isHorizontal) { 14012 cursor = { 14013 x: _alignStartEnd(align, this.left + padding, this.right - lineWidths[0]), 14014 y: this.top + padding + titleHeight, 14015 line: 0 14016 }; 14017 } else { 14018 cursor = { 14019 x: this.left + padding, 14020 y: _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height), 14021 line: 0 14022 }; 14023 } 14024 overrideTextDirection(this.ctx, opts.textDirection); 14025 var lineHeight = itemHeight + padding;
14026 this.legendItems.forEach(function (legendItem, i) { 14027 ctx.strokeStyle = legendItem.fontColor; 14028 ctx.fillStyle = legendItem.fontColor; 14029 var textWidth = ctx.measureText(legendItem.text).width; 14030 var textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign)); 14031 var width = boxWidth + halfFontSize + textWidth; 14032 var x = cursor.x; 14033 var y = cursor.y; 14034 rtlHelper.setWidth(_this27.width); 14035 if (isHorizontal) { 14036 if (i > 0 && x + width + padding > _this27.right) { 14037 y = cursor.y += lineHeight; 14038 cursor.line++; 14039 x = cursor.x = _alignStartEnd(align, _this27.left + padding, _this27.right - lineWidths[cursor.line]); 14040 } 14041 } else if (i > 0 && y + lineHeight > _this27.bottom) { 14042 x = cursor.x = x + columnSizes[cursor.line].width + padding; 14043 cursor.line++; 14044 y = cursor.y = _alignStartEnd(align, _this27.top + titleHeight + padding, _this27.bottom - columnSizes[cursor.line].height); 14045 } 14046 var realX = rtlHelper.x(x); 14047 drawLegendBox(realX, y, legendItem); 14048 x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : _this27.right, opts.rtl); 14049 fillText(rtlHelper.x(x), y, legendItem); 14050 if (isHorizontal) { 14051 cursor.x += width + padding; 14052 } else if (typeof legendItem.text !== 'string') { 14053 var fontLineHeight = labelFont.lineHeight; 14054 cursor.y += calculateLegendItemHeight(legendItem, fontLineHeight) + padding; 14055 } else { 14056 cursor.y += lineHeight; 14057 } 14058 }); 14059 restoreTextDirection(this.ctx, opts.textDirection); 14060 } 14061 }, { 14062 key: "drawTitle", 14063 value: function drawTitle() { 14064 var opts = this.options; 14065 var titleOpts = opts.title; 14066 var titleFont = toFont(titleOpts.font); 14067 var titlePadding = toPadding(titleOpts.padding); 14068 if (!titleOpts.display) { 14069 return; 14070 } 14071 var rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width); 14072 var ctx = this.ctx; 14073 var position = titleOpts.position; 14074 var halfFontSize = titleFont.size / 2; 14075 var topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize; 14076 var y; 14077 var left = this.left; 14078 var maxWidth = this.width; 14079 if (this.isHorizontal()) { 14080 maxWidth = Math.max.apply(Math, _toConsumableArray(this.lineWidths)); 14081 y = this.top + topPaddingPlusHalfFontSize; 14082 left = _alignStartEnd(opts.align, left, this.right - maxWidth); 14083 } else { 14084 var maxHeight = this.columnSizes.reduce(function (acc, size) { 14085 return Math.max(acc, size.height); 14086 }, 0); 14087 y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight()); 14088 } 14089 var x = _alignStartEnd(position, left, left + maxWidth); 14090 ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position)); 14091 ctx.textBaseline = 'middle'; 14092 ctx.strokeStyle = titleOpts.color; 14093 ctx.fillStyle = titleOpts.color; 14094 ctx.font = titleFont.string; 14095 renderText(ctx, titleOpts.text, x, y, titleFont); 14096 } 14097 }, { 14098 key: "_computeTitleHeight", 14099 value: function _computeTitleHeight() { 14100 var titleOpts = this.options.title; 14101 var titleFont = toFont(titleOpts.font); 14102 var titlePadding = toPadding(titleOpts.padding); 14103 return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0; 14104 } 14105 }, { 14106 key: "_getLegendItemAt", 14107 value: function _getLegendItemAt(x, y) { 14108 var i, hitBox, lh; 14109 if (_isBetween(x, this.left, this.right) && _isBetween(y, this.top, this.bottom)) { 14110 lh = this.legendHitBoxes; 14111 for (i = 0; i < lh.length; ++i) { 14112 hitBox = lh[i]; 14113 if (_isBetween(x, hitBox.left, hitBox.left + hitBox.width) && _isBetween(y, hitBox.top, hitBox.top + hitBox.height)) { 14114 return this.legendItems[i]; 14115 } 14116 } 14117 } 14118 return null; 14119 } 14120 }, {
14121 key: "handleEvent", 14122 value: function handleEvent(e) { 14123 var opts = this.options; 14124 if (!isListened(e.type, opts)) { 14125 return; 14126 } 14127 var hoveredItem = this._getLegendItemAt(e.x, e.y); 14128 if (e.type === 'mousemove' || e.type === 'mouseout') { 14129 var previous = this._hoveredItem; 14130 var sameItem = itemsEqual(previous, hoveredItem); 14131 if (previous && !sameItem) { 14132 callback(opts.onLeave, [e, previous, this], this); 14133 } 14134 this._hoveredItem = hoveredItem; 14135 if (hoveredItem && !sameItem) { 14136 callback(opts.onHover, [e, hoveredItem, this], this); 14137 } 14138 } else if (hoveredItem) { 14139 callback(opts.onClick, [e, hoveredItem, this], this); 14140 } 14141 } 14142 }]); 14143 }(Element); 14144 function calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight) { 14145 var itemWidth = calculateItemWidth(legendItem, boxWidth, labelFont, ctx); 14146 var itemHeight = calculateItemHeight(_itemHeight, legendItem, labelFont.lineHeight); 14147 return { 14148 itemWidth: itemWidth, 14149 itemHeight: itemHeight 14150 }; 14151 } 14152 function calculateItemWidth(legendItem, boxWidth, labelFont, ctx) { 14153 var legendItemText = legendItem.text; 14154 if (legendItemText && typeof legendItemText !== 'string') { 14155 legendItemText = legendItemText.reduce(function (a, b) { 14156 return a.length > b.length ? a : b; 14157 }); 14158 } 14159 return boxWidth + labelFont.size / 2 + ctx.measureText(legendItemText).width; 14160 } 14161 function calculateItemHeight(_itemHeight, legendItem, fontLineHeight) { 14162 var itemHeight = _itemHeight; 14163 if (typeof legendItem.text !== 'string') { 14164 itemHeight = calculateLegendItemHeight(legendItem, fontLineHeight); 14165 } 14166 return itemHeight; 14167 } 14168 function calculateLegendItemHeight(legendItem, fontLineHeight) { 14169 var labelHeight = legendItem.text ? legendItem.text.length : 0; 14170 return fontLineHeight * labelHeight; 14171 } 14172 function isListened(type, opts) { 14173 if ((type === 'mousemove' || type === 'mouseout') && (opts.onHover || opts.onLeave)) { 14174 return true; 14175 } 14176 if (opts.onClick && (type === 'click' || type === 'mouseup')) { 14177 return true; 14178 } 14179 return false; 14180 } 14181 var plugin_legend = { 14182 id: 'legend', 14183 _element: Legend, 14184 start: function start(chart, _args, options) { 14185 var legend = chart.legend = new Legend({ 14186 ctx: chart.ctx, 14187 options: options, 14188 chart: chart 14189 }); 14190 layouts.configure(chart, legend, options); 14191 layouts.addBox(chart, legend); 14192 }, 14193 stop: function stop(chart) { 14194 layouts.removeBox(chart, chart.legend); 14195 delete chart.legend; 14196 }, 14197 beforeUpdate: function beforeUpdate(chart, _args, options) { 14198 var legend = chart.legend; 14199 layouts.configure(chart, legend, options); 14200 legend.options = options; 14201 }, 14202 afterUpdate: function afterUpdate(chart) { 14203 var legend = chart.legend; 14204 legend.buildLabels(); 14205 legend.adjustHitBoxes(); 14206 }, 14207 afterEvent: function afterEvent(chart, args) { 14208 if (!args.replay) { 14209 chart.legend.handleEvent(args.event); 14210 } 14211 }, 14212 defaults: { 14213 display: true, 14214 position: 'top', 14215 align: 'center', 14216 fullSize: true, 14217 reverse: false, 14218 weight: 1000, 14219 onClick: function onClick(e, legendItem, legend) { 14220 var index = legendItem.datasetIndex; 14221 var ci = legend.chart; 14222 if (ci.isDatasetVisible(index)) { 14223 ci.hide(index); 14224 legendItem.hidden = true; 14225 } else { 14226 ci.show(index); 14227 legendItem.hidden = false; 14228 } 14229 }, 14230 onHover: null, 14231 onLeave: null, 14232 labels: { 14233 color: function color(ctx) { 14234 return ctx.chart.options.color; 14235 }, 14236 boxWidth: 40, 14237 padding: 10, 14238 generateLabels: function generateLabels(chart) { 14239 var datasets = chart.data.datasets; 14240 var _chart$legend$options = chart.legend.options.labels, 14241 usePointStyle = _chart$legend$options.usePointStyle, 14242 pointStyle = _chart$legend$options.pointStyle, 14243 textAlign = _chart$legend$options.textAlign, 14244 color = _chart$legend$options.color, 14245 useBorderRadius = _chart$legend$options.useBorderRadius, 14246 borderRadius = _chart$legend$options.borderRadius; 14247 return chart._getSortedDatasetMetas().map(function (meta) { 14248 var style = meta.controller.getStyle(usePointStyle ? 0 : undefined); 14249 var borderWidth = toPadding(style.borderWidth); 14250 return { 14251 text: datasets[meta.index].label, 14252 fillStyle: style.backgroundColor, 14253 fontColor: color, 14254 hidden: !meta.visible, 14255 lineCap: style.borderCapStyle, 14256 lineDash: style.borderDash, 14257 lineDashOffset: style.borderDashOffset, 14258 lineJoin: style.borderJoinStyle, 14259 lineWidth: (borderWidth.width + borderWidth.height) / 4, 14260 strokeStyle: style.borderColor, 14261 pointStyle: pointStyle || style.pointStyle, 14262 rotation: style.rotation, 14263 textAlign: textAlign || style.textAlign, 14264 borderRadius: useBorderRadius && (borderRadius || style.borderRadius), 14265 datasetIndex: meta.index 14266 }; 14267 }, this); 14268 } 14269 }, 14270 title: { 14271 color: function color(ctx) { 14272 return ctx.chart.options.color; 14273 }, 14274 display: false, 14275 position: 'center', 14276 text: '' 14277 } 14278 }, 14279 descriptors: { 14280 _scriptable: function _scriptable(name) { 14281 return !name.startsWith('on'); 14282 }, 14283 labels: { 14284 _scriptable: function _scriptable(name) { 14285 return !['generateLabels', 'filter', 'sort'].includes(name); 14286 } 14287 } 14288 } 14289 }; 14290 var Title = /*#__PURE__*/function (_Element8) { 14291 function Title(config) { 14292 var _this28; 14293 _classCallCheck$1(this, Title); 14294 _this28 = _callSuper(this, Title); 14295 _this28.chart = config.chart; 14296 _this28.options = config.options; 14297 _this28.ctx = config.ctx; 14298 _this28._padding = undefined; 14299 _this28.top = undefined; 14300 _this28.bottom = undefined; 14301 _this28.left = undefined; 14302 _this28.right = undefined; 14303 _this28.width = undefined; 14304 _this28.height = undefined; 14305 _this28.position = undefined; 14306 _this28.weight = undefined; 14307 _this28.fullSize = undefined; 14308 return _this28; 14309 } 14310 _inherits$1(Title, _Element8); 14311 return _createClass$1(Title, [{ 14312 key: "update", 14313 value: function update(maxWidth, maxHeight) { 14314 var opts = this.options; 14315 this.left = 0; 14316 this.top = 0; 14317 if (!opts.display) { 14318 this.width = this.height = this.right = this.bottom = 0; 14319 return; 14320 } 14321 this.width = this.right = maxWidth; 14322 this.height = this.bottom = maxHeight; 14323 var lineCount = isArray(opts.text) ? opts.text.length : 1; 14324 this._padding = toPadding(opts.padding);
14325 var textSize = lineCount * toFont(opts.font).lineHeight + this._padding.height; 14326 if (this.isHorizontal()) { 14327 this.height = textSize; 14328 } else { 14329 this.width = textSize; 14330 } 14331 } 14332 }, { 14333 key: "isHorizontal", 14334 value: function isHorizontal() { 14335 var pos = this.options.position; 14336 return pos === 'top' || pos === 'bottom'; 14337 } 14338 }, { 14339 key: "_drawArgs", 14340 value: function _drawArgs(offset) { 14341 var top = this.top, 14342 left = this.left, 14343 bottom = this.bottom, 14344 right = this.right, 14345 options = this.options; 14346 var align = options.align; 14347 var rotation = 0; 14348 var maxWidth, titleX, titleY; 14349 if (this.isHorizontal()) { 14350 titleX = _alignStartEnd(align, left, right); 14351 titleY = top + offset; 14352 maxWidth = right - left; 14353 } else { 14354 if (options.position === 'left') { 14355 titleX = left + offset; 14356 titleY = _alignStartEnd(align, bottom, top); 14357 rotation = PI * -0.5; 14358 } else { 14359 titleX = right - offset; 14360 titleY = _alignStartEnd(align, top, bottom); 14361 rotation = PI * 0.5; 14362 } 14363 maxWidth = bottom - top; 14364 } 14365 return { 14366 titleX: titleX, 14367 titleY: titleY, 14368 maxWidth: maxWidth, 14369 rotation: rotation 14370 }; 14371 } 14372 }, { 14373 key: "draw", 14374 value: function draw() { 14375 var ctx = this.ctx; 14376 var opts = this.options; 14377 if (!opts.display) { 14378 return; 14379 } 14380 var fontOpts = toFont(opts.font); 14381 var lineHeight = fontOpts.lineHeight; 14382 var offset = lineHeight / 2 + this._padding.top; 14383 var _this$_drawArgs = this._drawArgs(offset), 14384 titleX = _this$_drawArgs.titleX, 14385 titleY = _this$_drawArgs.titleY, 14386 maxWidth = _this$_drawArgs.maxWidth, 14387 rotation = _this$_drawArgs.rotation; 14388 renderText(ctx, opts.text, 0, 0, fontOpts, { 14389 color: opts.color, 14390 maxWidth: maxWidth, 14391 rotation: rotation, 14392 textAlign: _toLeftRightCenter(opts.align), 14393 textBaseline: 'middle', 14394 translation: [titleX, titleY] 14395 }); 14396 } 14397 }]); 14398 }(Element); 14399 function createTitle(chart, titleOpts) { 14400 var title = new Title({ 14401 ctx: chart.ctx, 14402 options: titleOpts, 14403 chart: chart 14404 }); 14405 layouts.configure(chart, title, titleOpts); 14406 layouts.addBox(chart, title); 14407 chart.titleBlock = title; 14408 } 14409 var plugin_title = { 14410 id: 'title', 14411 _element: Title, 14412 start: function start(chart, _args, options) { 14413 createTitle(chart, options); 14414 }, 14415 stop: function stop(chart) { 14416 var titleBlock = chart.titleBlock; 14417 layouts.removeBox(chart, titleBlock); 14418 delete chart.titleBlock; 14419 }, 14420 beforeUpdate: function beforeUpdate(chart, _args, options) { 14421 var title = chart.titleBlock; 14422 layouts.configure(chart, title, options); 14423 title.options = options; 14424 }, 14425 defaults: { 14426 align: 'center', 14427 display: false, 14428 font: { 14429 weight: 'bold' 14430 }, 14431 fullSize: true, 14432 padding: 10, 14433 position: 'top', 14434 text: '', 14435 weight: 2000 14436 }, 14437 defaultRoutes: { 14438 color: 'color' 14439 }, 14440 descriptors: { 14441 _scriptable: true, 14442 _indexable: false 14443 } 14444 }; 14445 var map = new WeakMap(); 14446 var plugin_subtitle = { 14447 id: 'subtitle', 14448 start: function start(chart, _args, options) { 14449 var title = new Title({ 14450 ctx: chart.ctx, 14451 options: options, 14452 chart: chart 14453 }); 14454 layouts.configure(chart, title, options); 14455 layouts.addBox(chart, title); 14456 map.set(chart, title); 14457 }, 14458 stop: function stop(chart) { 14459 layouts.removeBox(chart, map.get(chart)); 14460 map["delete"](chart); 14461 }, 14462 beforeUpdate: function beforeUpdate(chart, _args, options) { 14463 var title = map.get(chart); 14464 layouts.configure(chart, title, options); 14465 title.options = options; 14466 }, 14467 defaults: { 14468 align: 'center', 14469 display: false, 14470 font: { 14471 weight: 'normal' 14472 }, 14473 fullSize: true, 14474 padding: 0, 14475 position: 'top', 14476 text: '', 14477 weight: 1500 14478 }, 14479 defaultRoutes: { 14480 color: 'color' 14481 }, 14482 descriptors: { 14483 _scriptable: true, 14484 _indexable: false 14485 } 14486 }; 14487 var positioners = { 14488 average: function average(items) { 14489 if (!items.length) { 14490 return false;
14491 } 14492 var i, len; 14493 var xSet = new Set(); 14494 var y = 0; 14495 var count = 0; 14496 for (i = 0, len = items.length; i < len; ++i) { 14497 var el = items[i].element; 14498 if (el && el.hasValue()) { 14499 var pos = el.tooltipPosition(); 14500 xSet.add(pos.x); 14501 y += pos.y; 14502 ++count; 14503 } 14504 } 14505 if (count === 0 || xSet.size === 0) { 14506 return false; 14507 } 14508 var xAverage = _toConsumableArray(xSet).reduce(function (a, b) { 14509 return a + b; 14510 }) / xSet.size; 14511 return { 14512 x: xAverage, 14513 y: y / count 14514 }; 14515 }, 14516 nearest: function nearest(items, eventPosition) { 14517 if (!items.length) { 14518 return false; 14519 } 14520 var x = eventPosition.x; 14521 var y = eventPosition.y; 14522 var minDistance = Number.POSITIVE_INFINITY; 14523 var i, len, nearestElement; 14524 for (i = 0, len = items.length; i < len; ++i) { 14525 var el = items[i].element; 14526 if (el && el.hasValue()) { 14527 var center = el.getCenterPoint(); 14528 var d = distanceBetweenPoints(eventPosition, center); 14529 if (d < minDistance) { 14530 minDistance = d; 14531 nearestElement = el; 14532 } 14533 } 14534 } 14535 if (nearestElement) { 14536 var tp = nearestElement.tooltipPosition(); 14537 x = tp.x; 14538 y = tp.y; 14539 } 14540 return { 14541 x: x, 14542 y: y 14543 }; 14544 } 14545 }; 14546 function pushOrConcat(base, toPush) { 14547 if (toPush) { 14548 if (isArray(toPush)) { 14549 Array.prototype.push.apply(base, toPush); 14550 } else { 14551 base.push(toPush); 14552 } 14553 } 14554 return base; 14555 } 14556 function splitNewlines(str) { 14557 if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) { 14558 return str.split('\n'); 14559 } 14560 return str; 14561 } 14562 function createTooltipItem(chart, item) { 14563 var element = item.element, 14564 datasetIndex = item.datasetIndex, 14565 index = item.index; 14566 var controller = chart.getDatasetMeta(datasetIndex).controller; 14567 var _controller$getLabelA = controller.getLabelAndValue(index), 14568 label = _controller$getLabelA.label, 14569 value = _controller$getLabelA.value; 14570 return { 14571 chart: chart, 14572 label: label, 14573 parsed: controller.getParsed(index), 14574 raw: chart.data.datasets[datasetIndex].data[index], 14575 formattedValue: value, 14576 dataset: controller.getDataset(), 14577 dataIndex: index, 14578 datasetIndex: datasetIndex, 14579 element: element 14580 }; 14581 } 14582 function getTooltipSize(tooltip, options) { 14583 var ctx = tooltip.chart.ctx; 14584 var body = tooltip.body, 14585 footer = tooltip.footer, 14586 title = tooltip.title; 14587 var boxWidth = options.boxWidth, 14588 boxHeight = options.boxHeight; 14589 var bodyFont = toFont(options.bodyFont); 14590 var titleFont = toFont(options.titleFont); 14591 var footerFont = toFont(options.footerFont); 14592 var titleLineCount = title.length; 14593 var footerLineCount = footer.length; 14594 var bodyLineItemCount = body.length; 14595 var padding = toPadding(options.padding); 14596 var height = padding.height; 14597 var width = 0; 14598 var combinedBodyLength = body.reduce(function (count, bodyItem) { 14599 return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length; 14600 }, 0); 14601 combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length; 14602 if (titleLineCount) { 14603 height += titleLineCount * titleFont.lineHeight + (titleLineCount - 1) * options.titleSpacing + options.titleMarginBottom; 14604 } 14605 if (combinedBodyLength) { 14606 var bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight; 14607 height += bodyLineItemCount * bodyLineHeight + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight + (combinedBodyLength - 1) * options.bodySpacing; 14608 } 14609 if (footerLineCount) { 14610 height += options.footerMarginTop + footerLineCount * footerFont.lineHeight + (footerLineCount - 1) * options.footerSpacing; 14611 } 14612 var widthPadding = 0; 14613 var maxLineWidth = function maxLineWidth(line) { 14614 width = Math.max(width, ctx.measureText(line).width + widthPadding); 14615 }; 14616 ctx.save(); 14617 ctx.font = titleFont.string; 14618 each(tooltip.title, maxLineWidth); 14619 ctx.font = bodyFont.string; 14620 each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth); 14621 widthPadding = options.displayColors ? boxWidth + 2 + options.boxPadding : 0; 14622 each(body, function (bodyItem) { 14623 each(bodyItem.before, maxLineWidth); 14624 each(bodyItem.lines, maxLineWidth); 14625 each(bodyItem.after, maxLineWidth); 14626 }); 14627 widthPadding = 0; 14628 ctx.font = footerFont.string; 14629 each(tooltip.footer, maxLineWidth);
14630 ctx.restore(); 14631 width += padding.width; 14632 return { 14633 width: width, 14634 height: height 14635 }; 14636 } 14637 function determineYAlign(chart, size) { 14638 var y = size.y, 14639 height = size.height; 14640 if (y < height / 2) { 14641 return 'top'; 14642 } else if (y > chart.height - height / 2) { 14643 return 'bottom'; 14644 } 14645 return 'center'; 14646 } 14647 function doesNotFitWithAlign(xAlign, chart, options, size) { 14648 var x = size.x, 14649 width = size.width; 14650 var caret = options.caretSize + options.caretPadding; 14651 if (xAlign === 'left' && x + width + caret > chart.width) { 14652 return true; 14653 } 14654 if (xAlign === 'right' && x - width - caret < 0) { 14655 return true; 14656 } 14657 } 14658 function determineXAlign(chart, options, size, yAlign) { 14659 var x = size.x, 14660 width = size.width; 14661 var chartWidth = chart.width, 14662 _chart$chartArea = chart.chartArea, 14663 left = _chart$chartArea.left, 14664 right = _chart$chartArea.right; 14665 var xAlign = 'center'; 14666 if (yAlign === 'center') { 14667 xAlign = x <= (left + right) / 2 ? 'left' : 'right'; 14668 } else if (x <= width / 2) { 14669 xAlign = 'left'; 14670 } else if (x >= chartWidth - width / 2) { 14671 xAlign = 'right'; 14672 } 14673 if (doesNotFitWithAlign(xAlign, chart, options, size)) { 14674 xAlign = 'center'; 14675 } 14676 return xAlign; 14677 } 14678 function determineAlignment(chart, options, size) { 14679 var yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size); 14680 return { 14681 xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign), 14682 yAlign: yAlign 14683 }; 14684 } 14685 function alignX(size, xAlign) { 14686 var x = size.x, 14687 width = size.width; 14688 if (xAlign === 'right') { 14689 x -= width; 14690 } else if (xAlign === 'center') { 14691 x -= width / 2; 14692 } 14693 return x; 14694 } 14695 function alignY(size, yAlign, paddingAndSize) { 14696 var y = size.y, 14697 height = size.height; 14698 if (yAlign === 'top') { 14699 y += paddingAndSize; 14700 } else if (yAlign === 'bottom') { 14701 y -= height + paddingAndSize; 14702 } else { 14703 y -= height / 2; 14704 } 14705 return y; 14706 } 14707 function getBackgroundPoint(options, size, alignment, chart) { 14708 var caretSize = options.caretSize, 14709 caretPadding = options.caretPadding, 14710 cornerRadius = options.cornerRadius; 14711 var xAlign = alignment.xAlign, 14712 yAlign = alignment.yAlign; 14713 var paddingAndSize = caretSize + caretPadding; 14714 var _toTRBLCorners = toTRBLCorners(cornerRadius), 14715 topLeft = _toTRBLCorners.topLeft, 14716 topRight = _toTRBLCorners.topRight, 14717 bottomLeft = _toTRBLCorners.bottomLeft, 14718 bottomRight = _toTRBLCorners.bottomRight; 14719 var x = alignX(size, xAlign); 14720 var y = alignY(size, yAlign, paddingAndSize); 14721 if (yAlign === 'center') { 14722 if (xAlign === 'left') { 14723 x += paddingAndSize; 14724 } else if (xAlign === 'right') { 14725 x -= paddingAndSize; 14726 } 14727 } else if (xAlign === 'left') { 14728 x -= Math.max(topLeft, bottomLeft) + caretSize; 14729 } else if (xAlign === 'right') { 14730 x += Math.max(topRight, bottomRight) + caretSize; 14731 } 14732 return { 14733 x: _limitValue(x, 0, chart.width - size.width), 14734 y: _limitValue(y, 0, chart.height - size.height) 14735 }; 14736 } 14737 function getAlignedX(tooltip, align, options) { 14738 var padding = toPadding(options.padding); 14739 return align === 'center' ? tooltip.x + tooltip.width / 2 : align === 'right' ? tooltip.x + tooltip.width - padding.right : tooltip.x + padding.left; 14740 } 14741 function getBeforeAfterBodyLines(callback) { 14742 return pushOrConcat([], splitNewlines(callback)); 14743 } 14744 function createTooltipContext(parent, tooltip, tooltipItems) { 14745 return createContext(parent, { 14746 tooltip: tooltip, 14747 tooltipItems: tooltipItems, 14748 type: 'tooltip' 14749 }); 14750 } 14751 function overrideCallbacks(callbacks, context) { 14752 var override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks; 14753 return override ? callbacks.override(override) : callbacks; 14754 } 14755 var defaultCallbacks = { 14756 beforeTitle: noop, 14757 title: function title(tooltipItems) { 14758 if (tooltipItems.length > 0) { 14759 var item = tooltipItems[0]; 14760 var labels = item.chart.data.labels; 14761 var labelCount = labels ? labels.length : 0; 14762 if (this && this.options && this.options.mode === 'dataset') { 14763 return item.dataset.label || ''; 14764 } else if (item.label) { 14765 return item.label; 14766 } else if (labelCount > 0 && item.dataIndex < labelCount) { 14767 return labels[item.dataIndex]; 14768 } 14769 } 14770 return ''; 14771 }, 14772 afterTitle: noop, 14773 beforeBody: noop, 14774 beforeLabel: noop, 14775 label: function label(tooltipItem) { 14776 if (this && this.options && this.options.mode === 'dataset') { 14777 return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue; 14778 } 14779 var label = tooltipItem.dataset.label || ''; 14780 if (label) { 14781 label += ': '; 14782 } 14783 var value = tooltipItem.formattedValue; 14784 if (!isNullOrUndef(value)) { 14785 label += value; 14786 } 14787 return label; 14788 }, 14789 labelColor: function labelColor(tooltipItem) { 14790 var meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex); 14791 var options = meta.controller.getStyle(tooltipItem.dataIndex); 14792 return { 14793 borderColor: options.borderColor, 14794 backgroundColor: options.backgroundColor, 14795 borderWidth: options.borderWidth, 14796 borderDash: options.borderDash, 14797 borderDashOffset: options.borderDashOffset, 14798 borderRadius: 0 14799 }; 14800 }, 14801 labelTextColor: function labelTextColor() { 14802 return this.options.bodyColor; 14803 }, 14804 labelPointStyle: function labelPointStyle(tooltipItem) { 14805 var meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex); 14806 var options = meta.controller.getStyle(tooltipItem.dataIndex); 14807 return { 14808 pointStyle: options.pointStyle, 14809 rotation: options.rotation 14810 }; 14811 }, 14812 afterLabel: noop, 14813 afterBody: noop, 14814 beforeFooter: noop, 14815 footer: noop, 14816 afterFooter: noop 14817 }; 14818 function invokeCallbackWithFallback(callbacks, name, ctx, arg) { 14819 var result = callbacks[name].call(ctx, arg); 14820 if (typeof result === 'undefined') { 14821 return defaultCallbacks[name].call(ctx, arg); 14822 } 14823 return result; 14824 } 14825 var Tooltip = /*#__PURE__*/function (_Element9) { 14826 function Tooltip(config) { 14827 var _this29; 14828 _classCallCheck$1(this, Tooltip); 14829 _this29 = _callSuper(this, Tooltip); 14830 _this29.opacity = 0; 14831 _this29._active = []; 14832 _this29._eventPosition = undefined; 14833 _this29._size = undefined; 14834 _this29._cachedAnimations = undefined; 14835 _this29._tooltipItems = []; 14836 _this29.$animations = undefined; 14837 _this29.$context = undefined; 14838 _this29.chart = config.chart; 14839 _this29.options = config.options; 14840 _this29.dataPoints = undefined; 14841 _this29.title = undefined; 14842 _this29.beforeBody = undefined; 14843 _this29.body = undefined; 14844 _this29.afterBody = undefined; 14845 _this29.footer = undefined; 14846 _this29.xAlign = undefined; 14847 _this29.yAlign = undefined; 14848 _this29.x = undefined; 14849 _this29.y = undefined; 14850 _this29.height = undefined; 14851 _this29.width = undefined; 14852 _this29.caretX = undefined; 14853 _this29.caretY = undefined; 14854 _this29.labelColors = undefined; 14855 _this29.labelPointStyles = undefined; 14856 _this29.labelTextColors = undefined; 14857 return _this29; 14858 } 14859 _inherits$1(Tooltip, _Element9); 14860 return _createClass$1(Tooltip, [{ 14861 key: "initialize", 14862 value: function initialize(options) { 14863 this.options = options; 14864 this._cachedAnimations = undefined; 14865 this.$context = undefined; 14866 } 14867 }, {
14868 key: "_resolveAnimations", 14869 value: function _resolveAnimations() { 14870 var cached = this._cachedAnimations; 14871 if (cached) { 14872 return cached; 14873 } 14874 var chart = this.chart; 14875 var options = this.options.setContext(this.getContext()); 14876 var opts = options.enabled && chart.options.animation && options.animations; 14877 var animations = new Animations(this.chart, opts); 14878 if (opts._cacheable) { 14879 this._cachedAnimations = Object.freeze(animations); 14880 } 14881 return animations; 14882 } 14883 }, { 14884 key: "getContext", 14885 value: function getContext() { 14886 return this.$context || (this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems)); 14887 } 14888 }, { 14889 key: "getTitle", 14890 value: function getTitle(context, options) { 14891 var callbacks = options.callbacks; 14892 var beforeTitle = invokeCallbackWithFallback(callbacks, 'beforeTitle', this, context); 14893 var title = invokeCallbackWithFallback(callbacks, 'title', this, context); 14894 var afterTitle = invokeCallbackWithFallback(callbacks, 'afterTitle', this, context); 14895 var lines = []; 14896 lines = pushOrConcat(lines, splitNewlines(beforeTitle)); 14897 lines = pushOrConcat(lines, splitNewlines(title)); 14898 lines = pushOrConcat(lines, splitNewlines(afterTitle)); 14899 return lines; 14900 } 14901 }, { 14902 key: "getBeforeBody", 14903 value: function getBeforeBody(tooltipItems, options) { 14904 return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'beforeBody', this, tooltipItems)); 14905 } 14906 }, { 14907 key: "getBody", 14908 value: function getBody(tooltipItems, options) { 14909 var _this30 = this; 14910 var callbacks = options.callbacks; 14911 var bodyItems = []; 14912 each(tooltipItems, function (context) { 14913 var bodyItem = { 14914 before: [], 14915 lines: [], 14916 after: [] 14917 }; 14918 var scoped = overrideCallbacks(callbacks, context); 14919 pushOrConcat(bodyItem.before, splitNewlines(invokeCallbackWithFallback(scoped, 'beforeLabel', _this30, context))); 14920 pushOrConcat(bodyItem.lines, invokeCallbackWithFallback(scoped, 'label', _this30, context)); 14921 pushOrConcat(bodyItem.after, splitNewlines(invokeCallbackWithFallback(scoped, 'afterLabel', _this30, context))); 14922 bodyItems.push(bodyItem); 14923 }); 14924 return bodyItems; 14925 } 14926 }, { 14927 key: "getAfterBody", 14928 value: function getAfterBody(tooltipItems, options) { 14929 return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'afterBody', this, tooltipItems)); 14930 } 14931 }, { 14932 key: "getFooter", 14933 value: function getFooter(tooltipItems, options) { 14934 var callbacks = options.callbacks; 14935 var beforeFooter = invokeCallbackWithFallback(callbacks, 'beforeFooter', this, tooltipItems); 14936 var footer = invokeCallbackWithFallback(callbacks, 'footer', this, tooltipItems); 14937 var afterFooter = invokeCallbackWithFallback(callbacks, 'afterFooter', this, tooltipItems); 14938 var lines = []; 14939 lines = pushOrConcat(lines, splitNewlines(beforeFooter)); 14940 lines = pushOrConcat(lines, splitNewlines(footer)); 14941 lines = pushOrConcat(lines, splitNewlines(afterFooter)); 14942 return lines; 14943 } 14944 }, { 14945 key: "_createItems", 14946 value: function _createItems(options) { 14947 var _this31 = this; 14948 var active = this._active; 14949 var data = this.chart.data; 14950 var labelColors = []; 14951 var labelPointStyles = []; 14952 var labelTextColors = []; 14953 var tooltipItems = []; 14954 var i, len; 14955 for (i = 0, len = active.length; i < len; ++i) { 14956 tooltipItems.push(createTooltipItem(this.chart, active[i])); 14957 } 14958 if (options.filter) { 14959 tooltipItems = tooltipItems.filter(function (element, index, array) { 14960 return options.filter(element, index, array, data); 14961 }); 14962 } 14963 if (options.itemSort) { 14964 tooltipItems = tooltipItems.sort(function (a, b) { 14965 return options.itemSort(a, b, data); 14966 }); 14967 } 14968 each(tooltipItems, function (context) { 14969 var scoped = overrideCallbacks(options.callbacks, context); 14970 labelColors.push(invokeCallbackWithFallback(scoped, 'labelColor', _this31, context)); 14971 labelPointStyles.push(invokeCallbackWithFallback(scoped, 'labelPointStyle', _this31, context)); 14972 labelTextColors.push(invokeCallbackWithFallback(scoped, 'labelTextColor', _this31, context)); 14973 }); 14974 this.labelColors = labelColors; 14975 this.labelPointStyles = labelPointStyles; 14976 this.labelTextColors = labelTextColors; 14977 this.dataPoints = tooltipItems; 14978 return tooltipItems; 14979 } 14980 }, {
14981 key: "update", 14982 value: function update(changed, replay) { 14983 var options = this.options.setContext(this.getContext()); 14984 var active = this._active; 14985 var properties; 14986 var tooltipItems = []; 14987 if (!active.length) { 14988 if (this.opacity !== 0) { 14989 properties = { 14990 opacity: 0 14991 }; 14992 } 14993 } else { 14994 var position = positioners[options.position].call(this, active, this._eventPosition); 14995 tooltipItems = this._createItems(options); 14996 this.title = this.getTitle(tooltipItems, options); 14997 this.beforeBody = this.getBeforeBody(tooltipItems, options); 14998 this.body = this.getBody(tooltipItems, options); 14999 this.afterBody = this.getAfterBody(tooltipItems, options); 15000 this.footer = this.getFooter(tooltipItems, options); 15001 var size = this._size = getTooltipSize(this, options); 15002 var positionAndSize = Object.assign({}, position, size); 15003 var alignment = determineAlignment(this.chart, options, positionAndSize); 15004 var backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart); 15005 this.xAlign = alignment.xAlign; 15006 this.yAlign = alignment.yAlign; 15007 properties = { 15008 opacity: 1, 15009 x: backgroundPoint.x, 15010 y: backgroundPoint.y, 15011 width: size.width, 15012 height: size.height, 15013 caretX: position.x, 15014 caretY: position.y 15015 }; 15016 } 15017 this._tooltipItems = tooltipItems; 15018 this.$context = undefined; 15019 if (properties) { 15020 this._resolveAnimations().update(this, properties); 15021 } 15022 if (changed && options.external) { 15023 options.external.call(this, { 15024 chart: this.chart, 15025 tooltip: this, 15026 replay: replay 15027 }); 15028 } 15029 } 15030 }, { 15031 key: "drawCaret", 15032 value: function drawCaret(tooltipPoint, ctx, size, options) { 15033 var caretPosition = this.getCaretPosition(tooltipPoint, size, options); 15034 ctx.lineTo(caretPosition.x1, caretPosition.y1); 15035 ctx.lineTo(caretPosition.x2, caretPosition.y2); 15036 ctx.lineTo(caretPosition.x3, caretPosition.y3); 15037 } 15038 }, { 15039 key: "getCaretPosition", 15040 value: function getCaretPosition(tooltipPoint, size, options) { 15041 var xAlign = this.xAlign, 15042 yAlign = this.yAlign; 15043 var caretSize = options.caretSize, 15044 cornerRadius = options.cornerRadius; 15045 var _toTRBLCorners2 = toTRBLCorners(cornerRadius), 15046 topLeft = _toTRBLCorners2.topLeft, 15047 topRight = _toTRBLCorners2.topRight, 15048 bottomLeft = _toTRBLCorners2.bottomLeft, 15049 bottomRight = _toTRBLCorners2.bottomRight; 15050 var ptX = tooltipPoint.x, 15051 ptY = tooltipPoint.y; 15052 var width = size.width, 15053 height = size.height; 15054 var x1, x2, x3, y1, y2, y3; 15055 if (yAlign === 'center') { 15056 y2 = ptY + height / 2; 15057 if (xAlign === 'left') { 15058 x1 = ptX; 15059 x2 = x1 - caretSize; 15060 y1 = y2 + caretSize; 15061 y3 = y2 - caretSize; 15062 } else { 15063 x1 = ptX + width; 15064 x2 = x1 + caretSize; 15065 y1 = y2 - caretSize; 15066 y3 = y2 + caretSize; 15067 } 15068 x3 = x1; 15069 } else { 15070 if (xAlign === 'left') { 15071 x2 = ptX + Math.max(topLeft, bottomLeft) + caretSize; 15072 } else if (xAlign === 'right') { 15073 x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize; 15074 } else { 15075 x2 = this.caretX; 15076 } 15077 if (yAlign === 'top') { 15078 y1 = ptY; 15079 y2 = y1 - caretSize; 15080 x1 = x2 - caretSize; 15081 x3 = x2 + caretSize; 15082 } else { 15083 y1 = ptY + height; 15084 y2 = y1 + caretSize; 15085 x1 = x2 + caretSize; 15086 x3 = x2 - caretSize; 15087 } 15088 y3 = y1; 15089 } 15090 return { 15091 x1: x1, 15092 x2: x2, 15093 x3: x3, 15094 y1: y1, 15095 y2: y2, 15096 y3: y3 15097 }; 15098 } 15099 }, {
15100 key: "drawTitle", 15101 value: function drawTitle(pt, ctx, options) { 15102 var title = this.title; 15103 var length = title.length; 15104 var titleFont, titleSpacing, i; 15105 if (length) { 15106 var rtlHelper = getRtlAdapter(options.rtl, this.x, this.width); 15107 pt.x = getAlignedX(this, options.titleAlign, options); 15108 ctx.textAlign = rtlHelper.textAlign(options.titleAlign); 15109 ctx.textBaseline = 'middle'; 15110 titleFont = toFont(options.titleFont); 15111 titleSpacing = options.titleSpacing; 15112 ctx.fillStyle = options.titleColor; 15113 ctx.font = titleFont.string; 15114 for (i = 0; i < length; ++i) { 15115 ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2); 15116 pt.y += titleFont.lineHeight + titleSpacing; 15117 if (i + 1 === length) { 15118 pt.y += options.titleMarginBottom - titleSpacing; 15119 } 15120 } 15121 } 15122 } 15123 }, { 15124 key: "_drawColorBox", 15125 value: function _drawColorBox(ctx, pt, i, rtlHelper, options) { 15126 var labelColor = this.labelColors[i]; 15127 var labelPointStyle = this.labelPointStyles[i]; 15128 var boxHeight = options.boxHeight, 15129 boxWidth = options.boxWidth; 15130 var bodyFont = toFont(options.bodyFont); 15131 var colorX = getAlignedX(this, 'left', options); 15132 var rtlColorX = rtlHelper.x(colorX); 15133 var yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0; 15134 var colorY = pt.y + yOffSet; 15135 if (options.usePointStyle) { 15136 var drawOptions = { 15137 radius: Math.min(boxWidth, boxHeight) / 2, 15138 pointStyle: labelPointStyle.pointStyle, 15139 rotation: labelPointStyle.rotation, 15140 borderWidth: 1 15141 }; 15142 var centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2; 15143 var centerY = colorY + boxHeight / 2; 15144 ctx.strokeStyle = options.multiKeyBackground; 15145 ctx.fillStyle = options.multiKeyBackground; 15146 drawPoint(ctx, drawOptions, centerX, centerY); 15147 ctx.strokeStyle = labelColor.borderColor; 15148 ctx.fillStyle = labelColor.backgroundColor; 15149 drawPoint(ctx, drawOptions, centerX, centerY); 15150 } else { 15151 ctx.lineWidth = isObject(labelColor.borderWidth) ? Math.max.apply(Math, _toConsumableArray(Object.values(labelColor.borderWidth))) : labelColor.borderWidth || 1; 15152 ctx.strokeStyle = labelColor.borderColor; 15153 ctx.setLineDash(labelColor.borderDash || []); 15154 ctx.lineDashOffset = labelColor.borderDashOffset || 0; 15155 var outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth); 15156 var innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2); 15157 var borderRadius = toTRBLCorners(labelColor.borderRadius); 15158 if (Object.values(borderRadius).some(function (v) { 15159 return v !== 0; 15160 })) { 15161 ctx.beginPath(); 15162 ctx.fillStyle = options.multiKeyBackground; 15163 addRoundedRectPath(ctx, { 15164 x: outerX, 15165 y: colorY, 15166 w: boxWidth, 15167 h: boxHeight, 15168 radius: borderRadius 15169 }); 15170 ctx.fill(); 15171 ctx.stroke(); 15172 ctx.fillStyle = labelColor.backgroundColor; 15173 ctx.beginPath(); 15174 addRoundedRectPath(ctx, { 15175 x: innerX, 15176 y: colorY + 1, 15177 w: boxWidth - 2, 15178 h: boxHeight - 2, 15179 radius: borderRadius 15180 }); 15181 ctx.fill(); 15182 } else { 15183 ctx.fillStyle = options.multiKeyBackground; 15184 ctx.fillRect(outerX, colorY, boxWidth, boxHeight); 15185 ctx.strokeRect(outerX, colorY, boxWidth, boxHeight); 15186 ctx.fillStyle = labelColor.backgroundColor; 15187 ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2); 15188 } 15189 } 15190 ctx.fillStyle = this.labelTextColors[i]; 15191 } 15192 }, { 15193 key: "drawBody", 15194 value: function drawBody(pt, ctx, options) { 15195 var body = this.body; 15196 var bodySpacing = options.bodySpacing, 15197 bodyAlign = options.bodyAlign, 15198 displayColors = options.displayColors, 15199 boxHeight = options.boxHeight, 15200 boxWidth = options.boxWidth, 15201 boxPadding = options.boxPadding; 15202 var bodyFont = toFont(options.bodyFont); 15203 var bodyLineHeight = bodyFont.lineHeight; 15204 var xLinePadding = 0; 15205 var rtlHelper = getRtlAdapter(options.rtl, this.x, this.width); 15206 var fillLineOfText = function fillLineOfText(line) { 15207 ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2); 15208 pt.y += bodyLineHeight + bodySpacing; 15209 }; 15210 var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign); 15211 var bodyItem, textColor, lines, i, j, ilen, jlen; 15212 ctx.textAlign = bodyAlign; 15213 ctx.textBaseline = 'middle'; 15214 ctx.font = bodyFont.string; 15215 pt.x = getAlignedX(this, bodyAlignForCalculation, options); 15216 ctx.fillStyle = options.bodyColor; 15217 each(this.beforeBody, fillLineOfText); 15218 xLinePadding = displayColors && bodyAlignForCalculation !== 'right' ? bodyAlign === 'center' ? boxWidth / 2 + boxPadding : boxWidth + 2 + boxPadding : 0; 15219 for (i = 0, ilen = body.length; i < ilen; ++i) { 15220 bodyItem = body[i]; 15221 textColor = this.labelTextColors[i]; 15222 ctx.fillStyle = textColor; 15223 each(bodyItem.before, fillLineOfText); 15224 lines = bodyItem.lines; 15225 if (displayColors && lines.length) { 15226 this._drawColorBox(ctx, pt, i, rtlHelper, options); 15227 bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight); 15228 } 15229 for (j = 0, jlen = lines.length; j < jlen; ++j) { 15230 fillLineOfText(lines[j]); 15231 bodyLineHeight = bodyFont.lineHeight; 15232 } 15233 each(bodyItem.after, fillLineOfText); 15234 } 15235 xLinePadding = 0; 15236 bodyLineHeight = bodyFont.lineHeight; 15237 each(this.afterBody, fillLineOfText); 15238 pt.y -= bodySpacing; 15239 } 15240 }, {
15241 key: "drawFooter", 15242 value: function drawFooter(pt, ctx, options) { 15243 var footer = this.footer; 15244 var length = footer.length; 15245 var footerFont, i; 15246 if (length) { 15247 var rtlHelper = getRtlAdapter(options.rtl, this.x, this.width); 15248 pt.x = getAlignedX(this, options.footerAlign, options); 15249 pt.y += options.footerMarginTop; 15250 ctx.textAlign = rtlHelper.textAlign(options.footerAlign); 15251 ctx.textBaseline = 'middle'; 15252 footerFont = toFont(options.footerFont); 15253 ctx.fillStyle = options.footerColor; 15254 ctx.font = footerFont.string; 15255 for (i = 0; i < length; ++i) { 15256 ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2); 15257 pt.y += footerFont.lineHeight + options.footerSpacing; 15258 } 15259 } 15260 } 15261 }, { 15262 key: "drawBackground", 15263 value: function drawBackground(pt, ctx, tooltipSize, options) { 15264 var xAlign = this.xAlign, 15265 yAlign = this.yAlign; 15266 var x = pt.x, 15267 y = pt.y; 15268 var width = tooltipSize.width, 15269 height = tooltipSize.height; 15270 var _toTRBLCorners3 = toTRBLCorners(options.cornerRadius), 15271 topLeft = _toTRBLCorners3.topLeft, 15272 topRight = _toTRBLCorners3.topRight, 15273 bottomLeft = _toTRBLCorners3.bottomLeft, 15274 bottomRight = _toTRBLCorners3.bottomRight; 15275 ctx.fillStyle = options.backgroundColor; 15276 ctx.strokeStyle = options.borderColor; 15277 ctx.lineWidth = options.borderWidth; 15278 ctx.beginPath(); 15279 ctx.moveTo(x + topLeft, y); 15280 if (yAlign === 'top') { 15281 this.drawCaret(pt, ctx, tooltipSize, options); 15282 } 15283 ctx.lineTo(x + width - topRight, y); 15284 ctx.quadraticCurveTo(x + width, y, x + width, y + topRight); 15285 if (yAlign === 'center' && xAlign === 'right') { 15286 this.drawCaret(pt, ctx, tooltipSize, options); 15287 } 15288 ctx.lineTo(x + width, y + height - bottomRight); 15289 ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height); 15290 if (yAlign === 'bottom') { 15291 this.drawCaret(pt, ctx, tooltipSize, options); 15292 } 15293 ctx.lineTo(x + bottomLeft, y + height); 15294 ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft); 15295 if (yAlign === 'center' && xAlign === 'left') { 15296 this.drawCaret(pt, ctx, tooltipSize, options); 15297 } 15298 ctx.lineTo(x, y + topLeft); 15299 ctx.quadraticCurveTo(x, y, x + topLeft, y); 15300 ctx.closePath(); 15301 ctx.fill(); 15302 if (options.borderWidth > 0) { 15303 ctx.stroke(); 15304 } 15305 } 15306 }, { 15307 key: "_updateAnimationTarget", 15308 value: function _updateAnimationTarget(options) { 15309 var chart = this.chart; 15310 var anims = this.$animations; 15311 var animX = anims && anims.x; 15312 var animY = anims && anims.y; 15313 if (animX || animY) { 15314 var position = positioners[options.position].call(this, this._active, this._eventPosition); 15315 if (!position) { 15316 return; 15317 } 15318 var size = this._size = getTooltipSize(this, options); 15319 var positionAndSize = Object.assign({}, position, this._size); 15320 var alignment = determineAlignment(chart, options, positionAndSize); 15321 var point = getBackgroundPoint(options, positionAndSize, alignment, chart); 15322 if (animX._to !== point.x || animY._to !== point.y) { 15323 this.xAlign = alignment.xAlign; 15324 this.yAlign = alignment.yAlign; 15325 this.width = size.width; 15326 this.height = size.height; 15327 this.caretX = position.x; 15328 this.caretY = position.y; 15329 this._resolveAnimations().update(this, point); 15330 } 15331 } 15332 } 15333 }, { 15334 key: "_willRender", 15335 value: function _willRender() { 15336 return !!this.opacity; 15337 } 15338 }, { 15339 key: "draw", 15340 value: function draw(ctx) { 15341 var options = this.options.setContext(this.getContext()); 15342 var opacity = this.opacity; 15343 if (!opacity) { 15344 return; 15345 } 15346 this._updateAnimationTarget(options); 15347 var tooltipSize = { 15348 width: this.width, 15349 height: this.height 15350 }; 15351 var pt = { 15352 x: this.x, 15353 y: this.y 15354 }; 15355 opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity; 15356 var padding = toPadding(options.padding); 15357 var hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length; 15358 if (options.enabled && hasTooltipContent) { 15359 ctx.save(); 15360 ctx.globalAlpha = opacity;
15361 this.drawBackground(pt, ctx, tooltipSize, options); 15362 overrideTextDirection(ctx, options.textDirection); 15363 pt.y += padding.top; 15364 this.drawTitle(pt, ctx, options); 15365 this.drawBody(pt, ctx, options); 15366 this.drawFooter(pt, ctx, options); 15367 restoreTextDirection(ctx, options.textDirection); 15368 ctx.restore(); 15369 } 15370 } 15371 }, { 15372 key: "getActiveElements", 15373 value: function getActiveElements() { 15374 return this._active || []; 15375 } 15376 }, { 15377 key: "setActiveElements", 15378 value: function setActiveElements(activeElements, eventPosition) { 15379 var _this32 = this; 15380 var lastActive = this._active; 15381 var active = activeElements.map(function (_ref1) { 15382 var datasetIndex = _ref1.datasetIndex, 15383 index = _ref1.index; 15384 var meta = _this32.chart.getDatasetMeta(datasetIndex); 15385 if (!meta) { 15386 throw new Error('Cannot find a dataset at index ' + datasetIndex); 15387 } 15388 return { 15389 datasetIndex: datasetIndex, 15390 element: meta.data[index], 15391 index: index 15392 }; 15393 }); 15394 var changed = !_elementsEqual(lastActive, active); 15395 var positionChanged = this._positionChanged(active, eventPosition); 15396 if (changed || positionChanged) { 15397 this._active = active; 15398 this._eventPosition = eventPosition; 15399 this._ignoreReplayEvents = true; 15400 this.update(true); 15401 } 15402 } 15403 }, { 15404 key: "handleEvent", 15405 value: function handleEvent(e, replay) { 15406 var inChartArea = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; 15407 if (replay && this._ignoreReplayEvents) { 15408 return false; 15409 } 15410 this._ignoreReplayEvents = false; 15411 var options = this.options; 15412 var lastActive = this._active || []; 15413 var active = this._getActiveElements(e, lastActive, replay, inChartArea); 15414 var positionChanged = this._positionChanged(active, e); 15415 var changed = replay || !_elementsEqual(active, lastActive) || positionChanged; 15416 if (changed) { 15417 this._active = active; 15418 if (options.enabled || options.external) { 15419 this._eventPosition = { 15420 x: e.x, 15421 y: e.y 15422 }; 15423 this.update(true, replay); 15424 } 15425 } 15426 return changed; 15427 } 15428 }, { 15429 key: "_getActiveElements", 15430 value: function _getActiveElements(e, lastActive, replay, inChartArea) { 15431 var _this33 = this; 15432 var options = this.options; 15433 if (e.type === 'mouseout') { 15434 return []; 15435 } 15436 if (!inChartArea) { 15437 return lastActive.filter(function (i) { 15438 return _this33.chart.data.datasets[i.datasetIndex] && _this33.chart.getDatasetMeta(i.datasetIndex).controller.getParsed(i.index) !== undefined; 15439 }); 15440 } 15441 var active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay); 15442 if (options.reverse) { 15443 active.reverse(); 15444 } 15445 return active; 15446 } 15447 }, { 15448 key: "_positionChanged", 15449 value: function _positionChanged(active, e) { 15450 var caretX = this.caretX, 15451 caretY = this.caretY, 15452 options = this.options; 15453 var position = positioners[options.position].call(this, active, e); 15454 return position !== false && (caretX !== position.x || caretY !== position.y); 15455 } 15456 }]); 15457 }(Element); 15458 _defineProperty$1(Tooltip, "positioners", positioners); 15459 var plugin_tooltip = { 15460 id: 'tooltip', 15461 _element: Tooltip, 15462 positioners: positioners, 15463 afterInit: function afterInit(chart, _args, options) { 15464 if (options) { 15465 chart.tooltip = new Tooltip({ 15466 chart: chart, 15467 options: options 15468 }); 15469 } 15470 }, 15471 beforeUpdate: function beforeUpdate(chart, _args, options) { 15472 if (chart.tooltip) { 15473 chart.tooltip.initialize(options); 15474 } 15475 }, 15476 reset: function reset(chart, _args, options) { 15477 if (chart.tooltip) { 15478 chart.tooltip.initialize(options); 15479 } 15480 }, 15481 afterDraw: function afterDraw(chart) { 15482 var tooltip = chart.tooltip; 15483 if (tooltip && tooltip._willRender()) { 15484 var args = { 15485 tooltip: tooltip 15486 }; 15487 if (chart.notifyPlugins('beforeTooltipDraw', _objectSpread2
15487(_objectSpread2({}, args), {}, { 15488 cancelable: true 15489 })) === false) { 15490 return; 15491 } 15492 tooltip.draw(chart.ctx); 15493 chart.notifyPlugins('afterTooltipDraw', args); 15494 } 15495 }, 15496 afterEvent: function afterEvent(chart, args) { 15497 if (chart.tooltip) { 15498 var useFinalPosition = args.replay; 15499 if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) { 15500 args.changed = true; 15501 } 15502 } 15503 }, 15504 defaults: { 15505 enabled: true, 15506 external: null, 15507 position: 'average', 15508 backgroundColor: 'rgba(0,0,0,0.8)', 15509 titleColor: '#fff', 15510 titleFont: { 15511 weight: 'bold' 15512 }, 15513 titleSpacing: 2, 15514 titleMarginBottom: 6, 15515 titleAlign: 'left', 15516 bodyColor: '#fff', 15517 bodySpacing: 2, 15518 bodyFont: {}, 15519 bodyAlign: 'left', 15520 footerColor: '#fff', 15521 footerSpacing: 2, 15522 footerMarginTop: 6, 15523 footerFont: { 15524 weight: 'bold' 15525 }, 15526 footerAlign: 'left', 15527 padding: 6, 15528 caretPadding: 2, 15529 caretSize: 5, 15530 cornerRadius: 6, 15531 boxHeight: function boxHeight(ctx, opts) { 15532 return opts.bodyFont.size; 15533 }, 15534 boxWidth: function boxWidth(ctx, opts) { 15535 return opts.bodyFont.size; 15536 }, 15537 multiKeyBackground: '#fff', 15538 displayColors: true, 15539 boxPadding: 0, 15540 borderColor: 'rgba(0,0,0,0)', 15541 borderWidth: 0, 15542 animation: { 15543 duration: 400, 15544 easing: 'easeOutQuart' 15545 }, 15546 animations: { 15547 numbers: { 15548 type: 'number', 15549 properties: ['x', 'y', 'width', 'height', 'caretX', 'caretY'] 15550 }, 15551 opacity: { 15552 easing: 'linear', 15553 duration: 200 15554 } 15555 }, 15556 callbacks: defaultCallbacks 15557 }, 15558 defaultRoutes: { 15559 bodyFont: 'font', 15560 footerFont: 'font', 15561 titleFont: 'font' 15562 }, 15563 descriptors: { 15564 _scriptable: function _scriptable(name) { 15565 return name !== 'filter' && name !== 'itemSort' && name !== 'external'; 15566 }, 15567 _indexable: false, 15568 callbacks: { 15569 _scriptable: false, 15570 _indexable: false 15571 }, 15572 animation: { 15573 _fallback: false 15574 }, 15575 animations: { 15576 _fallback: 'animation' 15577 } 15578 }, 15579 additionalOptionScopes: ['interaction'] 15580 }; 15581 var plugins = /*#__PURE__*/Object.freeze({ 15582 __proto__: null, 15583 Colors: plugin_colors, 15584 Decimation: plugin_decimation, 15585 Filler: index, 15586 Legend: plugin_legend, 15587 SubTitle: plugin_subtitle, 15588 Title: plugin_title, 15589 Tooltip: plugin_tooltip 15590 }); 15591 var addIfString = function addIfString(labels, raw, index, addedLabels) { 15592 if (typeof raw === 'string') { 15593 index = labels.push(raw) - 1; 15594 addedLabels.unshift({ 15595 index: index, 15596 label: raw 15597 }); 15598 } else if (isNaN(raw)) { 15599 index = null; 15600 } 15601 return index; 15602 }; 15603 function findOrAddLabel(labels, raw, index, addedLabels) { 15604 var first = labels.indexOf(raw); 15605 if (first === -1) { 15606 return addIfString(labels, raw, index, addedLabels); 15607 } 15608 var last = labels.lastIndexOf(raw); 15609 return first !== last ? index : first; 15610 }
15611 var validIndex = function validIndex(index, max) { 15612 return index === null ? null : _limitValue(Math.round(index), 0, max); 15613 }; 15614 function _getLabelForValue(value) { 15615 var labels = this.getLabels(); 15616 if (value >= 0 && value < labels.length) { 15617 return labels[value]; 15618 } 15619 return value; 15620 } 15621 var CategoryScale = /*#__PURE__*/function (_Scale) { 15622 function CategoryScale(cfg) { 15623 var _this34; 15624 _classCallCheck$1(this, CategoryScale); 15625 _this34 = _callSuper(this, CategoryScale, [cfg]); 15626 _this34._startValue = undefined; 15627 _this34._valueRange = 0; 15628 _this34._addedLabels = []; 15629 return _this34; 15630 } 15631 _inherits$1(CategoryScale, _Scale); 15632 return _createClass$1(CategoryScale, [{ 15633 key: "init", 15634 value: function init(scaleOptions) { 15635 var added = this._addedLabels; 15636 if (added.length) { 15637 var labels = this.getLabels(); 15638 var _iterator25 = _createForOfIteratorHelper$1(added), 15639 _step25; 15640 try { 15641 for (_iterator25.s(); !(_step25 = _iterator25.n()).done;) { 15642 var _step25$value = _step25.value, 15643 _index3 = _step25$value.index, 15644 label = _step25$value.label; 15645 if (labels[_index3] === label) { 15646 labels.splice(_index3, 1); 15647 } 15648 } 15649 } catch (err) { 15650 _iterator25.e(err); 15651 } finally { 15652 _iterator25.f(); 15653 } 15654 this._addedLabels = []; 15655 } 15656 _superPropGet(CategoryScale, "init", this, 3)([scaleOptions]); 15657 } 15658 }, { 15659 key: "parse", 15660 value: function parse(raw, index) { 15661 if (isNullOrUndef(raw)) { 15662 return null; 15663 } 15664 var labels = this.getLabels(); 15665 index = isFinite(index) && labels[index] === raw ? index : findOrAddLabel(labels, raw, valueOrDefault(index, raw), this._addedLabels); 15666 return validIndex(index, labels.length - 1); 15667 } 15668 }, { 15669 key: "determineDataLimits", 15670 value: function determineDataLimits() { 15671 var _this$getUserBounds2 = this.getUserBounds(), 15672 minDefined = _this$getUserBounds2.minDefined, 15673 maxDefined = _this$getUserBounds2.maxDefined; 15674 var _this$getMinMax = this.getMinMax(true), 15675 min = _this$getMinMax.min, 15676 max = _this$getMinMax.max; 15677 if (this.options.bounds === 'ticks') { 15678 if (!minDefined) { 15679 min = 0; 15680 } 15681 if (!maxDefined) { 15682 max = this.getLabels().length - 1; 15683 } 15684 } 15685 this.min = min; 15686 this.max = max; 15687 } 15688 }, { 15689 key: "buildTicks", 15690 value: function buildTicks() { 15691 var min = this.min; 15692 var max = this.max; 15693 var offset = this.options.offset; 15694 var ticks = []; 15695 var labels = this.getLabels(); 15696 labels = min === 0 && max === labels.length - 1 ? labels : labels.slice(min, max + 1); 15697 this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1); 15698 this._startValue = this.min - (offset ? 0.5 : 0); 15699 for (var value = min; value <= max; value++) { 15700 ticks.push({ 15701 value: value 15702 }); 15703 } 15704 return ticks; 15705 } 15706 }, { 15707 key: "getLabelForValue", 15708 value: function getLabelForValue(value) { 15709 return _getLabelForValue.call(this, value); 15710 } 15711 }, { 15712 key: "configure", 15713 value: function configure() { 15714 _superPropGet(CategoryScale, "configure", this, 3)([]); 15715 if (!this.isHorizontal()) { 15716 this._reversePixels = !this._reversePixels; 15717 } 15718 } 15719 }, { 15720 key: "getPixelForValue", 15721 value: function getPixelForValue(value) { 15722 if (typeof value !== 'number') { 15723 value = this.parse(value); 15724 } 15725 return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange); 15726 } 15727 }, { 15728 key: "getPixelForTick", 15729 value: function getPixelForTick(index) { 15730 var ticks = this.ticks; 15731 if (index < 0 || index > ticks.length - 1) { 15732 return null; 15733 } 15734 return this.getPixelForValue(ticks[index].value); 15735 } 15736 }, {
15737 key: "getValueForPixel", 15738 value: function getValueForPixel(pixel) { 15739 return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange); 15740 } 15741 }, { 15742 key: "getBasePixel", 15743 value: function getBasePixel() { 15744 return this.bottom; 15745 } 15746 }]); 15747 }(Scale); 15748 _defineProperty$1(CategoryScale, "id", 'category'); 15749 _defineProperty$1(CategoryScale, "defaults", { 15750 ticks: { 15751 callback: _getLabelForValue 15752 } 15753 }); 15754 function generateTicks$1(generationOptions, dataRange) { 15755 var ticks = []; 15756 var MIN_SPACING = 1e-14; 15757 var bounds = generationOptions.bounds, 15758 step = generationOptions.step, 15759 min = generationOptions.min, 15760 max = generationOptions.max, 15761 precision = generationOptions.precision, 15762 count = generationOptions.count, 15763 maxTicks = generationOptions.maxTicks, 15764 maxDigits = generationOptions.maxDigits, 15765 includeBounds = generationOptions.includeBounds; 15766 var unit = step || 1; 15767 var maxSpaces = maxTicks - 1; 15768 var rmin = dataRange.min, 15769 rmax = dataRange.max; 15770 var minDefined = !isNullOrUndef(min); 15771 var maxDefined = !isNullOrUndef(max); 15772 var countDefined = !isNullOrUndef(count); 15773 var minSpacing = (rmax - rmin) / (maxDigits + 1); 15774 var spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit; 15775 var factor, niceMin, niceMax, numSpaces; 15776 if (spacing < MIN_SPACING && !minDefined && !maxDefined) { 15777 return [{ 15778 value: rmin 15779 }, { 15780 value: rmax 15781 }]; 15782 } 15783 numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing); 15784 if (numSpaces > maxSpaces) { 15785 spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit; 15786 } 15787 if (!isNullOrUndef(precision)) { 15788 factor = Math.pow(10, precision); 15789 spacing = Math.ceil(spacing * factor) / factor; 15790 } 15791 if (bounds === 'ticks') { 15792 niceMin = Math.floor(rmin / spacing) * spacing; 15793 niceMax = Math.ceil(rmax / spacing) * spacing; 15794 } else { 15795 niceMin = rmin; 15796 niceMax = rmax; 15797 } 15798 if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) { 15799 numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks)); 15800 spacing = (max - min) / numSpaces; 15801 niceMin = min; 15802 niceMax = max; 15803 } else if (countDefined) { 15804 niceMin = minDefined ? min : niceMin; 15805 niceMax = maxDefined ? max : niceMax; 15806 numSpaces = count - 1; 15807 spacing = (niceMax - niceMin) / numSpaces; 15808 } else { 15809 numSpaces = (niceMax - niceMin) / spacing; 15810 if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { 15811 numSpaces = Math.round(numSpaces); 15812 } else { 15813 numSpaces = Math.ceil(numSpaces); 15814 } 15815 } 15816 var decimalPlaces = Math.max(_decimalPlaces(spacing), _decimalPlaces(niceMin)); 15817 factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision); 15818 niceMin = Math.round(niceMin * factor) / factor; 15819 niceMax = Math.round(niceMax * factor) / factor; 15820 var j = 0; 15821 if (minDefined) { 15822 if (includeBounds && niceMin !== min) { 15823 ticks.push({ 15824 value: min 15825 }); 15826 if (niceMin < min) { 15827 j++; 15828 } 15829 if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) { 15830 j++; 15831 } 15832 } else if (niceMin < min) { 15833 j++; 15834 } 15835 } 15836 for (; j < numSpaces; ++j) { 15837 var tickValue = Math.round((niceMin + j * spacing) * factor) / factor; 15838 if (maxDefined && tickValue > max) { 15839 break; 15840 } 15841 ticks.push({ 15842 value: tickValue 15843 }); 15844 } 15845 if (maxDefined && includeBounds && niceMax !== max) { 15846 if (ticks.length && almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) { 15847 ticks[ticks.length - 1].value = max; 15848 } else { 15849 ticks.push({ 15850 value: max 15851 }); 15852 } 15853 } else if (!maxDefined || niceMax === max) { 15854 ticks.push({ 15855 value: niceMax 15856 }); 15857 } 15858 return ticks; 15859 } 15860 function relativeLabelSize(value, minSpacing, _ref10) { 15861 var horizontal = _ref10.horizontal, 15862 minRotation = _ref10.minRotation; 15863 var rad = toRadians(minRotation); 15864 var ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001; 15865 var length = 0.75 * minSpacing * ('' + value).length; 15866 return Math.min(minSpacing / ratio, length); 15867 }
15868 var LinearScaleBase = /*#__PURE__*/function (_Scale2) { 15869 function LinearScaleBase(cfg) { 15870 var _this35; 15871 _classCallCheck$1(this, LinearScaleBase); 15872 _this35 = _callSuper(this, LinearScaleBase, [cfg]); 15873 _this35.start = undefined; 15874 _this35.end = undefined; 15875 _this35._startValue = undefined; 15876 _this35._endValue = undefined; 15877 _this35._valueRange = 0; 15878 return _this35; 15879 } 15880 _inherits$1(LinearScaleBase, _Scale2); 15881 return _createClass$1(LinearScaleBase, [{ 15882 key: "parse", 15883 value: function parse(raw, index) { 15884 if (isNullOrUndef(raw)) { 15885 return null; 15886 } 15887 if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) { 15888 return null; 15889 } 15890 return +raw; 15891 } 15892 }, { 15893 key: "handleTickRangeOptions", 15894 value: function handleTickRangeOptions() { 15895 var beginAtZero = this.options.beginAtZero; 15896 var _this$getUserBounds3 = this.getUserBounds(), 15897 minDefined = _this$getUserBounds3.minDefined, 15898 maxDefined = _this$getUserBounds3.maxDefined; 15899 var min = this.min, 15900 max = this.max; 15901 var setMin = function setMin(v) { 15902 return min = minDefined ? min : v; 15903 }; 15904 var setMax = function setMax(v) { 15905 return max = maxDefined ? max : v; 15906 }; 15907 if (beginAtZero) { 15908 var minSign = sign(min); 15909 var maxSign = sign(max); 15910 if (minSign < 0 && maxSign < 0) { 15911 setMax(0); 15912 } else if (minSign > 0 && maxSign > 0) { 15913 setMin(0); 15914 } 15915 } 15916 if (min === max) { 15917 var offset = max === 0 ? 1 : Math.abs(max * 0.05); 15918 setMax(max + offset); 15919 if (!beginAtZero) { 15920 setMin(min - offset); 15921 } 15922 } 15923 this.min = min; 15924 this.max = max; 15925 } 15926 }, { 15927 key: "getTickLimit", 15928 value: function getTickLimit() { 15929 var tickOpts = this.options.ticks; 15930 var maxTicksLimit = tickOpts.maxTicksLimit, 15931 stepSize = tickOpts.stepSize; 15932 var maxTicks; 15933 if (stepSize) { 15934 maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1; 15935 if (maxTicks > 1000) { 15936 console.warn("scales.".concat(this.id, ".ticks.stepSize: ").concat(stepSize, " would result generating up to ").concat(maxTicks, " ticks. Limiting to 1000.")); 15937 maxTicks = 1000; 15938 } 15939 } else { 15940 maxTicks = this.computeTickLimit(); 15941 maxTicksLimit = maxTicksLimit || 11; 15942 } 15943 if (maxTicksLimit) { 15944 maxTicks = Math.min(maxTicksLimit, maxTicks); 15945 } 15946 return maxTicks; 15947 } 15948 }, { 15949 key: "computeTickLimit", 15950 value: function computeTickLimit() { 15951 return Number.POSITIVE_INFINITY; 15952 } 15953 }, { 15954 key: "buildTicks", 15955 value: function buildTicks() { 15956 var opts = this.options; 15957 var tickOpts = opts.ticks; 15958 var maxTicks = this.getTickLimit(); 15959 maxTicks = Math.max(2, maxTicks); 15960 var numericGeneratorOptions = { 15961 maxTicks: maxTicks, 15962 bounds: opts.bounds, 15963 min: opts.min, 15964 max: opts.max, 15965 precision: tickOpts.precision, 15966 step: tickOpts.stepSize, 15967 count: tickOpts.count, 15968 maxDigits: this._maxDigits(), 15969 horizontal: this.isHorizontal(), 15970 minRotation: tickOpts.minRotation || 0, 15971 includeBounds: tickOpts.includeBounds !== false 15972 }; 15973 var dataRange = this._range || this; 15974 var ticks = generateTicks$1(numericGeneratorOptions, dataRange); 15975 if (opts.bounds === 'ticks') { 15976 _setMinAndMaxByKey(ticks, this, 'value'); 15977 } 15978 if (opts.reverse) { 15979 ticks.reverse(); 15980 this.start = this.max; 15981 this.end = this.min; 15982 } else { 15983 this.start = this.min; 15984 this.end = this.max; 15985 } 15986 return ticks; 15987 } 15988 }, { 15989 key: "configure", 15990 value: function configure() { 15991 var ticks = this.ticks; 15992 var start = this.min; 15993 var end = this.max; 15994 _superPropGet(LinearScaleBase, "configure", this, 3)([]); 15995 if (this.options.offset && ticks.length) { 15996 var offset = (end - start) / Math.max(ticks.length - 1, 1) / 2; 15997 start -= offset; 15998 end += offset; 15999 } 16000 this._startValue = start; 16001 this._endValue = end; 16002 this._valueRange = end - start; 16003 } 16004 }, {
16005 key: "getLabelForValue", 16006 value: function getLabelForValue(value) { 16007 return formatNumber(value, this.chart.options.locale, this.options.ticks.format); 16008 } 16009 }]); 16010 }(Scale); 16011 var LinearScale = /*#__PURE__*/function (_LinearScaleBase) { 16012 function LinearScale() { 16013 _classCallCheck$1(this, LinearScale); 16014 return _callSuper(this, LinearScale, arguments); 16015 } 16016 _inherits$1(LinearScale, _LinearScaleBase); 16017 return _createClass$1(LinearScale, [{ 16018 key: "determineDataLimits", 16019 value: function determineDataLimits() { 16020 var _this$getMinMax2 = this.getMinMax(true), 16021 min = _this$getMinMax2.min, 16022 max = _this$getMinMax2.max; 16023 this.min = isNumberFinite(min) ? min : 0; 16024 this.max = isNumberFinite(max) ? max : 1; 16025 this.handleTickRangeOptions(); 16026 } 16027 }, { 16028 key: "computeTickLimit", 16029 value: function computeTickLimit() { 16030 var horizontal = this.isHorizontal(); 16031 var length = horizontal ? this.width : this.height; 16032 var minRotation = toRadians(this.options.ticks.minRotation); 16033 var ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001; 16034 var tickFont = this._resolveTickFontOptions(0); 16035 return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio)); 16036 } 16037 }, { 16038 key: "getPixelForValue", 16039 value: function getPixelForValue(value) { 16040 return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange); 16041 } 16042 }, { 16043 key: "getValueForPixel", 16044 value: function getValueForPixel(pixel) { 16045 return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange; 16046 } 16047 }]); 16048 }(LinearScaleBase); 16049 _defineProperty$1(LinearScale, "id", 'linear'); 16050 _defineProperty$1(LinearScale, "defaults", { 16051 ticks: { 16052 callback: Ticks.formatters.numeric 16053 } 16054 }); 16055 var log10Floor = function log10Floor(v) { 16056 return Math.floor(log10(v)); 16057 }; 16058 var changeExponent = function changeExponent(v, m) { 16059 return Math.pow(10, log10Floor(v) + m); 16060 }; 16061 function isMajor(tickVal) { 16062 var remain = tickVal / Math.pow(10, log10Floor(tickVal)); 16063 return remain === 1; 16064 } 16065 function steps(min, max, rangeExp) { 16066 var rangeStep = Math.pow(10, rangeExp); 16067 var start = Math.floor(min / rangeStep); 16068 var end = Math.ceil(max / rangeStep); 16069 return end - start; 16070 } 16071 function startExp(min, max) { 16072 var range = max - min; 16073 var rangeExp = log10Floor(range); 16074 while (steps(min, max, rangeExp) > 10) { 16075 rangeExp++; 16076 } 16077 while (steps(min, max, rangeExp) < 10) { 16078 rangeExp--; 16079 } 16080 return Math.min(rangeExp, log10Floor(min)); 16081 } 16082 function generateTicks(generationOptions, _ref11) { 16083 var min = _ref11.min, 16084 max = _ref11.max; 16085 min = finiteOrDefault(generationOptions.min, min); 16086 var ticks = []; 16087 var minExp = log10Floor(min); 16088 var exp = startExp(min, max); 16089 var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1; 16090 var stepSize = Math.pow(10, exp); 16091 var base = minExp > exp ? Math.pow(10, minExp) : 0; 16092 var start = Math.round((min - base) * precision) / precision; 16093 var offset = Math.floor((min - base) / stepSize / 10) * stepSize * 10; 16094 var significand = Math.floor((start - offset) / Math.pow(10, exp)); 16095 var value = finiteOrDefault(generationOptions.min, Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision); 16096 while (value < max) { 16097 ticks.push({ 16098 value: value, 16099 major: isMajor(value), 16100 significand: significand 16101 }); 16102 if (significand >= 10) { 16103 significand = significand < 15 ? 15 : 20; 16104 } else { 16105 significand++; 16106 } 16107 if (significand >= 20) { 16108 exp++; 16109 significand = 2; 16110 precision = exp >= 0 ? 1 : precision; 16111 } 16112 value = Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision; 16113 } 16114 var lastTick = finiteOrDefault(generationOptions.max, value); 16115 ticks.push({ 16116 value: lastTick, 16117 major: isMajor(lastTick), 16118 significand: significand 16119 }); 16120 return ticks; 16121 }
16122 var LogarithmicScale = /*#__PURE__*/function (_Scale3) { 16123 function LogarithmicScale(cfg) { 16124 var _this36; 16125 _classCallCheck$1(this, LogarithmicScale); 16126 _this36 = _callSuper(this, LogarithmicScale, [cfg]); 16127 _this36.start = undefined; 16128 _this36.end = undefined; 16129 _this36._startValue = undefined; 16130 _this36._valueRange = 0; 16131 return _this36; 16132 } 16133 _inherits$1(LogarithmicScale, _Scale3); 16134 return _createClass$1(LogarithmicScale, [{ 16135 key: "parse", 16136 value: function parse(raw, index) { 16137 var value = LinearScaleBase.prototype.parse.apply(this, [raw, index]); 16138 if (value === 0) { 16139 this._zero = true; 16140 return undefined; 16141 } 16142 return isNumberFinite(value) && value > 0 ? value : null; 16143 } 16144 }, { 16145 key: "determineDataLimits", 16146 value: function determineDataLimits() { 16147 var _this$getMinMax3 = this.getMinMax(true), 16148 min = _this$getMinMax3.min, 16149 max = _this$getMinMax3.max; 16150 this.min = isNumberFinite(min) ? Math.max(0, min) : null; 16151 this.max = isNumberFinite(max) ? Math.max(0, max) : null; 16152 if (this.options.beginAtZero) { 16153 this._zero = true; 16154 } 16155 if (this._zero && this.min !== this._suggestedMin && !isNumberFinite(this._userMin)) { 16156 this.min = min === changeExponent(this.min, 0) ? changeExponent(this.min, -1) : changeExponent(this.min, 0); 16157 } 16158 this.handleTickRangeOptions(); 16159 } 16160 }, { 16161 key: "handleTickRangeOptions", 16162 value: function handleTickRangeOptions() { 16163 var _this$getUserBounds4 = this.getUserBounds(), 16164 minDefined = _this$getUserBounds4.minDefined, 16165 maxDefined = _this$getUserBounds4.maxDefined; 16166 var min = this.min; 16167 var max = this.max; 16168 var setMin = function setMin(v) { 16169 return min = minDefined ? min : v; 16170 }; 16171 var setMax = function setMax(v) { 16172 return max = maxDefined ? max : v; 16173 }; 16174 if (min === max) { 16175 if (min <= 0) { 16176 setMin(1); 16177 setMax(10); 16178 } else { 16179 setMin(changeExponent(min, -1)); 16180 setMax(changeExponent(max, +1)); 16181 } 16182 } 16183 if (min <= 0) { 16184 setMin(changeExponent(max, -1)); 16185 } 16186 if (max <= 0) { 16187 setMax(changeExponent(min, +1)); 16188 } 16189 this.min = min; 16190 this.max = max; 16191 } 16192 }, { 16193 key: "buildTicks", 16194 value: function buildTicks() { 16195 var opts = this.options; 16196 var generationOptions = { 16197 min: this._userMin, 16198 max: this._userMax 16199 }; 16200 var ticks = generateTicks(generationOptions, this); 16201 if (opts.bounds === 'ticks') { 16202 _setMinAndMaxByKey(ticks, this, 'value'); 16203 } 16204 if (opts.reverse) { 16205 ticks.reverse(); 16206 this.start = this.max; 16207 this.end = this.min; 16208 } else { 16209 this.start = this.min; 16210 this.end = this.max; 16211 } 16212 return ticks; 16213 } 16214 }, { 16215 key: "getLabelForValue", 16216 value: function getLabelForValue(value) { 16217 return value === undefined ? '0' : formatNumber(value, this.chart.options.locale, this.options.ticks.format); 16218 } 16219 }, { 16220 key: "configure", 16221 value: function configure() { 16222 var start = this.min; 16223 _superPropGet(LogarithmicScale, "configure", this, 3)([]); 16224 this._startValue = log10(start); 16225 this._valueRange = log10(this.max) - log10(start); 16226 } 16227 }, { 16228 key: "getPixelForValue", 16229 value: function getPixelForValue(value) { 16230 if (value === undefined || value === 0) { 16231 value = this.min; 16232 } 16233 if (value === null || isNaN(value)) { 16234 return NaN; 16235 } 16236 return this.getPixelForDecimal(value === this.min ? 0 : (log10(value) - this._startValue) / this._valueRange); 16237 } 16238 }, { 16239 key: "getValueForPixel", 16240 value: function getValueForPixel(pixel) { 16241 var decimal = this.getDecimalForPixel(pixel); 16242 return Math.pow(10, this._startValue + decimal * this._valueRange); 16243 } 16244 }]); 16245 }(Scale); 16246 _defineProperty$1(LogarithmicScale, "id", 'logarithmic'); 16247 _defineProperty$1(LogarithmicScale, "defaults", { 16248 ticks: { 16249 callback: Ticks.formatters.logarithmic, 16250 major: { 16251 enabled: true 16252 } 16253 } 16254 }); 16255 function getTickBackdropHeight(opts) { 16256 var tickOpts = opts.ticks; 16257 if (tickOpts.display && opts.display) { 16258 var padding = toPadding(tickOpts.backdropPadding); 16259 return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height; 16260 } 16261 return 0; 16262 } 16263 function measureLabelSize(ctx, font, label) { 16264 label = isArray(label) ? label : [label]; 16265 return { 16266 w: _longestText(ctx, font.string, label), 16267 h: label.length * font.lineHeight 16268 }; 16269 } 16270 function determineLimits(angle, pos, size, min, max) { 16271 if (angle === min || angle === max) { 16272 return { 16273 start: pos - size / 2, 16274 end: pos + size / 2 16275 }; 16276 } else if (angle < min || angle > max) { 16277 return { 16278 start: pos - size, 16279 end: pos 16280 }; 16281 } 16282 return { 16283 start: pos, 16284 end: pos + size 16285 }; 16286 } 16287 function fitWithPointLabels(scale) { 16288 var orig = { 16289 l: scale.left + scale._padding.left, 16290 r: scale.right - scale._padding.right, 16291 t: scale.top + scale._padding.top, 16292 b: scale.bottom - scale._padding.bottom 16293 }; 16294 var limits = Object.assign({}, orig); 16295 var labelSizes = []; 16296 var padding = []; 16297 var valueCount = scale._pointLabels.length; 16298 var pointLabelOpts = scale.options.pointLabels; 16299 var additionalAngle = pointLabelOpts.centerPointLabels ? PI / valueCount : 0; 16300 for (var i = 0; i < valueCount; i++) { 16301 var opts = pointLabelOpts.setContext(scale.getPointLabelContext(i)); 16302 padding[i] = opts.padding; 16303 var pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle); 16304 var plFont = toFont(opts.font); 16305 var textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]); 16306 labelSizes[i] = textSize; 16307 var angleRadians = _normalizeAngle(scale.getIndexAngle(i) + additionalAngle); 16308 var angle = Math.round(toDegrees(angleRadians)); 16309 var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180); 16310 var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270); 16311 updateLimits(limits, orig, angleRadians, hLimits, vLimits); 16312 } 16313 scale.setCenterPoint(orig.l - limits.l, limits.r - orig.r, orig.t - limits.t, limits.b - orig.b); 16314 scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding); 16315 } 16316 function updateLimits(limits, orig, angle, hLimits, vLimits) { 16317 var sin = Math.abs(Math.sin(angle)); 16318 var cos = Math.abs(Math.cos(angle)); 16319 var x = 0; 16320 var y = 0; 16321 if (hLimits.start < orig.l) { 16322 x = (orig.l - hLimits.start) / sin; 16323 limits.l = Math.min(limits.l, orig.l - x); 16324 } else if (hLimits.end > orig.r) { 16325 x = (hLimits.end - orig.r) / sin; 16326 limits.r = Math.max(limits.r, orig.r + x); 16327 } 16328 if (vLimits.start < orig.t) { 16329 y = (orig.t - vLimits.start) / cos; 16330 limits.t = Math.min(limits.t, orig.t - y); 16331 } else if (vLimits.end > orig.b) { 16332 y = (vLimits.end - orig.b) / cos; 16333 limits.b = Math.max(limits.b, orig.b + y); 16334 } 16335 } 16336 function createPointLabelItem(scale, index, itemOpts) { 16337 var outerDistance = scale.drawingArea; 16338 var extra = itemOpts.extra, 16339 additionalAngle = itemOpts.additionalAngle, 16340 padding = itemOpts.padding, 16341 size = itemOpts.size; 16342 var pointLabelPosition = scale.getPointPosition(index, outerDistance + extra + padding, additionalAngle); 16343 var angle = Math.round(toDegrees(_normalizeAngle(pointLabelPosition.angle + HALF_PI))); 16344 var y = yForAngle(pointLabelPosition.y, size.h, angle); 16345 var textAlign = getTextAlignForAngle(angle); 16346 var left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign); 16347 return { 16348 visible: true, 16349 x: pointLabelPosition.x, 16350 y: y, 16351 textAlign: textAlign, 16352 left: left, 16353 top: y, 16354 right: left + size.w, 16355 bottom: y + size.h 16356 }; 16357 } 16358 function isNotOverlapped(item, area) { 16359 if (!area) { 16360 return true; 16361 } 16362 var left = item.left, 16363 top = item.top, 16364 right = item.right, 16365 bottom = item.bottom; 16366 var apexesInArea = _isPointInArea({ 16367 x: left, 16368 y: top 16369 }, area) || _isPointInArea({ 16370 x: left, 16371 y: bottom 16372 }, area) || _isPointInArea({ 16373 x: right, 16374 y: top 16375 }, area) || _isPointInArea({ 16376 x: right, 16377 y: bottom 16378 }, area); 16379 return !apexesInArea; 16380 } 16381 function buildPointLabelItems(scale, labelSizes, padding) { 16382 var items = []; 16383 var valueCount = scale._pointLabels.length; 16384 var opts = scale.options; 16385 var _opts$pointLabels = opts.pointLabels, 16386 centerPointLabels = _opts$pointLabels.centerPointLabels, 16387 display = _opts$pointLabels.display; 16388 var itemOpts = { 16389 extra: getTickBackdropHeight(opts) / 2, 16390 additionalAngle: centerPointLabels ? PI / valueCount : 0 16391 }; 16392 var area; 16393 for (var i = 0; i < valueCount; i++) { 16394 itemOpts.padding = padding[i]; 16395 itemOpts.size = labelSizes[i]; 16396 var item = createPointLabelItem(scale, i, itemOpts); 16397 items.push(item); 16398 if (display === 'auto') { 16399 item.visible = isNotOverlapped(item, area); 16400 if (item.visible) { 16401 area = item; 16402 } 16403 } 16404 } 16405 return items; 16406 } 16407 function getTextAlignForAngle(angle) { 16408 if (angle === 0 || angle === 180) { 16409 return 'center'; 16410 } else if (angle < 180) { 16411 return 'left'; 16412 } 16413 return 'right'; 16414 } 16415 function leftForTextAlign(x, w, align) { 16416 if (align === 'right') { 16417 x -= w; 16418 } else if (align === 'center') { 16419 x -= w / 2; 16420 } 16421 return x; 16422 } 16423 function yForAngle(y, h, angle) { 16424 if (angle === 90 || angle === 270) { 16425 y -= h / 2; 16426 } else if (angle > 270 || angle < 90) { 16427 y -= h; 16428 } 16429 return y; 16430 } 16431 function drawPointLabelBox(ctx, opts, item) { 16432 var left = item.left, 16433 top = item.top, 16434 right = item.right, 16435 bottom = item.bottom; 16436 var backdropColor = opts.backdropColor; 16437 if (!isNullOrUndef(backdropColor)) { 16438 var borderRadius = toTRBLCorners(opts.borderRadius); 16439 var padding = toPadding(opts.backdropPadding); 16440 ctx.fillStyle = backdropColor; 16441 var backdropLeft = left - padding.left; 16442 var backdropTop = top - padding.top; 16443 var backdropWidth = right - left + padding.width; 16444 var backdropHeight = bottom - top + padding.height; 16445 if (Object.values(borderRadius).some(function (v) { 16446 return v !== 0; 16447 })) { 16448 ctx.beginPath(); 16449 addRoundedRectPath(ctx, { 16450 x: backdropLeft, 16451 y: backdropTop, 16452 w: backdropWidth, 16453 h: backdropHeight, 16454 radius: borderRadius 16455 }); 16456 ctx.fill(); 16457 } else { 16458 ctx.fillRect(backdropLeft, backdropTop, backdropWidth, backdropHeight); 16459 } 16460 } 16461 } 16462 function drawPointLabels(scale, labelCount) { 16463 var ctx = scale.ctx, 16464 pointLabels = scale.options.pointLabels; 16465 for (var i = labelCount - 1; i >= 0; i--) { 16466 var item = scale._pointLabelItems[i]; 16467 if (!item.visible) { 16468 continue; 16469 } 16470 var optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i)); 16471 drawPointLabelBox(ctx, optsAtIndex, item); 16472 var plFont = toFont(optsAtIndex.font); 16473 var x = item.x, 16474 y = item.y, 16475 textAlign = item.textAlign; 16476 renderText(ctx, scale._pointLabels[i], x, y + plFont.lineHeight / 2, plFont, { 16477 color: optsAtIndex.color, 16478 textAlign: textAlign, 16479 textBaseline: 'middle' 16480 }); 16481 } 16482 } 16483 function pathRadiusLine(scale, radius, circular, labelCount) { 16484 var ctx = scale.ctx; 16485 if (circular) { 16486 ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU); 16487 } else { 16488 var pointPosition = scale.getPointPosition(0, radius); 16489 ctx.moveTo(pointPosition.x, pointPosition.y); 16490 for (var i = 1; i < labelCount; i++) { 16491 pointPosition = scale.getPointPosition(i, radius); 16492 ctx.lineTo(pointPosition.x, pointPosition.y); 16493 } 16494 } 16495 } 16496 function drawRadiusLine(scale, gridLineOpts, radius, labelCount, borderOpts) { 16497 var ctx = scale.ctx; 16498 var circular = gridLineOpts.circular; 16499 var color = gridLineOpts.color, 16500 lineWidth = gridLineOpts.lineWidth; 16501 if (!circular && !labelCount || !color || !lineWidth || radius < 0) { 16502 return; 16503 } 16504 ctx.save(); 16505 ctx.strokeStyle = color; 16506 ctx.lineWidth = lineWidth; 16507 ctx.setLineDash(borderOpts.dash || []); 16508 ctx.lineDashOffset = borderOpts.dashOffset; 16509 ctx.beginPath(); 16510 pathRadiusLine(scale, radius, circular, labelCount); 16511 ctx.closePath(); 16512 ctx.stroke();
16513 ctx.restore(); 16514 } 16515 function createPointLabelContext(parent, index, label) { 16516 return createContext(parent, { 16517 label: label, 16518 index: index, 16519 type: 'pointLabel' 16520 }); 16521 } 16522 var RadialLinearScale = /*#__PURE__*/function (_LinearScaleBase2) { 16523 function RadialLinearScale(cfg) { 16524 var _this37; 16525 _classCallCheck$1(this, RadialLinearScale); 16526 _this37 = _callSuper(this, RadialLinearScale, [cfg]); 16527 _this37.xCenter = undefined; 16528 _this37.yCenter = undefined; 16529 _this37.drawingArea = undefined; 16530 _this37._pointLabels = []; 16531 _this37._pointLabelItems = []; 16532 return _this37; 16533 } 16534 _inherits$1(RadialLinearScale, _LinearScaleBase2); 16535 return _createClass$1(RadialLinearScale, [{ 16536 key: "setDimensions", 16537 value: function setDimensions() { 16538 var padding = this._padding = toPadding(getTickBackdropHeight(this.options) / 2); 16539 var w = this.width = this.maxWidth - padding.width; 16540 var h = this.height = this.maxHeight - padding.height; 16541 this.xCenter = Math.floor(this.left + w / 2 + padding.left); 16542 this.yCenter = Math.floor(this.top + h / 2 + padding.top); 16543 this.drawingArea = Math.floor(Math.min(w, h) / 2); 16544 } 16545 }, { 16546 key: "determineDataLimits", 16547 value: function determineDataLimits() { 16548 var _this$getMinMax4 = this.getMinMax(false), 16549 min = _this$getMinMax4.min, 16550 max = _this$getMinMax4.max; 16551 this.min = isNumberFinite(min) && !isNaN(min) ? min : 0; 16552 this.max = isNumberFinite(max) && !isNaN(max) ? max : 0; 16553 this.handleTickRangeOptions(); 16554 } 16555 }, { 16556 key: "computeTickLimit", 16557 value: function computeTickLimit() { 16558 return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options)); 16559 } 16560 }, { 16561 key: "generateTickLabels", 16562 value: function generateTickLabels(ticks) { 16563 var _this38 = this; 16564 LinearScaleBase.prototype.generateTickLabels.call(this, ticks); 16565 this._pointLabels = this.getLabels().map(function (value, index) { 16566 var label = callback(_this38.options.pointLabels.callback, [value, index], _this38); 16567 return label || label === 0 ? label : ''; 16568 }).filter(function (v, i) { 16569 return _this38.chart.getDataVisibility(i); 16570 }); 16571 } 16572 }, { 16573 key: "fit", 16574 value: function fit() { 16575 var opts = this.options; 16576 if (opts.display && opts.pointLabels.display) { 16577 fitWithPointLabels(this); 16578 } else { 16579 this.setCenterPoint(0, 0, 0, 0); 16580 } 16581 } 16582 }, { 16583 key: "setCenterPoint", 16584 value: function setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) { 16585 this.xCenter += Math.floor((leftMovement - rightMovement) / 2); 16586 this.yCenter += Math.floor((topMovement - bottomMovement) / 2); 16587 this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement)); 16588 } 16589 }, { 16590 key: "getIndexAngle", 16591 value: function getIndexAngle(index) { 16592 var angleMultiplier = TAU / (this._pointLabels.length || 1); 16593 var startAngle = this.options.startAngle || 0; 16594 return _normalizeAngle(index * angleMultiplier + toRadians(startAngle)); 16595 } 16596 }, { 16597 key: "getDistanceFromCenterForValue", 16598 value: function getDistanceFromCenterForValue(value) { 16599 if (isNullOrUndef(value)) { 16600 return NaN; 16601 } 16602 var scalingFactor = this.drawingArea / (this.max - this.min); 16603 if (this.options.reverse) { 16604 return (this.max - value) * scalingFactor; 16605 } 16606 return (value - this.min) * scalingFactor; 16607 } 16608 }, { 16609 key: "getValueForDistanceFromCenter", 16610 value: function getValueForDistanceFromCenter(distance) { 16611 if (isNullOrUndef(distance)) { 16612 return NaN; 16613 } 16614 var scaledDistance = distance / (this.drawingArea / (this.max - this.min)); 16615 return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance; 16616 } 16617 }, { 16618 key: "getPointLabelContext", 16619 value: function getPointLabelContext(index) { 16620 var pointLabels = this._pointLabels || []; 16621 if (index >= 0 && index < pointLabels.length) { 16622 var pointLabel = pointLabels[index]; 16623 return createPointLabelContext(this.getContext(), index, pointLabel); 16624 } 16625 } 16626 }, {
16627 key: "getPointPosition", 16628 value: function getPointPosition(index, distanceFromCenter) { 16629 var additionalAngle = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; 16630 var angle = this.getIndexAngle(index) - HALF_PI + additionalAngle; 16631 return { 16632 x: Math.cos(angle) * distanceFromCenter + this.xCenter, 16633 y: Math.sin(angle) * distanceFromCenter + this.yCenter, 16634 angle: angle 16635 }; 16636 } 16637 }, { 16638 key: "getPointPositionForValue", 16639 value: function getPointPositionForValue(index, value) { 16640 return this.getPointPosition(index, this.getDistanceFromCenterForValue(value)); 16641 } 16642 }, { 16643 key: "getBasePosition", 16644 value: function getBasePosition(index) { 16645 return this.getPointPositionForValue(index || 0, this.getBaseValue()); 16646 } 16647 }, { 16648 key: "getPointLabelPosition", 16649 value: function getPointLabelPosition(index) { 16650 var _this$_pointLabelItem = this._pointLabelItems[index], 16651 left = _this$_pointLabelItem.left, 16652 top = _this$_pointLabelItem.top, 16653 right = _this$_pointLabelItem.right, 16654 bottom = _this$_pointLabelItem.bottom; 16655 return { 16656 left: left, 16657 top: top, 16658 right: right, 16659 bottom: bottom 16660 }; 16661 } 16662 }, { 16663 key: "drawBackground", 16664 value: function drawBackground() { 16665 var _this$options14 = this.options, 16666 backgroundColor = _this$options14.backgroundColor, 16667 circular = _this$options14.grid.circular; 16668 if (backgroundColor) { 16669 var ctx = this.ctx; 16670 ctx.save(); 16671 ctx.beginPath(); 16672 pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length); 16673 ctx.closePath(); 16674 ctx.fillStyle = backgroundColor; 16675 ctx.fill(); 16676 ctx.restore(); 16677 } 16678 } 16679 }, { 16680 key: "drawGrid", 16681 value: function drawGrid() { 16682 var _this39 = this; 16683 var ctx = this.ctx; 16684 var opts = this.options; 16685 var angleLines = opts.angleLines, 16686 grid = opts.grid, 16687 border = opts.border; 16688 var labelCount = this._pointLabels.length; 16689 var i, offset, position; 16690 if (opts.pointLabels.display) { 16691 drawPointLabels(this, labelCount); 16692 } 16693 if (grid.display) { 16694 this.ticks.forEach(function (tick, index) { 16695 if (index !== 0 || index === 0 && _this39.min < 0) { 16696 offset = _this39.getDistanceFromCenterForValue(tick.value); 16697 var context = _this39.getContext(index); 16698 var optsAtIndex = grid.setContext(context); 16699 var optsAtIndexBorder = border.setContext(context); 16700 drawRadiusLine(_this39, optsAtIndex, offset, labelCount, optsAtIndexBorder); 16701 } 16702 }); 16703 } 16704 if (angleLines.display) { 16705 ctx.save(); 16706 for (i = labelCount - 1; i >= 0; i--) { 16707 var optsAtIndex = angleLines.setContext(this.getPointLabelContext(i)); 16708 var color = optsAtIndex.color, 16709 lineWidth = optsAtIndex.lineWidth; 16710 if (!lineWidth || !color) { 16711 continue; 16712 } 16713 ctx.lineWidth = lineWidth; 16714 ctx.strokeStyle = color; 16715 ctx.setLineDash(optsAtIndex.borderDash); 16716 ctx.lineDashOffset = optsAtIndex.borderDashOffset; 16717 offset = this.getDistanceFromCenterForValue(opts.reverse ? this.min : this.max); 16718 position = this.getPointPosition(i, offset); 16719 ctx.beginPath(); 16720 ctx.moveTo(this.xCenter, this.yCenter); 16721 ctx.lineTo(position.x, position.y); 16722 ctx.stroke(); 16723 } 16724 ctx.restore(); 16725 } 16726 } 16727 }, { 16728 key: "drawBorder", 16729 value: function drawBorder() {} 16730 }, { 16731 key: "drawLabels", 16732 value: function drawLabels() { 16733 var _this40 = this; 16734 var ctx = this.ctx; 16735 var opts = this.options; 16736 var tickOpts = opts.ticks; 16737 if (!tickOpts.display) { 16738 return; 16739 } 16740 var startAngle = this.getIndexAngle(0); 16741 var offset, width; 16742 ctx.save(); 16743 ctx.translate(this.xCenter, this.yCenter); 16744 ctx.rotate(startAngle); 16745 ctx.textAlign = 'center'; 16746 ctx.textBaseline = 'middle'; 16747 this.ticks.forEach(function (tick, index) { 16748 if (index === 0 && _this40.min >= 0 && !opts.reverse) { 16749 return; 16750 } 16751 var optsAtIndex = tickOpts.setContext(_this40.getContext(index));
16752 var tickFont = toFont(optsAtIndex.font); 16753 offset = _this40.getDistanceFromCenterForValue(_this40.ticks[index].value); 16754 if (optsAtIndex.showLabelBackdrop) { 16755 ctx.font = tickFont.string; 16756 width = ctx.measureText(tick.label).width; 16757 ctx.fillStyle = optsAtIndex.backdropColor; 16758 var padding = toPadding(optsAtIndex.backdropPadding); 16759 ctx.fillRect(-width / 2 - padding.left, -offset - tickFont.size / 2 - padding.top, width + padding.width, tickFont.size + padding.height); 16760 } 16761 renderText(ctx, tick.label, 0, -offset, tickFont, { 16762 color: optsAtIndex.color, 16763 strokeColor: optsAtIndex.textStrokeColor, 16764 strokeWidth: optsAtIndex.textStrokeWidth 16765 }); 16766 }); 16767 ctx.restore(); 16768 } 16769 }, { 16770 key: "drawTitle", 16771 value: function drawTitle() {} 16772 }]); 16773 }(LinearScaleBase); 16774 _defineProperty$1(RadialLinearScale, "id", 'radialLinear'); 16775 _defineProperty$1(RadialLinearScale, "defaults", { 16776 display: true, 16777 animate: true, 16778 position: 'chartArea', 16779 angleLines: { 16780 display: true, 16781 lineWidth: 1, 16782 borderDash: [], 16783 borderDashOffset: 0.0 16784 }, 16785 grid: { 16786 circular: false 16787 }, 16788 startAngle: 0, 16789 ticks: { 16790 showLabelBackdrop: true, 16791 callback: Ticks.formatters.numeric 16792 }, 16793 pointLabels: { 16794 backdropColor: undefined, 16795 backdropPadding: 2, 16796 display: true, 16797 font: { 16798 size: 10 16799 }, 16800 callback: function callback(label) { 16801 return label; 16802 }, 16803 padding: 5, 16804 centerPointLabels: false 16805 } 16806 }); 16807 _defineProperty$1(RadialLinearScale, "defaultRoutes", { 16808 'angleLines.color': 'borderColor', 16809 'pointLabels.color': 'color', 16810 'ticks.color': 'color' 16811 }); 16812 _defineProperty$1(RadialLinearScale, "descriptors", { 16813 angleLines: { 16814 _fallback: 'grid' 16815 } 16816 }); 16817 var INTERVALS = { 16818 millisecond: { 16819 common: true, 16820 size: 1, 16821 steps: 1000 16822 }, 16823 second: { 16824 common: true, 16825 size: 1000, 16826 steps: 60 16827 }, 16828 minute: { 16829 common: true, 16830 size: 60000, 16831 steps: 60 16832 }, 16833 hour: { 16834 common: true, 16835 size: 3600000, 16836 steps: 24 16837 }, 16838 day: { 16839 common: true, 16840 size: 86400000, 16841 steps: 30 16842 }, 16843 week: { 16844 common: false, 16845 size: 604800000, 16846 steps: 4 16847 }, 16848 month: { 16849 common: true, 16850 size: 2.628e9, 16851 steps: 12 16852 }, 16853 quarter: { 16854 common: false, 16855 size: 7.884e9, 16856 steps: 4 16857 }, 16858 year: { 16859 common: true, 16860 size: 3.154e10 16861 } 16862 }; 16863 var UNITS = /* #__PURE__ */Object.keys(INTERVALS); 16864 function sorter(a, b) { 16865 return a - b; 16866 } 16867 function _parse(scale, input) { 16868 if (isNullOrUndef(input)) { 16869 return null; 16870 } 16871 var adapter = scale._adapter; 16872 var _scale$_parseOpts = scale._parseOpts, 16873 parser = _scale$_parseOpts.parser, 16874 round = _scale$_parseOpts.round, 16875 isoWeekday = _scale$_parseOpts.isoWeekday; 16876 var value = input; 16877 if (typeof parser === 'function') { 16878 value = parser(value); 16879 } 16880 if (!isNumberFinite(value)) { 16881 value = typeof parser === 'string' ? adapter.parse(value, parser) : adapter.parse(value); 16882 } 16883 if (value === null) { 16884 return null; 16885 } 16886 if (round) { 16887 value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true) ? adapter.startOf(value, 'isoWeek', isoWeekday) : adapter.startOf(value, round); 16888 } 16889 return +value; 16890 } 16891 function determineUnitForAutoTicks(minUnit, min, max, capacity) { 16892 var ilen = UNITS.length; 16893 for (var i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) { 16894 var interval = INTERVALS[UNITS[i]]; 16895 var factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER; 16896 if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) { 16897 return UNITS[i]; 16898 } 16899 } 16900 return UNITS[ilen - 1]; 16901 } 16902 function determineUnitForFormatting(scale, numTicks, minUnit, min, max) { 16903 for (var i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) { 16904 var unit = UNITS[i]; 16905 if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) { 16906 return unit; 16907 } 16908 } 16909 return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0]; 16910 } 16911 function determineMajorUnit(unit) { 16912 for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) { 16913 if (INTERVALS[UNITS[i]].common) { 16914 return UNITS[i]; 16915 } 16916 } 16917 } 16918 function addTick(ticks, time, timestamps) { 16919 if (!timestamps) { 16920 ticks[time] = true; 16921 } else if (timestamps.length) { 16922 var _lookup2 = _lookup(timestamps, time), 16923 lo = _lookup2.lo, 16924 hi = _lookup2.hi; 16925 var timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi]; 16926 ticks[timestamp] = true; 16927 } 16928 } 16929 function setMajorTicks(scale, ticks, map, majorUnit) { 16930 var adapter = scale._adapter; 16931 var first = +adapter.startOf(ticks[0].value, majorUnit); 16932 var last = ticks[ticks.length - 1].value; 16933 var major, index; 16934 for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) { 16935 index = map[major]; 16936 if (index >= 0) { 16937 ticks[index].major = true; 16938 } 16939 } 16940 return ticks; 16941 } 16942 function ticksFromTimestamps(scale, values, majorUnit) { 16943 var ticks = []; 16944 var map = {}; 16945 var ilen = values.length; 16946 var i, value; 16947 for (i = 0; i < ilen; ++i) { 16948 value = values[i]; 16949 map[value] = i; 16950 ticks.push({ 16951 value: value, 16952 major: false 16953 }); 16954 } 16955 return ilen === 0 || !majorUnit ? ticks : setMajorTicks(scale, ticks, map, majorUnit); 16956 }
16957 var TimeScale = /*#__PURE__*/function (_Scale4) { 16958 function TimeScale(props) { 16959 var _this41; 16960 _classCallCheck$1(this, TimeScale); 16961 _this41 = _callSuper(this, TimeScale, [props]); 16962 _this41._cache = { 16963 data: [], 16964 labels: [], 16965 all: [] 16966 }; 16967 _this41._unit = 'day'; 16968 _this41._majorUnit = undefined; 16969 _this41._offsets = {}; 16970 _this41._normalized = false; 16971 _this41._parseOpts = undefined; 16972 return _this41; 16973 } 16974 _inherits$1(TimeScale, _Scale4); 16975 return _createClass$1(TimeScale, [{ 16976 key: "init", 16977 value: function init(scaleOpts) { 16978 var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 16979 var time = scaleOpts.time || (scaleOpts.time = {}); 16980 var adapter = this._adapter = new adapters._date(scaleOpts.adapters.date); 16981 adapter.init(opts); 16982 mergeIf(time.displayFormats, adapter.formats()); 16983 this._parseOpts = { 16984 parser: time.parser, 16985 round: time.round, 16986 isoWeekday: time.isoWeekday 16987 }; 16988 _superPropGet(TimeScale, "init", this, 3)([scaleOpts]); 16989 this._normalized = opts.normalized; 16990 } 16991 }, { 16992 key: "parse", 16993 value: function parse(raw, index) { 16994 if (raw === undefined) { 16995 return null; 16996 } 16997 return _parse(this, raw); 16998 } 16999 }, { 17000 key: "beforeLayout", 17001 value: function beforeLayout() { 17002 _superPropGet(TimeScale, "beforeLayout", this, 3)([]); 17003 this._cache = { 17004 data: [], 17005 labels: [], 17006 all: [] 17007 }; 17008 } 17009 }, { 17010 key: "determineDataLimits", 17011 value: function determineDataLimits() { 17012 var options = this.options; 17013 var adapter = this._adapter; 17014 var unit = options.time.unit || 'day'; 17015 var _this$getUserBounds5 = this.getUserBounds(), 17016 min = _this$getUserBounds5.min, 17017 max = _this$getUserBounds5.max, 17018 minDefined = _this$getUserBounds5.minDefined, 17019 maxDefined = _this$getUserBounds5.maxDefined; 17020 function _applyBounds(bounds) { 17021 if (!minDefined && !isNaN(bounds.min)) { 17022 min = Math.min(min, bounds.min); 17023 } 17024 if (!maxDefined && !isNaN(bounds.max)) { 17025 max = Math.max(max, bounds.max); 17026 } 17027 } 17028 if (!minDefined || !maxDefined) { 17029 _applyBounds(this._getLabelBounds()); 17030 if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') { 17031 _applyBounds(this.getMinMax(false)); 17032 } 17033 } 17034 min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit); 17035 max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1; 17036 this.min = Math.min(min, max - 1); 17037 this.max = Math.max(min + 1, max); 17038 } 17039 }, { 17040 key: "_getLabelBounds", 17041 value: function _getLabelBounds() { 17042 var arr = this.getLabelTimestamps(); 17043 var min = Number.POSITIVE_INFINITY; 17044 var max = Number.NEGATIVE_INFINITY; 17045 if (arr.length) { 17046 min = arr[0]; 17047 max = arr[arr.length - 1]; 17048 } 17049 return { 17050 min: min, 17051 max: max 17052 }; 17053 } 17054 }, { 17055 key: "buildTicks", 17056 value: function buildTicks() { 17057 var options = this.options; 17058 var timeOpts = options.time; 17059 var tickOpts = options.ticks; 17060 var timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate(); 17061 if (options.bounds === 'ticks' && timestamps.length) { 17062 this.min = this._userMin || timestamps[0]; 17063 this.max = this._userMax || timestamps[timestamps.length - 1]; 17064 } 17065 var min = this.min; 17066 var max = this.max; 17067 var ticks = _filterBetween(timestamps, min, max); 17068 this._unit = timeOpts.unit || (tickOpts.autoSkip ? determineUnitForAutoTicks(timeOpts.minUnit, this.min, this.max, this._getLabelCapacity(min)) : determineUnitForFormatting(this, ticks.length, timeOpts.minUnit, this.min, this.max)); 17069 this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined : determineMajorUnit(this._unit); 17070 this.initOffsets(timestamps); 17071 if (options.reverse) { 17072 ticks.reverse(); 17073 } 17074 return ticksFromTimestamps(this, ticks, this._majorUnit); 17075 } 17076 }, {
17077 key: "afterAutoSkip", 17078 value: function afterAutoSkip() { 17079 if (this.options.offsetAfterAutoskip) { 17080 this.initOffsets(this.ticks.map(function (tick) { 17081 return +tick.value; 17082 })); 17083 } 17084 } 17085 }, { 17086 key: "initOffsets", 17087 value: function initOffsets() { 17088 var timestamps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 17089 var start = 0; 17090 var end = 0; 17091 var first, last; 17092 if (this.options.offset && timestamps.length) { 17093 first = this.getDecimalForValue(timestamps[0]); 17094 if (timestamps.length === 1) { 17095 start = 1 - first; 17096 } else { 17097 start = (this.getDecimalForValue(timestamps[1]) - first) / 2; 17098 } 17099 last = this.getDecimalForValue(timestamps[timestamps.length - 1]); 17100 if (timestamps.length === 1) { 17101 end = last; 17102 } else { 17103 end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2; 17104 } 17105 } 17106 var limit = timestamps.length < 3 ? 0.5 : 0.25; 17107 start = _limitValue(start, 0, limit); 17108 end = _limitValue(end, 0, limit); 17109 this._offsets = { 17110 start: start, 17111 end: end, 17112 factor: 1 / (start + 1 + end) 17113 }; 17114 } 17115 }, { 17116 key: "_generate", 17117 value: function _generate() { 17118 var adapter = this._adapter; 17119 var min = this.min; 17120 var max = this.max; 17121 var options = this.options; 17122 var timeOpts = options.time; 17123 var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min)); 17124 var stepSize = valueOrDefault(options.ticks.stepSize, 1); 17125 var weekday = minor === 'week' ? timeOpts.isoWeekday : false; 17126 var hasWeekday = isNumber(weekday) || weekday === true; 17127 var ticks = {}; 17128 var first = min; 17129 var time, count; 17130 if (hasWeekday) { 17131 first = +adapter.startOf(first, 'isoWeek', weekday); 17132 } 17133 first = +adapter.startOf(first, hasWeekday ? 'day' : minor); 17134 if (adapter.diff(max, min, minor) > 100000 * stepSize) { 17135 throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor); 17136 } 17137 var timestamps = options.ticks.source === 'data' && this.getDataTimestamps(); 17138 for (time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++) { 17139 addTick(ticks, time, timestamps); 17140 } 17141 if (time === max || options.bounds === 'ticks' || count === 1) { 17142 addTick(ticks, time, timestamps); 17143 } 17144 return Object.keys(ticks).sort(sorter).map(function (x) { 17145 return +x; 17146 }); 17147 } 17148 }, { 17149 key: "getLabelForValue", 17150 value: function getLabelForValue(value) { 17151 var adapter = this._adapter; 17152 var timeOpts = this.options.time; 17153 if (timeOpts.tooltipFormat) { 17154 return adapter.format(value, timeOpts.tooltipFormat); 17155 } 17156 return adapter.format(value, timeOpts.displayFormats.datetime); 17157 } 17158 }, { 17159 key: "format", 17160 value: function format(value, _format) { 17161 var options = this.options; 17162 var formats = options.time.displayFormats; 17163 var unit = this._unit; 17164 var fmt = _format || formats[unit]; 17165 return this._adapter.format(value, fmt); 17166 } 17167 }, { 17168 key: "_tickFormatFunction", 17169 value: function _tickFormatFunction(time, index, ticks, format) { 17170 var options = this.options; 17171 var formatter = options.ticks.callback; 17172 if (formatter) { 17173 return callback(formatter, [time, index, ticks], this); 17174 } 17175 var formats = options.time.displayFormats; 17176 var unit = this._unit; 17177 var majorUnit = this._majorUnit; 17178 var minorFormat = unit && formats[unit]; 17179 var majorFormat = majorUnit && formats[majorUnit]; 17180 var tick = ticks[index]; 17181 var major = majorUnit && majorFormat && tick && tick.major; 17182 return this._adapter.format(time, format || (major ? majorFormat : minorFormat)); 17183 } 17184 }, {
17185 key: "generateTickLabels", 17186 value: function generateTickLabels(ticks) { 17187 var i, ilen, tick; 17188 for (i = 0, ilen = ticks.length; i < ilen; ++i) { 17189 tick = ticks[i]; 17190 tick.label = this._tickFormatFunction(tick.value, i, ticks); 17191 } 17192 } 17193 }, { 17194 key: "getDecimalForValue", 17195 value: function getDecimalForValue(value) { 17196 return value === null ? NaN : (value - this.min) / (this.max - this.min); 17197 } 17198 }, { 17199 key: "getPixelForValue", 17200 value: function getPixelForValue(value) { 17201 var offsets = this._offsets; 17202 var pos = this.getDecimalForValue(value); 17203 return this.getPixelForDecimal((offsets.start + pos) * offsets.factor); 17204 } 17205 }, { 17206 key: "getValueForPixel", 17207 value: function getValueForPixel(pixel) { 17208 var offsets = this._offsets; 17209 var pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end; 17210 return this.min + pos * (this.max - this.min); 17211 } 17212 }, { 17213 key: "_getLabelSize", 17214 value: function _getLabelSize(label) { 17215 var ticksOpts = this.options.ticks; 17216 var tickLabelWidth = this.ctx.measureText(label).width; 17217 var angle = toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation); 17218 var cosRotation = Math.cos(angle); 17219 var sinRotation = Math.sin(angle); 17220 var tickFontSize = this._resolveTickFontOptions(0).size; 17221 return { 17222 w: tickLabelWidth * cosRotation + tickFontSize * sinRotation, 17223 h: tickLabelWidth * sinRotation + tickFontSize * cosRotation 17224 }; 17225 } 17226 }, { 17227 key: "_getLabelCapacity", 17228 value: function _getLabelCapacity(exampleTime) { 17229 var timeOpts = this.options.time; 17230 var displayFormats = timeOpts.displayFormats; 17231 var format = displayFormats[timeOpts.unit] || displayFormats.millisecond; 17232 var exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [exampleTime], this._majorUnit), format); 17233 var size = this._getLabelSize(exampleLabel); 17234 var capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1; 17235 return capacity > 0 ? capacity : 1; 17236 } 17237 }, { 17238 key: "getDataTimestamps", 17239 value: function getDataTimestamps() { 17240 var timestamps = this._cache.data || []; 17241 var i, ilen; 17242 if (timestamps.length) { 17243 return timestamps; 17244 } 17245 var metas = this.getMatchingVisibleMetas(); 17246 if (this._normalized && metas.length) { 17247 return this._cache.data = metas[0].controller.getAllParsedValues(this); 17248 } 17249 for (i = 0, ilen = metas.length; i < ilen; ++i) { 17250 timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this)); 17251 } 17252 return this._cache.data = this.normalize(timestamps); 17253 } 17254 }, { 17255 key: "getLabelTimestamps", 17256 value: function getLabelTimestamps() { 17257 var timestamps = this._cache.labels || []; 17258 var i, ilen; 17259 if (timestamps.length) { 17260 return timestamps; 17261 } 17262 var labels = this.getLabels(); 17263 for (i = 0, ilen = labels.length; i < ilen; ++i) { 17264 timestamps.push(_parse(this, labels[i])); 17265 } 17266 return this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps); 17267 } 17268 }, { 17269 key: "normalize", 17270 value: function normalize(values) { 17271 return _arrayUnique(values.sort(sorter)); 17272 } 17273 }]); 17274 }(Scale); 17275 _defineProperty$1(TimeScale, "id", 'time'); 17276 _defineProperty$1(TimeScale, "defaults", { 17277 bounds: 'data', 17278 adapters: {}, 17279 time: { 17280 parser: false, 17281 unit: false, 17282 round: false, 17283 isoWeekday: false, 17284 minUnit: 'millisecond', 17285 displayFormats: {} 17286 }, 17287 ticks: { 17288 source: 'auto', 17289 callback: false, 17290 major: { 17291 enabled: false 17292 } 17293 } 17294 }); 17295 function interpolate(table, val, reverse) { 17296 var lo = 0; 17297 var hi = table.length - 1; 17298 var prevSource, nextSource, prevTarget, nextTarget; 17299 if (reverse) { 17300 if (val >= table[lo].pos && val <= table[hi].pos) { 17301 var _lookupByKey2 = _lookupByKey(table, 'pos', val); 17302 lo = _lookupByKey2.lo; 17303 hi = _lookupByKey2.hi; 17304 } 17305 var _table$lo = table[lo]; 17306 prevSource = _table$lo.pos; 17307 prevTarget = _table$lo.time; 17308 var _table$hi = table[hi]; 17309 nextSource = _table$hi.pos; 17310 nextTarget = _table$hi.time; 17311 } else { 17312 if (val >= table[lo].time && val <= table[hi].time) { 17313 var _lookupByKey3 = _lookupByKey(table, 'time', val); 17314 lo = _lookupByKey3.lo; 17315 hi = _lookupByKey3.hi; 17316 } 17317 var _table$lo2 = table[lo];
17318 prevSource = _table$lo2.time; 17319 prevTarget = _table$lo2.pos; 17320 var _table$hi2 = table[hi]; 17321 nextSource = _table$hi2.time; 17322 nextTarget = _table$hi2.pos; 17323 } 17324 var span = nextSource - prevSource; 17325 return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget; 17326 } 17327 var TimeSeriesScale = /*#__PURE__*/function (_TimeScale2) { 17328 function TimeSeriesScale(props) { 17329 var _this42; 17330 _classCallCheck$1(this, TimeSeriesScale); 17331 _this42 = _callSuper(this, TimeSeriesScale, [props]); 17332 _this42._table = []; 17333 _this42._minPos = undefined; 17334 _this42._tableRange = undefined; 17335 return _this42; 17336 } 17337 _inherits$1(TimeSeriesScale, _TimeScale2); 17338 return _createClass$1(TimeSeriesScale, [{ 17339 key: "initOffsets", 17340 value: function initOffsets() { 17341 var timestamps = this._getTimestampsForTable(); 17342 var table = this._table = this.buildLookupTable(timestamps); 17343 this._minPos = interpolate(table, this.min); 17344 this._tableRange = interpolate(table, this.max) - this._minPos; 17345 _superPropGet(TimeSeriesScale, "initOffsets", this, 3)([timestamps]); 17346 } 17347 }, { 17348 key: "buildLookupTable", 17349 value: function buildLookupTable(timestamps) { 17350 var min = this.min, 17351 max = this.max; 17352 var items = []; 17353 var table = []; 17354 var i, ilen, prev, curr, next; 17355 for (i = 0, ilen = timestamps.length; i < ilen; ++i) { 17356 curr = timestamps[i]; 17357 if (curr >= min && curr <= max) { 17358 items.push(curr); 17359 } 17360 } 17361 if (items.length < 2) { 17362 return [{ 17363 time: min, 17364 pos: 0 17365 }, { 17366 time: max, 17367 pos: 1 17368 }]; 17369 } 17370 for (i = 0, ilen = items.length; i < ilen; ++i) { 17371 next = items[i + 1]; 17372 prev = items[i - 1]; 17373 curr = items[i]; 17374 if (Math.round((next + prev) / 2) !== curr) { 17375 table.push({ 17376 time: curr, 17377 pos: i / (ilen - 1) 17378 }); 17379 } 17380 } 17381 return table; 17382 } 17383 }, { 17384 key: "_generate", 17385 value: function _generate() { 17386 var min = this.min; 17387 var max = this.max; 17388 var timestamps = _superPropGet(TimeSeriesScale, "getDataTimestamps", this, 3)([]); 17389 if (!timestamps.includes(min) || !timestamps.length) { 17390 timestamps.splice(0, 0, min); 17391 } 17392 if (!timestamps.includes(max) || timestamps.length === 1) { 17393 timestamps.push(max); 17394 } 17395 return timestamps.sort(function (a, b) { 17396 return a - b; 17397 }); 17398 } 17399 }, { 17400 key: "_getTimestampsForTable", 17401 value: function _getTimestampsForTable() { 17402 var timestamps = this._cache.all || []; 17403 if (timestamps.length) { 17404 return timestamps; 17405 } 17406 var data = this.getDataTimestamps(); 17407 var label = this.getLabelTimestamps(); 17408 if (data.length && label.length) { 17409 timestamps = this.normalize(data.concat(label)); 17410 } else { 17411 timestamps = data.length ? data : label; 17412 } 17413 timestamps = this._cache.all = timestamps; 17414 return timestamps; 17415 } 17416 }, { 17417 key: "getDecimalForValue", 17418 value: function getDecimalForValue(value) { 17419 return (interpolate(this._table, value) - this._minPos) / this._tableRange; 17420 } 17421 }, { 17422 key: "getValueForPixel", 17423 value: function getValueForPixel(pixel) { 17424 var offsets = this._offsets; 17425 var decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end; 17426 return interpolate(this._table, decimal * this._tableRange + this._minPos, true); 17427 } 17428 }]); 17429 }(TimeScale); 17430 _defineProperty$1(TimeSeriesScale, "id", 'timeseries'); 17431 _defineProperty$1(TimeSeriesScale, "defaults", TimeScale.defaults); 17432 var scales = /*#__PURE__*/Object.freeze({ 17433 __proto__: null, 17434 CategoryScale: CategoryScale, 17435 LinearScale: LinearScale, 17436 LogarithmicScale: LogarithmicScale, 17437 RadialLinearScale: RadialLinearScale, 17438 TimeScale: TimeScale, 17439 TimeSeriesScale: TimeSeriesScale 17440 }); 17441 var registerables = [controllers, elements, plugins, scales]; 17442 17443 Chart.register.apply(Chart, _toConsumableArray(registerables)); 17444 17445 var helpers = /*#__PURE__*/Object.freeze({ 17446 __proto__: null, 17447 HALF_PI: HALF_PI, 17448 INFINITY: INFINITY, 17449 PI: PI, 17450 PITAU: PITAU, 17451 QUARTER_PI: QUARTER_PI, 17452 RAD_PER_DEG: RAD_PER_DEG, 17453 TAU: TAU, 17454 TWO_THIRDS_PI: TWO_THIRDS_PI, 17455 _addGrace: _addGrace, 17456 _alignPixel: _alignPixel, 17457 _alignStartEnd: _alignStartEnd, 17458 _angleBetween: _angleBetween, 17459 _angleDiff: _angleDiff, 17460 _arrayUnique: _arrayUnique, 17461 _attachContext: _attachContext, 17462 _bezierCurveTo: _bezierCurveTo, 17463 _bezierInterpolation: _bezierInterpolation, 17464 _boundSegment: _boundSegment, 17465 _boundSegments: _boundSegments, 17466 _capitalize: _capitalize, 17467 _computeSegments: _computeSegments, 17468 _createResolver: _createResolver, 17469 _decimalPlaces: _decimalPlaces, 17470 _deprecated: _deprecated, 17471 _descriptors: _descriptors, 17472 _elementsEqual: _elementsEqual, 17473 _factorize: _factorize, 17474 _filterBetween: _filterBetween, 17475 _getParentNode: _getParentNode, 17476 _getStartAndCountOfVisiblePoints: _getStartAndCountOfVisiblePoints, 17477 _int16Range: _int16Range, 17478 _isBetween: _isBetween, 17479 _isClickEvent: _isClickEvent,
vendor: 5,035 bytes, lines 17480-17634
17480 _isDomSupported: _isDomSupported, 17481 _isPointInArea: _isPointInArea, 17482 _limitValue: _limitValue, 17483 _longestText: _longestText, 17484 _lookup: _lookup, 17485 _lookupByKey: _lookupByKey, 17486 _measureText: _measureText, 17487 _merger: _merger, 17488 _mergerIf: _mergerIf, 17489 _normalizeAngle: _normalizeAngle, 17490 _parseObjectDataRadialScale: _parseObjectDataRadialScale, 17491 _pointInLine: _pointInLine, 17492 _readValueToProps: _readValueToProps, 17493 _rlookupByKey: _rlookupByKey, 17494 _scaleRangesChanged: _scaleRangesChanged, 17495 _setMinAndMaxByKey: _setMinAndMaxByKey, 17496 _splitKey: _splitKey, 17497 _steppedInterpolation: _steppedInterpolation, 17498 _steppedLineTo: _steppedLineTo, 17499 _textX: _textX, 17500 _toLeftRightCenter: _toLeftRightCenter, 17501 _updateBezierControlPoints: _updateBezierControlPoints, 17502 addRoundedRectPath: addRoundedRectPath, 17503 almostEquals: almostEquals, 17504 almostWhole: almostWhole, 17505 callback: callback, 17506 clearCanvas: clearCanvas, 17507 clipArea: clipArea, 17508 clone: clone, 17509 color: color, 17510 createContext: createContext, 17511 debounce: debounce, 17512 defined: defined, 17513 distanceBetweenPoints: distanceBetweenPoints, 17514 drawPoint: drawPoint, 17515 drawPointLegend: drawPointLegend, 17516 each: each, 17517 easingEffects: effects, 17518 finiteOrDefault: finiteOrDefault, 17519 fontString: fontString, 17520 formatNumber: formatNumber, 17521 getAngleFromPoint: getAngleFromPoint, 17522 getDatasetClipArea: getDatasetClipArea, 17523 getHoverColor: getHoverColor, 17524 getMaximumSize: getMaximumSize, 17525 getRelativePosition: getRelativePosition, 17526 getRtlAdapter: getRtlAdapter, 17527 getStyle: getStyle, 17528 isArray: isArray, 17529 isFinite: isNumberFinite, 17530 isFunction: isFunction, 17531 isNullOrUndef: isNullOrUndef, 17532 isNumber: isNumber, 17533 isObject: isObject, 17534 isPatternOrGradient: isPatternOrGradient, 17535 listenArrayEvents: listenArrayEvents, 17536 log10: log10, 17537 merge: merge, 17538 mergeIf: mergeIf, 17539 niceNum: niceNum, 17540 noop: noop, 17541 overrideTextDirection: overrideTextDirection, 17542 readUsedSize: readUsedSize, 17543 renderText: renderText, 17544 requestAnimFrame: requestAnimFrame, 17545 resolve: resolve, 17546 resolveObjectKey: resolveObjectKey, 17547 restoreTextDirection: restoreTextDirection, 17548 retinaScale: retinaScale, 17549 setsEqual: setsEqual, 17550 sign: sign, 17551 splineCurve: splineCurve, 17552 splineCurveMonotone: splineCurveMonotone, 17553 supportsEventListenerOptions: supportsEventListenerOptions, 17554 throttled: throttled, 17555 toDegrees: toDegrees, 17556 toDimension: toDimension, 17557 toFont: toFont, 17558 toFontString: toFontString, 17559 toLineHeight: toLineHeight, 17560 toPadding: toPadding, 17561 toPercentage: toPercentage, 17562 toRadians: toRadians, 17563 toTRBL: toTRBL, 17564 toTRBLCorners: toTRBLCorners, 17565 uid: uid, 17566 unclipArea: unclipArea, 17567 unlistenArrayEvents: unlistenArrayEvents, 17568 valueOrDefault: valueOrDefault 17569 }); 17570 17571 function _typeof(o) { 17572 "@babel/helpers - typeof"; 17573 17574 return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { 17575 return typeof o; 17576 } : function (o) { 17577 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; 17578 }, _typeof(o); 17579 } 17580 17581 function toInteger(dirtyNumber) { 17582 if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) { 17583 return NaN; 17584 } 17585 var number = Number(dirtyNumber); 17586 if (isNaN(number)) { 17587 return number; 17588 } 17589 return number < 0 ? Math.ceil(number) : Math.floor(number); 17590 } 17591 17592 function requiredArgs(required, args) { 17593 if (args.length < required) { 17594 throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present'); 17595 } 17596 } 17597 17598 /** 17599 * @name toDate 17600 * @category Common Helpers 17601 * @summary Convert the given argument to an instance of Date. 17602 * 17603 * @description 17604 * Convert the given argument to an instance of Date. 17605 * 17606 * If the argument is an instance of Date, the function returns its clone. 17607 * 17608 * If the argument is a number, it is treated as a timestamp. 17609 * 17610 * If the argument is none of the above, the function returns Invalid Date. 17611 * 17612 * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`. 17613 * 17614 * @param {Date|Number} argument - the value to convert 17615 * @returns {Date} the parsed date in the local time zone 17616 * @throws {TypeError} 1 argument required 17617 * 17618 * @example 17619 * // Clone the date: 17620 * const result = toDate(new Date(2014, 1, 11, 11, 30, 30)) 17621 * //=> Tue Feb 11 2014 11:30:30 17622 * 17623 * @example 17624 * // Convert the timestamp to date: 17625 * const result = toDate(1392098430000) 17626 * //=> Tue Feb 11 2014 11:30:30 17627 */ 17628 function toDate(argument) { 17629 requiredArgs(1, arguments); 17630 var argStr = Object.prototype.toString.call(argument); 17631 17632 // Clone the date 17633 if (argument instanceof Date || _typeof(argument) === 'object' && argStr === '[object Date]') { 17634 // Prevent the date to lose the milliseconds when passed to
vendor: 5,371 bytes, lines 17634-17760
17634new Date() in IE10 17635 return new Date(argument.getTime()); 17636 } else if (typeof argument === 'number' || argStr === '[object Number]') { 17637 return new Date(argument); 17638 } else { 17639 if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') { 17640 // eslint-disable-next-line no-console 17641 console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"); 17642 // eslint-disable-next-line no-console 17643 console.warn(new Error().stack); 17644 } 17645 return new Date(NaN); 17646 } 17647 } 17648 17649 /** 17650 * @name addDays 17651 * @category Day Helpers 17652 * @summary Add the specified number of days to the given date. 17653 * 17654 * @description 17655 * Add the specified number of days to the given date. 17656 * 17657 * @param {Date|Number} date - the date to be changed 17658 * @param {Number} amount - the amount of days to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. 17659 * @returns {Date} - the new date with the days added 17660 * @throws {TypeError} - 2 arguments required 17661 * 17662 * @example 17663 * // Add 10 days to 1 September 2014: 17664 * const result = addDays(new Date(2014, 8, 1), 10) 17665 * //=> Thu Sep 11 2014 00:00:00 17666 */ 17667 function addDays(dirtyDate, dirtyAmount) { 17668 requiredArgs(2, arguments); 17669 var date = toDate(dirtyDate); 17670 var amount = toInteger(dirtyAmount); 17671 if (isNaN(amount)) { 17672 return new Date(NaN); 17673 } 17674 if (!amount) { 17675 // If 0 days, no-op to avoid changing times in the hour before end of DST 17676 return date; 17677 } 17678 date.setDate(date.getDate() + amount); 17679 return date; 17680 } 17681 17682 /** 17683 * @name addMonths 17684 * @category Month Helpers 17685 * @summary Add the specified number of months to the given date. 17686 * 17687 * @description 17688 * Add the specified number of months to the given date. 17689 * 17690 * @param {Date|Number} date - the date to be changed 17691 * @param {Number} amount - the amount of months to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. 17692 * @returns {Date} the new date with the months added 17693 * @throws {TypeError} 2 arguments required 17694 * 17695 * @example 17696 * // Add 5 months to 1 September 2014: 17697 * const result = addMonths(new Date(2014, 8, 1), 5) 17698 * //=> Sun Feb 01 2015 00:00:00 17699 */ 17700 function addMonths(dirtyDate, dirtyAmount) { 17701 requiredArgs(2, arguments); 17702 var date = toDate(dirtyDate); 17703 var amount = toInteger(dirtyAmount); 17704 if (isNaN(amount)) { 17705 return new Date(NaN); 17706 } 17707 if (!amount) { 17708 // If 0 months, no-op to avoid changing times in the hour before end of DST 17709 return date; 17710 } 17711 var dayOfMonth = date.getDate(); 17712 17713 // The JS Date object supports date math by accepting out-of-bounds values for 17714 // month, day, etc. For example, new Date(2020, 0, 0) returns 31 Dec 2019 and 17715 // new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we 17716 // want except that dates will wrap around the end of a month, meaning that 17717 // new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So 17718 // we'll default to the end of the desired month by adding 1 to the desired 17719 // month and using a date of 0 to back up one day to the end of the desired 17720 // month. 17721 var endOfDesiredMonth = new Date(date.getTime()); 17722 endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0); 17723 var daysInMonth = endOfDesiredMonth.getDate(); 17724 if (dayOfMonth >= daysInMonth) { 17725 // If we're already at the end of the month, then this is the correct date 17726 // and we're done. 17727 return endOfDesiredMonth; 17728 } else { 17729 // Otherwise, we now know that setting the original day-of-month value won't 17730 // cause an overflow, so set the desired day-of-month. Note that we can't 17731 // just set the date of `endOfDesiredMonth` because that object may have had 17732 // its time changed in the unusual case where where a DST transition was on 17733 // the last day of the month and its local time was in the hour skipped or 17734 // repeated next to a DST transition. So we use `date` instead which is 17735 // guaranteed to still have the original time. 17736 date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth); 17737 return date; 17738 } 17739 } 17740 17741 /** 17742 * @name addMilliseconds 17743 * @category Millisecond Helpers 17744 * @summary Add the specified number of milliseconds to the given date. 17745 * 17746 * @description 17747 * Add the specified number of milliseconds to the given date. 17748 * 17749 * @param {Date|Number} date - the date to be changed 17750 * @param {Number} amount - the amount of milliseconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. 17751 * @returns {Date} the new date with the milliseconds added 17752 * @throws {TypeError} 2 arguments required 17753 * 17754 * @example 17755 * // Add 750 milliseconds to 10 July 2014 12:45:30.000: 17756 * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) 17757 * //=> Thu Jul 10 2014 12:45:30.750 17758 */ 17759 function addMilliseconds(dirtyDate, dirtyAmount) { 17760 requiredArgs(2, arguments);
vendor: 4,347 bytes, lines 17761-17848
17761 var timestamp = toDate(dirtyDate).getTime(); 17762 var amount = toInteger(dirtyAmount); 17763 return new Date(timestamp + amount); 17764 } 17765 17766 var MILLISECONDS_IN_HOUR = 3600000; 17767 17768 /** 17769 * @name addHours 17770 * @category Hour Helpers 17771 * @summary Add the specified number of hours to the given date. 17772 * 17773 * @description 17774 * Add the specified number of hours to the given date. 17775 * 17776 * @param {Date|Number} date - the date to be changed 17777 * @param {Number} amount - the amount of hours to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. 17778 * @returns {Date} the new date with the hours added 17779 * @throws {TypeError} 2 arguments required 17780 * 17781 * @example 17782 * // Add 2 hours to 10 July 2014 23:00:00: 17783 * const result = addHours(new Date(2014, 6, 10, 23, 0), 2) 17784 * //=> Fri Jul 11 2014 01:00:00 17785 */ 17786 function addHours(dirtyDate, dirtyAmount) { 17787 requiredArgs(2, arguments); 17788 var amount = toInteger(dirtyAmount); 17789 return addMilliseconds(dirtyDate, amount * MILLISECONDS_IN_HOUR); 17790 } 17791 17792 var defaultOptions = {}; 17793 function getDefaultOptions() { 17794 return defaultOptions; 17795 } 17796 17797 /** 17798 * @name startOfWeek 17799 * @category Week Helpers 17800 * @summary Return the start of a week for the given date. 17801 * 17802 * @description 17803 * Return the start of a week for the given date. 17804 * The result will be in the local timezone. 17805 * 17806 * @param {Date|Number} date - the original date 17807 * @param {Object} [options] - an object with options. 17808 * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} 17809 * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) 17810 * @returns {Date} the start of a week 17811 * @throws {TypeError} 1 argument required 17812 * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 17813 * 17814 * @example 17815 * // The start of a week for 2 September 2014 11:55:00: 17816 * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) 17817 * //=> Sun Aug 31 2014 00:00:00 17818 * 17819 * @example 17820 * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: 17821 * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 }) 17822 * //=> Mon Sep 01 2014 00:00:00 17823 */ 17824 function startOfWeek(dirtyDate, options) { 17825 var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; 17826 requiredArgs(1, arguments); 17827 var defaultOptions = getDefaultOptions(); 17828 var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); 17829 17830 // Test if weekStartsOn is between 0 and 6 _and_ is not NaN 17831 if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { 17832 throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); 17833 } 17834 var date = toDate(dirtyDate); 17835 var day = date.getDay(); 17836 var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; 17837 date.setDate(date.getDate() - diff); 17838 date.setHours(0, 0, 0, 0); 17839 return date; 17840 } 17841 17842 /** 17843 * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds. 17844 * They usually appear for dates that denote time before the timezones were introduced 17845 * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891 17846 * and GMT+01:00:00 after that date) 17847 * 17848 * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
vendor: 5,765 bytes, lines 17849-18004
17849 * which would lead to incorrect calculations. 17850 * 17851 * This function returns the timezone offset in milliseconds that takes seconds in account. 17852 */ 17853 function getTimezoneOffsetInMilliseconds(date) { 17854 var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds())); 17855 utcDate.setUTCFullYear(date.getFullYear()); 17856 return date.getTime() - utcDate.getTime(); 17857 } 17858 17859 /** 17860 * @name startOfDay 17861 * @category Day Helpers 17862 * @summary Return the start of a day for the given date. 17863 * 17864 * @description 17865 * Return the start of a day for the given date. 17866 * The result will be in the local timezone. 17867 * 17868 * @param {Date|Number} date - the original date 17869 * @returns {Date} the start of a day 17870 * @throws {TypeError} 1 argument required 17871 * 17872 * @example 17873 * // The start of a day for 2 September 2014 11:55:00: 17874 * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0)) 17875 * //=> Tue Sep 02 2014 00:00:00 17876 */ 17877 function startOfDay(dirtyDate) { 17878 requiredArgs(1, arguments); 17879 var date = toDate(dirtyDate); 17880 date.setHours(0, 0, 0, 0); 17881 return date; 17882 } 17883 17884 var MILLISECONDS_IN_DAY$1 = 86400000; 17885 17886 /** 17887 * @name differenceInCalendarDays 17888 * @category Day Helpers 17889 * @summary Get the number of calendar days between the given dates. 17890 * 17891 * @description 17892 * Get the number of calendar days between the given dates. This means that the times are removed 17893 * from the dates and then the difference in days is calculated. 17894 * 17895 * @param {Date|Number} dateLeft - the later date 17896 * @param {Date|Number} dateRight - the earlier date 17897 * @returns {Number} the number of calendar days 17898 * @throws {TypeError} 2 arguments required 17899 * 17900 * @example 17901 * // How many calendar days are between 17902 * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? 17903 * const result = differenceInCalendarDays( 17904 * new Date(2012, 6, 2, 0, 0), 17905 * new Date(2011, 6, 2, 23, 0) 17906 * ) 17907 * //=> 366 17908 * // How many calendar days are between 17909 * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00? 17910 * const result = differenceInCalendarDays( 17911 * new Date(2011, 6, 3, 0, 1), 17912 * new Date(2011, 6, 2, 23, 59) 17913 * ) 17914 * //=> 1 17915 */ 17916 function differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) { 17917 requiredArgs(2, arguments); 17918 var startOfDayLeft = startOfDay(dirtyDateLeft); 17919 var startOfDayRight = startOfDay(dirtyDateRight); 17920 var timestampLeft = startOfDayLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfDayLeft); 17921 var timestampRight = startOfDayRight.getTime() - getTimezoneOffsetInMilliseconds(startOfDayRight); 17922 17923 // Round the number of days to the nearest integer 17924 // because the number of milliseconds in a day is not constant 17925 // (e.g. it's different in the day of the daylight saving time clock shift) 17926 return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY$1); 17927 } 17928 17929 var MILLISECONDS_IN_MINUTE = 60000; 17930 17931 /** 17932 * @name addMinutes 17933 * @category Minute Helpers 17934 * @summary Add the specified number of minutes to the given date. 17935 * 17936 * @description 17937 * Add the specified number of minutes to the given date. 17938 * 17939 * @param {Date|Number} date - the date to be changed 17940 * @param {Number} amount - the amount of minutes to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. 17941 * @returns {Date} the new date with the minutes added 17942 * @throws {TypeError} 2 arguments required 17943 * 17944 * @example 17945 * // Add 30 minutes to 10 July 2014 12:00:00: 17946 * const result = addMinutes(new Date(2014, 6, 10, 12, 0), 30) 17947 * //=> Thu Jul 10 2014 12:30:00 17948 */ 17949 function addMinutes(dirtyDate, dirtyAmount) { 17950 requiredArgs(2, arguments); 17951 var amount = toInteger(dirtyAmount); 17952 return addMilliseconds(dirtyDate, amount * MILLISECONDS_IN_MINUTE); 17953 } 17954 17955 /** 17956 * @name addQuarters 17957 * @category Quarter Helpers 17958 * @summary Add the specified number of year quarters to the given date. 17959 * 17960 * @description 17961 * Add the specified number of year quarters to the given date. 17962 * 17963 * @param {Date|Number} date - the date to be changed 17964 * @param {Number} amount - the amount of quarters to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. 17965 * @returns {Date} the new date with the quarters added 17966 * @throws {TypeError} 2 arguments required 17967 * 17968 * @example 17969 * // Add 1 quarter to 1 September 2014: 17970 * const result = addQuarters(new Date(2014, 8, 1), 1) 17971 * //=> Mon Dec 01 2014 00:00:00 17972 */ 17973 function addQuarters(dirtyDate, dirtyAmount) { 17974 requiredArgs(2, arguments); 17975 var amount = toInteger(dirtyAmount); 17976 var months = amount * 3; 17977 return addMonths(dirtyDate, months); 17978 } 17979 17980 /** 17981 * @name addSeconds 17982 * @category Second Helpers 17983 * @summary Add the specified number of seconds to the given date. 17984 * 17985 * @description 17986 * Add the specified number of seconds to the given date. 17987 * 17988 * @param {Date|Number} date - the date to be changed 17989 * @param {Number} amount - the amount of seconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. 17990 * @returns {Date} the new date with the seconds added 17991 * @throws {TypeError} 2 arguments required 17992 * 17993 * @example 17994 * // Add 30 seconds to 10 July 2014 12:45:00: 17995 * const result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) 17996 * //=> Thu Jul 10 2014 12:45:30 17997 */ 17998 function addSeconds(dirtyDate, dirtyAmount) { 17999 requiredArgs(2, arguments); 18000 var amount = toInteger(dirtyAmount); 18001 return addMilliseconds(dirtyDate, amount * 1000); 18002 } 18003 18004 /**
18005 * @name addWeeks 18006 * @category Week Helpers 18007 * @summary Add the specified number of weeks to the given date. 18008 * 18009 * @description 18010 * Add the specified number of week to the given date. 18011 * 18012 * @param {Date|Number} date - the date to be changed 18013 * @param {Number} amount - the amount of weeks to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. 18014 * @returns {Date} the new date with the weeks added 18015 * @throws {TypeError} 2 arguments required 18016 * 18017 * @example 18018 * // Add 4 weeks to 1 September 2014: 18019 * const result = addWeeks(new Date(2014, 8, 1), 4) 18020 * //=> Mon Sep 29 2014 00:00:00 18021 */ 18022 function addWeeks(dirtyDate, dirtyAmount) { 18023 requiredArgs(2, arguments); 18024 var amount = toInteger(dirtyAmount); 18025 var days = amount * 7; 18026 return addDays(dirtyDate, days); 18027 } 18028 18029 /** 18030 * @name addYears 18031 * @category Year Helpers 18032 * @summary Add the specified number of years to the given date. 18033 * 18034 * @description 18035 * Add the specified number of years to the given date. 18036 * 18037 * @param {Date|Number} date - the date to be changed 18038 * @param {Number} amount - the amount of years to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. 18039 * @returns {Date} the new date with the years added 18040 * @throws {TypeError} 2 arguments required 18041 * 18042 * @example 18043 * // Add 5 years to 1 September 2014: 18044 * const result = addYears(new Date(2014, 8, 1), 5) 18045 * //=> Sun Sep 01 2019 00:00:00 18046 */ 18047 function addYears(dirtyDate, dirtyAmount) { 18048 requiredArgs(2, arguments); 18049 var amount = toInteger(dirtyAmount); 18050 return addMonths(dirtyDate, amount * 12); 18051 } 18052 18053 /** 18054 * @name compareAsc 18055 * @category Common Helpers 18056 * @summary Compare the two dates and return -1, 0 or 1. 18057 * 18058 * @description 18059 * Compare the two dates and return 1 if the first date is after the second, 18060 * -1 if the first date is before the second or 0 if dates are equal. 18061 * 18062 * @param {Date|Number} dateLeft - the first date to compare 18063 * @param {Date|Number} dateRight - the second date to compare 18064 * @returns {Number} the result of the comparison 18065 * @throws {TypeError} 2 arguments required 18066 * 18067 * @example 18068 * // Compare 11 February 1987 and 10 July 1989: 18069 * const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10)) 18070 * //=> -1 18071 * 18072 * @example 18073 * // Sort the array of dates: 18074 * const result = [ 18075 * new Date(1995, 6, 2), 18076 * new Date(1987, 1, 11), 18077 * new Date(1989, 6, 10) 18078 * ].sort(compareAsc) 18079 * //=> [ 18080 * // Wed Feb 11 1987 00:00:00, 18081 * // Mon Jul 10 1989 00:00:00, 18082 * // Sun Jul 02 1995 00:00:00 18083 * // ] 18084 */ 18085 function compareAsc(dirtyDateLeft, dirtyDateRight) { 18086 requiredArgs(2, arguments); 18087 var dateLeft = toDate(dirtyDateLeft); 18088 var dateRight = toDate(dirtyDateRight); 18089 var diff = dateLeft.getTime() - dateRight.getTime(); 18090 if (diff < 0) { 18091 return -1; 18092 } else if (diff > 0) { 18093 return 1; 18094 // Return 0 if diff is 0; return NaN if diff is NaN 18095 } else { 18096 return diff; 18097 } 18098 } 18099 18100 /** 18101 * Days in 1 week. 18102 * 18103 * @name daysInWeek 18104 * @constant 18105 * @type {number} 18106 * @default 18107 */ 18108 18109 /** 18110 * Milliseconds in 1 minute 18111 * 18112 * @name millisecondsInMinute 18113 * @constant 18114 * @type {number} 18115 * @default 18116 */ 18117 var millisecondsInMinute = 60000; 18118 18119 /** 18120 * Milliseconds in 1 hour 18121 * 18122 * @name millisecondsInHour 18123 * @constant 18124 * @type {number} 18125 * @default 18126 */ 18127 var millisecondsInHour = 3600000; 18128 18129 /** 18130 * Milliseconds in 1 second 18131 * 18132 * @name millisecondsInSecond 18133 * @constant 18134 * @type {number} 18135 * @default 18136 */ 18137 var millisecondsInSecond = 1000; 18138 18139 /** 18140 * @name isDate 18141 * @category Common Helpers 18142 * @summary Is the given value a date? 18143 * 18144 * @description 18145 * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes. 18146 * 18147 * @param {*} value - the value to check 18148 * @returns {boolean} true if the given value is a date 18149 * @throws {TypeError} 1 arguments required 18150 * 18151 * @example 18152 * // For a valid date: 18153 * const result = isDate(new Date()) 18154 * //=> true 18155 * 18156 * @example
18157 * // For an invalid date: 18158 * const result = isDate(new Date(NaN)) 18159 * //=> true 18160 * 18161 * @example 18162 * // For some value: 18163 * const result = isDate('2014-02-31') 18164 * //=> false 18165 * 18166 * @example 18167 * // For an object: 18168 * const result = isDate({}) 18169 * //=> false 18170 */ 18171 function isDate(value) { 18172 requiredArgs(1, arguments); 18173 return value instanceof Date || _typeof(value) === 'object' && Object.prototype.toString.call(value) === '[object Date]'; 18174 } 18175 18176 /** 18177 * @name isValid 18178 * @category Common Helpers 18179 * @summary Is the given date valid? 18180 * 18181 * @description 18182 * Returns false if argument is Invalid Date and true otherwise. 18183 * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate} 18184 * Invalid Date is a Date, whose time value is NaN. 18185 * 18186 * Time value of Date: http://es5.github.io/#x15.9.1.1 18187 * 18188 * @param {*} date - the date to check 18189 * @returns {Boolean} the date is valid 18190 * @throws {TypeError} 1 argument required 18191 * 18192 * @example 18193 * // For the valid date: 18194 * const result = isValid(new Date(2014, 1, 31)) 18195 * //=> true 18196 * 18197 * @example 18198 * // For the value, convertable into a date: 18199 * const result = isValid(1393804800000) 18200 * //=> true 18201 * 18202 * @example 18203 * // For the invalid date: 18204 * const result = isValid(new Date('')) 18205 * //=> false 18206 */ 18207 function isValid(dirtyDate) { 18208 requiredArgs(1, arguments); 18209 if (!isDate(dirtyDate) && typeof dirtyDate !== 'number') { 18210 return false; 18211 } 18212 var date = toDate(dirtyDate); 18213 return !isNaN(Number(date)); 18214 } 18215 18216 /** 18217 * @name differenceInCalendarMonths 18218 * @category Month Helpers 18219 * @summary Get the number of calendar months between the given dates. 18220 * 18221 * @description 18222 * Get the number of calendar months between the given dates. 18223 * 18224 * @param {Date|Number} dateLeft - the later date 18225 * @param {Date|Number} dateRight - the earlier date 18226 * @returns {Number} the number of calendar months 18227 * @throws {TypeError} 2 arguments required 18228 * 18229 * @example 18230 * // How many calendar months are between 31 January 2014 and 1 September 2014? 18231 * const result = differenceInCalendarMonths( 18232 * new Date(2014, 8, 1), 18233 * new Date(2014, 0, 31) 18234 * ) 18235 * //=> 8 18236 */ 18237 function differenceInCalendarMonths(dirtyDateLeft, dirtyDateRight) { 18238 requiredArgs(2, arguments); 18239 var dateLeft = toDate(dirtyDateLeft); 18240 var dateRight = toDate(dirtyDateRight); 18241 var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); 18242 var monthDiff = dateLeft.getMonth() - dateRight.getMonth(); 18243 return yearDiff * 12 + monthDiff; 18244 } 18245 18246 /** 18247 * @name differenceInCalendarYears 18248 * @category Year Helpers 18249 * @summary Get the number of calendar years between the given dates. 18250 * 18251 * @description 18252 * Get the number of calendar years between the given dates. 18253 * 18254 * @param {Date|Number} dateLeft - the later date 18255 * @param {Date|Number} dateRight - the earlier date 18256 * @returns {Number} the number of calendar years 18257 * @throws {TypeError} 2 arguments required 18258 * 18259 * @example 18260 * // How many calendar years are between 31 December 2013 and 11 February 2015? 18261 * const result = differenceInCalendarYears( 18262 * new Date(2015, 1, 11), 18263 * new Date(2013, 11, 31) 18264 * ) 18265 * //=> 2 18266 */ 18267 function differenceInCalendarYears(dirtyDateLeft, dirtyDateRight) { 18268 requiredArgs(2, arguments); 18269 var dateLeft = toDate(dirtyDateLeft); 18270 var dateRight = toDate(dirtyDateRight); 18271 return dateLeft.getFullYear() - dateRight.getFullYear(); 18272 } 18273 18274 // for accurate equality comparisons of UTC timestamps that end up 18275 // having the same representation in local time, e.g. one hour before 18276 // DST ends vs. the instant that DST ends. 18277 function compareLocalAsc(dateLeft, dateRight) { 18278 var diff = dateLeft.getFullYear() - dateRight.getFullYear() || dateLeft.getMonth() - dateRight.getMonth() || dateLeft.getDate() - dateRight.getDate() || dateLeft.getHours() - dateRight.getHours() || dateLeft.getMinutes() - dateRight.getMinutes() || dateLeft.getSeconds() - dateRight.getSeconds() || dateLeft.getMilliseconds() - dateRight.getMilliseconds(); 18279 if (diff < 0) { 18280 return -1; 18281 } else if (diff > 0) { 18282 return 1; 18283 // Return 0 if diff is 0; return NaN if diff is NaN 18284 } else { 18285 return diff; 18286 } 18287 } 18288 18289 /** 18290 * @name differenceInDays 18291 * @category Day Helpers 18292 * @summary Get the number of full days between the given dates. 18293 * 18294 * @description 18295 * Get the number of full day periods between two dates. Fractional days are 18296 * truncated towards zero. 18297 * 18298 * One "full day" is the distance between a local time in one day to the same 18299 * local time on the next or previous day. A full day can sometimes be less than 18300 * or more than 24 hours if a daylight savings change happens between two dates. 18301 * 18302 * To ignore DST and only measure exact 24-hour periods, use this instead: 18303 * `Math.floor(differenceInHours(dateLeft, dateRight)/24)|0`. 18304 * 18305 * 18306 * @param {Date|Number} dateLeft - the later date 18307 * @param {Date|Number} dateRight - the earlier date 18308 * @returns {Number} the number of full days according to the local timezone 18309 * @throws {TypeError} 2 arguments required 18310 * 18311 * @example 18312 * // How many full days are between 18313 * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? 18314 * const result = differenceInDays( 18315 * new Date(2012, 6, 2, 0, 0), 18316 * new Date(2011, 6, 2, 23, 0) 18317 * ) 18318 * //=> 365 18319 * // How many full days are between 18320 * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00? 18321 * const result = differenceInDays( 18322 * new Date(2011, 6, 3, 0, 1), 18323 * new Date(2011, 6, 2, 23, 59) 18324 * ) 18325 * //=> 0 18326 * // How many full days are between 18327 * // 1 March 2020 0:00 and 1 June 2020 0:00 ? 18328 * // Note: because local time is used, the 18329 * // result will always be 92 days, even in 18330 * // time zones where DST starts and the 18331 * // period has only 92*24-1 hours. 18332 * const result = differenceInDays( 18333 * new Date(2020, 5, 1), 18334 * new Date(2020, 2, 1) 18335 * ) 18336 //=> 92 18337 */ 18338 function differenceInDays(dirtyDateLeft, dirtyDateRight) { 18339 requiredArgs(2, arguments);
18340 var dateLeft = toDate(dirtyDateLeft); 18341 var dateRight = toDate(dirtyDateRight); 18342 var sign = compareLocalAsc(dateLeft, dateRight); 18343 var difference = Math.abs(differenceInCalendarDays(dateLeft, dateRight)); 18344 dateLeft.setDate(dateLeft.getDate() - sign * difference); 18345 18346 // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full 18347 // If so, result must be decreased by 1 in absolute value 18348 var isLastDayNotFull = Number(compareLocalAsc(dateLeft, dateRight) === -sign); 18349 var result = sign * (difference - isLastDayNotFull); 18350 // Prevent negative zero 18351 return result === 0 ? 0 : result; 18352 } 18353 18354 /** 18355 * @name differenceInMilliseconds 18356 * @category Millisecond Helpers 18357 * @summary Get the number of milliseconds between the given dates. 18358 * 18359 * @description 18360 * Get the number of milliseconds between the given dates. 18361 * 18362 * @param {Date|Number} dateLeft - the later date 18363 * @param {Date|Number} dateRight - the earlier date 18364 * @returns {Number} the number of milliseconds 18365 * @throws {TypeError} 2 arguments required 18366 * 18367 * @example 18368 * // How many milliseconds are between 18369 * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700? 18370 * const result = differenceInMilliseconds( 18371 * new Date(2014, 6, 2, 12, 30, 21, 700), 18372 * new Date(2014, 6, 2, 12, 30, 20, 600) 18373 * ) 18374 * //=> 1100 18375 */ 18376 function differenceInMilliseconds(dateLeft, dateRight) { 18377 requiredArgs(2, arguments); 18378 return toDate(dateLeft).getTime() - toDate(dateRight).getTime(); 18379 } 18380 18381 var roundingMap = { 18382 ceil: Math.ceil, 18383 round: Math.round, 18384 floor: Math.floor, 18385 trunc: function trunc(value) { 18386 return value < 0 ? Math.ceil(value) : Math.floor(value); 18387 } // Math.trunc is not supported by IE 18388 }; 18389 var defaultRoundingMethod = 'trunc'; 18390 function getRoundingMethod(method) { 18391 return method ? roundingMap[method] : roundingMap[defaultRoundingMethod]; 18392 } 18393 18394 /** 18395 * @name differenceInHours 18396 * @category Hour Helpers 18397 * @summary Get the number of hours between the given dates. 18398 * 18399 * @description 18400 * Get the number of hours between the given dates. 18401 * 18402 * @param {Date|Number} dateLeft - the later date 18403 * @param {Date|Number} dateRight - the earlier date 18404 * @param {Object} [options] - an object with options. 18405 * @param {String} [options.roundingMethod='trunc'] - a rounding method (`ceil`, `floor`, `round` or `trunc`) 18406 * @returns {Number} the number of hours 18407 * @throws {TypeError} 2 arguments required 18408 * 18409 * @example 18410 * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00? 18411 * const result = differenceInHours( 18412 * new Date(2014, 6, 2, 19, 0), 18413 * new Date(2014, 6, 2, 6, 50) 18414 * ) 18415 * //=> 12 18416 */ 18417 function differenceInHours(dateLeft, dateRight, options) { 18418 requiredArgs(2, arguments); 18419 var diff = differenceInMilliseconds(dateLeft, dateRight) / millisecondsInHour; 18420 return getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod)(diff); 18421 } 18422 18423 /** 18424 * @name differenceInMinutes 18425 * @category Minute Helpers 18426 * @summary Get the number of minutes between the given dates. 18427 * 18428 * @description 18429 * Get the signed number of full (rounded towards 0) minutes between the given dates. 18430 * 18431 * @param {Date|Number} dateLeft - the later date 18432 * @param {Date|Number} dateRight - the earlier date 18433 * @param {Object} [options] - an object with options. 18434 * @param {String} [options.roundingMethod='trunc'] - a rounding method (`ceil`, `floor`, `round` or `trunc`) 18435 * @returns {Number} the number of minutes 18436 * @throws {TypeError} 2 arguments required 18437 * 18438 * @example 18439 * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00? 18440 * const result = differenceInMinutes( 18441 * new Date(2014, 6, 2, 12, 20, 0), 18442 * new Date(2014, 6, 2, 12, 7, 59) 18443 * ) 18444 * //=> 12 18445 * 18446 * @example 18447 * // How many minutes are between 10:01:59 and 10:00:00 18448 * const result = differenceInMinutes( 18449 * new Date(2000, 0, 1, 10, 0, 0), 18450 * new Date(2000, 0, 1, 10, 1, 59) 18451 * ) 18452 * //=> -1 18453 */ 18454 function differenceInMinutes(dateLeft, dateRight, options) { 18455 requiredArgs(2, arguments); 18456 var diff = differenceInMilliseconds(dateLeft, dateRight) / millisecondsInMinute; 18457 return getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod)(diff); 18458 } 18459 18460 /** 18461 * @name endOfDay 18462 * @category Day Helpers 18463 * @summary Return the end of a day for the given date. 18464 * 18465 * @description 18466 * Return the end of a day for the given date. 18467 * The result will be in the local timezone. 18468 * 18469 * @param {Date|Number} date - the original date 18470 * @returns {Date} the end of a day 18471 * @throws {TypeError} 1 argument required 18472 * 18473 * @example 18474 * // The end of a day for 2 September 2014 11:55:00: 18475 * const result = endOfDay(new Date(2014, 8, 2, 11, 55, 0)) 18476 * //=> Tue Sep 02 2014 23:59:59.999 18477 */ 18478 function endOfDay(dirtyDate) { 18479 requiredArgs(1, arguments);
vendor: 3,282 bytes, lines 18480-18576
18480 var date = toDate(dirtyDate); 18481 date.setHours(23, 59, 59, 999); 18482 return date; 18483 } 18484 18485 /** 18486 * @name endOfMonth 18487 * @category Month Helpers 18488 * @summary Return the end of a month for the given date. 18489 * 18490 * @description 18491 * Return the end of a month for the given date. 18492 * The result will be in the local timezone. 18493 * 18494 * @param {Date|Number} date - the original date 18495 * @returns {Date} the end of a month 18496 * @throws {TypeError} 1 argument required 18497 * 18498 * @example 18499 * // The end of a month for 2 September 2014 11:55:00: 18500 * const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0)) 18501 * //=> Tue Sep 30 2014 23:59:59.999 18502 */ 18503 function endOfMonth(dirtyDate) { 18504 requiredArgs(1, arguments); 18505 var date = toDate(dirtyDate); 18506 var month = date.getMonth(); 18507 date.setFullYear(date.getFullYear(), month + 1, 0); 18508 date.setHours(23, 59, 59, 999); 18509 return date; 18510 } 18511 18512 /** 18513 * @name isLastDayOfMonth 18514 * @category Month Helpers 18515 * @summary Is the given date the last day of a month? 18516 * 18517 * @description 18518 * Is the given date the last day of a month? 18519 * 18520 * @param {Date|Number} date - the date to check 18521 * @returns {Boolean} the date is the last day of a month 18522 * @throws {TypeError} 1 argument required 18523 * 18524 * @example 18525 * // Is 28 February 2014 the last day of a month? 18526 * const result = isLastDayOfMonth(new Date(2014, 1, 28)) 18527 * //=> true 18528 */ 18529 function isLastDayOfMonth(dirtyDate) { 18530 requiredArgs(1, arguments); 18531 var date = toDate(dirtyDate); 18532 return endOfDay(date).getTime() === endOfMonth(date).getTime(); 18533 } 18534 18535 /** 18536 * @name differenceInMonths 18537 * @category Month Helpers 18538 * @summary Get the number of full months between the given dates. 18539 * 18540 * @description 18541 * Get the number of full months between the given dates using trunc as a default rounding method. 18542 * 18543 * @param {Date|Number} dateLeft - the later date 18544 * @param {Date|Number} dateRight - the earlier date 18545 * @returns {Number} the number of full months 18546 * @throws {TypeError} 2 arguments required 18547 * 18548 * @example 18549 * // How many full months are between 31 January 2014 and 1 September 2014? 18550 * const result = differenceInMonths(new Date(2014, 8, 1), new Date(2014, 0, 31)) 18551 * //=> 7 18552 */ 18553 function differenceInMonths(dirtyDateLeft, dirtyDateRight) { 18554 requiredArgs(2, arguments); 18555 var dateLeft = toDate(dirtyDateLeft); 18556 var dateRight = toDate(dirtyDateRight); 18557 var sign = compareAsc(dateLeft, dateRight); 18558 var difference = Math.abs(differenceInCalendarMonths(dateLeft, dateRight)); 18559 var result; 18560 18561 // Check for the difference of less than month 18562 if (difference < 1) { 18563 result = 0; 18564 } else { 18565 if (dateLeft.getMonth() === 1 && dateLeft.getDate() > 27) { 18566 // This will check if the date is end of Feb and assign a higher end of month date 18567 // to compare it with Jan 18568 dateLeft.setDate(30); 18569 } 18570 dateLeft.setMonth(dateLeft.getMonth() - sign * difference); 18571 18572 // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full 18573 // If so, result must be decreased by 1 in absolute value 18574 var isLastMonthNotFull = compareAsc(dateLeft, dateRight) === -sign; 18575 18576 // Check for cases of one full calendar month
18577 if (isLastDayOfMonth(toDate(dirtyDateLeft)) && difference === 1 && compareAsc(dirtyDateLeft, dateRight) === 1) { 18578 isLastMonthNotFull = false; 18579 } 18580 result = sign * (difference - Number(isLastMonthNotFull)); 18581 } 18582 18583 // Prevent negative zero 18584 return result === 0 ? 0 : result; 18585 } 18586 18587 /** 18588 * @name differenceInQuarters 18589 * @category Quarter Helpers 18590 * @summary Get the number of quarters between the given dates. 18591 * 18592 * @description 18593 * Get the number of quarters between the given dates. 18594 * 18595 * @param {Date|Number} dateLeft - the later date 18596 * @param {Date|Number} dateRight - the earlier date 18597 * @param {Object} [options] - an object with options. 18598 * @param {String} [options.roundingMethod='trunc'] - a rounding method (`ceil`, `floor`, `round` or `trunc`) 18599 * @returns {Number} the number of full quarters 18600 * @throws {TypeError} 2 arguments required 18601 * 18602 * @example 18603 * // How many full quarters are between 31 December 2013 and 2 July 2014? 18604 * const result = differenceInQuarters(new Date(2014, 6, 2), new Date(2013, 11, 31)) 18605 * //=> 2 18606 */ 18607 function differenceInQuarters(dateLeft, dateRight, options) { 18608 requiredArgs(2, arguments); 18609 var diff = differenceInMonths(dateLeft, dateRight) / 3; 18610 return getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod)(diff); 18611 } 18612 18613 /** 18614 * @name differenceInSeconds 18615 * @category Second Helpers 18616 * @summary Get the number of seconds between the given dates. 18617 * 18618 * @description 18619 * Get the number of seconds between the given dates. 18620 * 18621 * @param {Date|Number} dateLeft - the later date 18622 * @param {Date|Number} dateRight - the earlier date 18623 * @param {Object} [options] - an object with options. 18624 * @param {String} [options.roundingMethod='trunc'] - a rounding method (`ceil`, `floor`, `round` or `trunc`) 18625 * @returns {Number} the number of seconds 18626 * @throws {TypeError} 2 arguments required 18627 * 18628 * @example 18629 * // How many seconds are between 18630 * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000? 18631 * const result = differenceInSeconds( 18632 * new Date(2014, 6, 2, 12, 30, 20, 0), 18633 * new Date(2014, 6, 2, 12, 30, 7, 999) 18634 * ) 18635 * //=> 12 18636 */ 18637 function differenceInSeconds(dateLeft, dateRight, options) { 18638 requiredArgs(2, arguments); 18639 var diff = differenceInMilliseconds(dateLeft, dateRight) / 1000; 18640 return getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod)(diff); 18641 } 18642 18643 /** 18644 * @name differenceInWeeks 18645 * @category Week Helpers 18646 * @summary Get the number of full weeks between the given dates. 18647 * 18648 * @description 18649 * Get the number of full weeks between two dates. Fractional weeks are 18650 * truncated towards zero by default. 18651 * 18652 * One "full week" is the distance between a local time in one day to the same 18653 * local time 7 days earlier or later. A full week can sometimes be less than 18654 * or more than 7*24 hours if a daylight savings change happens between two dates. 18655 * 18656 * To ignore DST and only measure exact 7*24-hour periods, use this instead: 18657 * `Math.floor(differenceInHours(dateLeft, dateRight)/(7*24))|0`. 18658 * 18659 * 18660 * @param {Date|Number} dateLeft - the later date 18661 * @param {Date|Number} dateRight - the earlier date 18662 * @param {Object} [options] - an object with options. 18663 * @param {String} [options.roundingMethod='trunc'] - a rounding method (`ceil`, `floor`, `round` or `trunc`) 18664 * @returns {Number} the number of full weeks 18665 * @throws {TypeError} 2 arguments required 18666 * 18667 * @example 18668 * // How many full weeks are between 5 July 2014 and 20 July 2014? 18669 * const result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5)) 18670 * //=> 2 18671 * 18672 * // How many full weeks are between 18673 * // 1 March 2020 0:00 and 6 June 2020 0:00 ? 18674 * // Note: because local time is used, the 18675 * // result will always be 8 weeks (54 days), 18676 * // even if DST starts and the period has 18677 * // only 54*24-1 hours. 18678 * const result = differenceInWeeks( 18679 * new Date(2020, 5, 1), 18680 * new Date(2020, 2, 6) 18681 * ) 18682 * //=> 8 18683 */ 18684 function differenceInWeeks(dateLeft, dateRight, options) { 18685 requiredArgs(2, arguments); 18686 var diff = differenceInDays(dateLeft, dateRight) / 7; 18687 return getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod)(diff); 18688 } 18689 18690 /** 18691 * @name differenceInYears 18692 * @category Year Helpers 18693 * @summary Get the number of full years between the given dates. 18694 * 18695 * @description 18696 * Get the number of full years between the given dates. 18697 * 18698 * @param {Date|Number} dateLeft - the later date 18699 * @param {Date|Number} dateRight - the earlier date 18700 * @returns {Number} the number of full years 18701 * @throws {TypeError} 2 arguments required 18702 * 18703 * @example 18704 * // How many full years are between 31 December 2013 and 11 February 2015? 18705 * const result = differenceInYears(new Date(2015, 1, 11), new Date(2013, 11, 31)) 18706 * //=> 1 18707 */ 18708 function differenceInYears(dirtyDateLeft, dirtyDateRight) { 18709 requiredArgs(2, arguments);
vendor: 4,545 bytes, lines 18710-18853
18710 var dateLeft = toDate(dirtyDateLeft); 18711 var dateRight = toDate(dirtyDateRight); 18712 var sign = compareAsc(dateLeft, dateRight); 18713 var difference = Math.abs(differenceInCalendarYears(dateLeft, dateRight)); 18714 18715 // Set both dates to a valid leap year for accurate comparison when dealing 18716 // with leap days 18717 dateLeft.setFullYear(1584); 18718 dateRight.setFullYear(1584); 18719 18720 // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full 18721 // If so, result must be decreased by 1 in absolute value 18722 var isLastYearNotFull = compareAsc(dateLeft, dateRight) === -sign; 18723 var result = sign * (difference - Number(isLastYearNotFull)); 18724 // Prevent negative zero 18725 return result === 0 ? 0 : result; 18726 } 18727 18728 /** 18729 * @name startOfMinute 18730 * @category Minute Helpers 18731 * @summary Return the start of a minute for the given date. 18732 * 18733 * @description 18734 * Return the start of a minute for the given date. 18735 * The result will be in the local timezone. 18736 * 18737 * @param {Date|Number} date - the original date 18738 * @returns {Date} the start of a minute 18739 * @throws {TypeError} 1 argument required 18740 * 18741 * @example 18742 * // The start of a minute for 1 December 2014 22:15:45.400: 18743 * const result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) 18744 * //=> Mon Dec 01 2014 22:15:00 18745 */ 18746 function startOfMinute(dirtyDate) { 18747 requiredArgs(1, arguments); 18748 var date = toDate(dirtyDate); 18749 date.setSeconds(0, 0); 18750 return date; 18751 } 18752 18753 /** 18754 * @name startOfQuarter 18755 * @category Quarter Helpers 18756 * @summary Return the start of a year quarter for the given date. 18757 * 18758 * @description 18759 * Return the start of a year quarter for the given date. 18760 * The result will be in the local timezone. 18761 * 18762 * @param {Date|Number} date - the original date 18763 * @returns {Date} the start of a quarter 18764 * @throws {TypeError} 1 argument required 18765 * 18766 * @example 18767 * // The start of a quarter for 2 September 2014 11:55:00: 18768 * const result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) 18769 * //=> Tue Jul 01 2014 00:00:00 18770 */ 18771 function startOfQuarter(dirtyDate) { 18772 requiredArgs(1, arguments); 18773 var date = toDate(dirtyDate); 18774 var currentMonth = date.getMonth(); 18775 var month = currentMonth - currentMonth % 3; 18776 date.setMonth(month, 1); 18777 date.setHours(0, 0, 0, 0); 18778 return date; 18779 } 18780 18781 /** 18782 * @name startOfMonth 18783 * @category Month Helpers 18784 * @summary Return the start of a month for the given date. 18785 * 18786 * @description 18787 * Return the start of a month for the given date. 18788 * The result will be in the local timezone. 18789 * 18790 * @param {Date|Number} date - the original date 18791 * @returns {Date} the start of a month 18792 * @throws {TypeError} 1 argument required 18793 * 18794 * @example 18795 * // The start of a month for 2 September 2014 11:55:00: 18796 * const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0)) 18797 * //=> Mon Sep 01 2014 00:00:00 18798 */ 18799 function startOfMonth(dirtyDate) { 18800 requiredArgs(1, arguments); 18801 var date = toDate(dirtyDate); 18802 date.setDate(1); 18803 date.setHours(0, 0, 0, 0); 18804 return date; 18805 } 18806 18807 /** 18808 * @name endOfYear 18809 * @category Year Helpers 18810 * @summary Return the end of a year for the given date. 18811 * 18812 * @description 18813 * Return the end of a year for the given date. 18814 * The result will be in the local timezone. 18815 * 18816 * @param {Date|Number} date - the original date 18817 * @returns {Date} the end of a year 18818 * @throws {TypeError} 1 argument required 18819 * 18820 * @example 18821 * // The end of a year for 2 September 2014 11:55:00: 18822 * const result = endOfYear(new Date(2014, 8, 2, 11, 55, 00)) 18823 * //=> Wed Dec 31 2014 23:59:59.999 18824 */ 18825 function endOfYear(dirtyDate) { 18826 requiredArgs(1, arguments); 18827 var date = toDate(dirtyDate); 18828 var year = date.getFullYear(); 18829 date.setFullYear(year + 1, 0, 0); 18830 date.setHours(23, 59, 59, 999); 18831 return date; 18832 } 18833 18834 /** 18835 * @name startOfYear 18836 * @category Year Helpers 18837 * @summary Return the start of a year for the given date. 18838 * 18839 * @description 18840 * Return the start of a year for the given date. 18841 * The result will be in the local timezone. 18842 * 18843 * @param {Date|Number} date - the original date 18844 * @returns {Date} the start of a year 18845 * @throws {TypeError} 1 argument required 18846 * 18847 * @example 18848 * // The start of a year for 2 September 2014 11:55:00: 18849 * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00)) 18850 * //=> Wed Jan 01 2014 00:00:00 18851 */ 18852 function startOfYear(dirtyDate) { 18853 requiredArgs(1, arguments);
vendor: 4,295 bytes, lines 18854-18950
18854 var cleanDate = toDate(dirtyDate); 18855 var date = new Date(0); 18856 date.setFullYear(cleanDate.getFullYear(), 0, 1); 18857 date.setHours(0, 0, 0, 0); 18858 return date; 18859 } 18860 18861 /** 18862 * @name endOfHour 18863 * @category Hour Helpers 18864 * @summary Return the end of an hour for the given date. 18865 * 18866 * @description 18867 * Return the end of an hour for the given date. 18868 * The result will be in the local timezone. 18869 * 18870 * @param {Date|Number} date - the original date 18871 * @returns {Date} the end of an hour 18872 * @throws {TypeError} 1 argument required 18873 * 18874 * @example 18875 * // The end of an hour for 2 September 2014 11:55:00: 18876 * const result = endOfHour(new Date(2014, 8, 2, 11, 55)) 18877 * //=> Tue Sep 02 2014 11:59:59.999 18878 */ 18879 function endOfHour(dirtyDate) { 18880 requiredArgs(1, arguments); 18881 var date = toDate(dirtyDate); 18882 date.setMinutes(59, 59, 999); 18883 return date; 18884 } 18885 18886 /** 18887 * @name endOfWeek 18888 * @category Week Helpers 18889 * @summary Return the end of a week for the given date. 18890 * 18891 * @description 18892 * Return the end of a week for the given date. 18893 * The result will be in the local timezone. 18894 * 18895 * @param {Date|Number} date - the original date 18896 * @param {Object} [options] - an object with options. 18897 * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} 18898 * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) 18899 * @returns {Date} the end of a week 18900 * @throws {TypeError} 1 argument required 18901 * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 18902 * 18903 * @example 18904 * // The end of a week for 2 September 2014 11:55:00: 18905 * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0)) 18906 * //=> Sat Sep 06 2014 23:59:59.999 18907 * 18908 * @example 18909 * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00: 18910 * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 }) 18911 * //=> Sun Sep 07 2014 23:59:59.999 18912 */ 18913 function endOfWeek(dirtyDate, options) { 18914 var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; 18915 requiredArgs(1, arguments); 18916 var defaultOptions = getDefaultOptions(); 18917 var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); 18918 18919 // Test if weekStartsOn is between 0 and 6 _and_ is not NaN 18920 if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { 18921 throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); 18922 } 18923 var date = toDate(dirtyDate); 18924 var day = date.getDay(); 18925 var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); 18926 date.setDate(date.getDate() + diff); 18927 date.setHours(23, 59, 59, 999); 18928 return date; 18929 } 18930 18931 /** 18932 * @name endOfMinute 18933 * @category Minute Helpers 18934 * @summary Return the end of a minute for the given date. 18935 * 18936 * @description 18937 * Return the end of a minute for the given date. 18938 * The result will be in the local timezone. 18939 * 18940 * @param {Date|Number} date - the original date 18941 * @returns {Date} the end of a minute 18942 * @throws {TypeError} 1 argument required 18943 * 18944 * @example 18945 * // The end of a minute for 1 December 2014 22:15:45.400: 18946 * const result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) 18947 * //=> Mon Dec 01 2014 22:15:59.999 18948 */ 18949 function endOfMinute(dirtyDate) { 18950 requiredArgs(1, arguments);
vendor: 4,698 bytes, lines 18951-19089
18951 var date = toDate(dirtyDate); 18952 date.setSeconds(59, 999); 18953 return date; 18954 } 18955 18956 /** 18957 * @name endOfQuarter 18958 * @category Quarter Helpers 18959 * @summary Return the end of a year quarter for the given date. 18960 * 18961 * @description 18962 * Return the end of a year quarter for the given date. 18963 * The result will be in the local timezone. 18964 * 18965 * @param {Date|Number} date - the original date 18966 * @returns {Date} the end of a quarter 18967 * @throws {TypeError} 1 argument required 18968 * 18969 * @example 18970 * // The end of a quarter for 2 September 2014 11:55:00: 18971 * const result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) 18972 * //=> Tue Sep 30 2014 23:59:59.999 18973 */ 18974 function endOfQuarter(dirtyDate) { 18975 requiredArgs(1, arguments); 18976 var date = toDate(dirtyDate); 18977 var currentMonth = date.getMonth(); 18978 var month = currentMonth - currentMonth % 3 + 3; 18979 date.setMonth(month, 0); 18980 date.setHours(23, 59, 59, 999); 18981 return date; 18982 } 18983 18984 /** 18985 * @name endOfSecond 18986 * @category Second Helpers 18987 * @summary Return the end of a second for the given date. 18988 * 18989 * @description 18990 * Return the end of a second for the given date. 18991 * The result will be in the local timezone. 18992 * 18993 * @param {Date|Number} date - the original date 18994 * @returns {Date} the end of a second 18995 * @throws {TypeError} 1 argument required 18996 * 18997 * @example 18998 * // The end of a second for 1 December 2014 22:15:45.400: 18999 * const result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) 19000 * //=> Mon Dec 01 2014 22:15:45.999 19001 */ 19002 function endOfSecond(dirtyDate) { 19003 requiredArgs(1, arguments); 19004 var date = toDate(dirtyDate); 19005 date.setMilliseconds(999); 19006 return date; 19007 } 19008 19009 /** 19010 * @name subMilliseconds 19011 * @category Millisecond Helpers 19012 * @summary Subtract the specified number of milliseconds from the given date. 19013 * 19014 * @description 19015 * Subtract the specified number of milliseconds from the given date. 19016 * 19017 * @param {Date|Number} date - the date to be changed 19018 * @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. 19019 * @returns {Date} the new date with the milliseconds subtracted 19020 * @throws {TypeError} 2 arguments required 19021 * 19022 * @example 19023 * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000: 19024 * const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) 19025 * //=> Thu Jul 10 2014 12:45:29.250 19026 */ 19027 function subMilliseconds(dirtyDate, dirtyAmount) { 19028 requiredArgs(2, arguments); 19029 var amount = toInteger(dirtyAmount); 19030 return addMilliseconds(dirtyDate, -amount); 19031 } 19032 19033 var MILLISECONDS_IN_DAY = 86400000; 19034 function getUTCDayOfYear(dirtyDate) { 19035 requiredArgs(1, arguments); 19036 var date = toDate(dirtyDate); 19037 var timestamp = date.getTime(); 19038 date.setUTCMonth(0, 1); 19039 date.setUTCHours(0, 0, 0, 0); 19040 var startOfYearTimestamp = date.getTime(); 19041 var difference = timestamp - startOfYearTimestamp; 19042 return Math.floor(difference / MILLISECONDS_IN_DAY) + 1; 19043 } 19044 19045 function startOfUTCISOWeek(dirtyDate) { 19046 requiredArgs(1, arguments); 19047 var weekStartsOn = 1; 19048 var date = toDate(dirtyDate); 19049 var day = date.getUTCDay(); 19050 var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; 19051 date.setUTCDate(date.getUTCDate() - diff); 19052 date.setUTCHours(0, 0, 0, 0); 19053 return date; 19054 } 19055 19056 function getUTCISOWeekYear(dirtyDate) { 19057 requiredArgs(1, arguments); 19058 var date = toDate(dirtyDate); 19059 var year = date.getUTCFullYear(); 19060 var fourthOfJanuaryOfNextYear = new Date(0); 19061 fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4); 19062 fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0); 19063 var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear); 19064 var fourthOfJanuaryOfThisYear = new Date(0); 19065 fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4); 19066 fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0); 19067 var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear); 19068 if (date.getTime() >= startOfNextYear.getTime()) { 19069 return year + 1; 19070 } else if (date.getTime() >= startOfThisYear.getTime()) { 19071 return year; 19072 } else { 19073 return year - 1; 19074 } 19075 } 19076 19077 function startOfUTCISOWeekYear(dirtyDate) { 19078 requiredArgs(1, arguments); 19079 var year = getUTCISOWeekYear(dirtyDate); 19080 var fourthOfJanuary = new Date(0); 19081 fourthOfJanuary.setUTCFullYear(year, 0, 4); 19082 fourthOfJanuary.setUTCHours(0, 0, 0, 0); 19083 var date = startOfUTCISOWeek(fourthOfJanuary); 19084 return date; 19085 } 19086 19087 var MILLISECONDS_IN_WEEK$1 = 604800000; 19088 function getUTCISOWeek(dirtyDate) { 19089 requiredArgs(1, arguments);
vendor: 5,797 bytes, lines 19090-19161
19090 var date = toDate(dirtyDate); 19091 var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); 19092 19093 // Round the number of days to the nearest integer 19094 // because the number of milliseconds in a week is not constant 19095 // (e.g. it's different in the week of the daylight saving time clock shift) 19096 return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1; 19097 } 19098 19099 function startOfUTCWeek(dirtyDate, options) { 19100 var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; 19101 requiredArgs(1, arguments); 19102 var defaultOptions = getDefaultOptions(); 19103 var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); 19104 19105 // Test if weekStartsOn is between 0 and 6 _and_ is not NaN 19106 if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { 19107 throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); 19108 } 19109 var date = toDate(dirtyDate); 19110 var day = date.getUTCDay(); 19111 var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; 19112 date.setUTCDate(date.getUTCDate() - diff); 19113 date.setUTCHours(0, 0, 0, 0); 19114 return date; 19115 } 19116 19117 function getUTCWeekYear(dirtyDate, options) { 19118 var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; 19119 requiredArgs(1, arguments); 19120 var date = toDate(dirtyDate); 19121 var year = date.getUTCFullYear(); 19122 var defaultOptions = getDefaultOptions(); 19123 var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); 19124 19125 // Test if weekStartsOn is between 1 and 7 _and_ is not NaN 19126 if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { 19127 throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); 19128 } 19129 var firstWeekOfNextYear = new Date(0); 19130 firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate); 19131 firstWeekOfNextYear.setUTCHours(0, 0, 0, 0); 19132 var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options); 19133 var firstWeekOfThisYear = new Date(0); 19134 firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate); 19135 firstWeekOfThisYear.setUTCHours(0, 0, 0, 0); 19136 var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options); 19137 if (date.getTime() >= startOfNextYear.getTime()) { 19138 return year + 1; 19139 } else if (date.getTime() >= startOfThisYear.getTime()) { 19140 return year; 19141 } else { 19142 return year - 1; 19143 } 19144 } 19145 19146 function startOfUTCWeekYear(dirtyDate, options) { 19147 var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; 19148 requiredArgs(1, arguments); 19149 var defaultOptions = getDefaultOptions(); 19150 var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); 19151 var year = getUTCWeekYear(dirtyDate, options); 19152 var firstWeek = new Date(0); 19153 firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate); 19154 firstWeek.setUTCHours(0, 0, 0, 0); 19155 var date = startOfUTCWeek(firstWeek, options); 19156 return date; 19157 } 19158 19159 var MILLISECONDS_IN_WEEK = 604800000; 19160 function getUTCWeek(dirtyDate, options) { 19161 requiredArgs(1, arguments);
vendor: 47,520 bytes, lines 19162-20618
19162 var date = toDate(dirtyDate); 19163 var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime(); 19164 19165 // Round the number of days to the nearest integer 19166 // because the number of milliseconds in a week is not constant 19167 // (e.g. it's different in the week of the daylight saving time clock shift) 19168 return Math.round(diff / MILLISECONDS_IN_WEEK) + 1; 19169 } 19170 19171 function addLeadingZeros(number, targetLength) { 19172 var sign = number < 0 ? '-' : ''; 19173 var output = Math.abs(number).toString(); 19174 while (output.length < targetLength) { 19175 output = '0' + output; 19176 } 19177 return sign + output; 19178 } 19179 19180 /* 19181 * | | Unit | | Unit | 19182 * |-----|--------------------------------|-----|--------------------------------| 19183 * | a | AM, PM | A* | | 19184 * | d | Day of month | D | | 19185 * | h | Hour [1-12] | H | Hour [0-23] | 19186 * | m | Minute | M | Month | 19187 * | s | Second | S | Fraction of second | 19188 * | y | Year (abs) | Y | | 19189 * 19190 * Letters marked by * are not implemented but reserved by Unicode standard. 19191 */ 19192 var formatters$2 = { 19193 // Year 19194 y: function y(date, token) { 19195 // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens 19196 // | Year | y | yy | yyy | yyyy | yyyyy | 19197 // |----------|-------|----|-------|-------|-------| 19198 // | AD 1 | 1 | 01 | 001 | 0001 | 00001 | 19199 // | AD 12 | 12 | 12 | 012 | 0012 | 00012 | 19200 // | AD 123 | 123 | 23 | 123 | 0123 | 00123 | 19201 // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 | 19202 // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 | 19203 19204 var signedYear = date.getUTCFullYear(); 19205 // Returns 1 for 1 BC (which is year 0 in JavaScript) 19206 var year = signedYear > 0 ? signedYear : 1 - signedYear; 19207 return addLeadingZeros(token === 'yy' ? year % 100 : year, token.length); 19208 }, 19209 // Month 19210 M: function M(date, token) { 19211 var month = date.getUTCMonth(); 19212 return token === 'M' ? String(month + 1) : addLeadingZeros(month + 1, 2); 19213 }, 19214 // Day of the month 19215 d: function d(date, token) { 19216 return addLeadingZeros(date.getUTCDate(), token.length); 19217 }, 19218 // AM or PM 19219 a: function a(date, token) { 19220 var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am'; 19221 switch (token) { 19222 case 'a': 19223 case 'aa': 19224 return dayPeriodEnumValue.toUpperCase(); 19225 case 'aaa': 19226 return dayPeriodEnumValue; 19227 case 'aaaaa': 19228 return dayPeriodEnumValue[0]; 19229 case 'aaaa': 19230 default: 19231 return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.'; 19232 } 19233 }, 19234 // Hour [1-12] 19235 h: function h(date, token) { 19236 return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length); 19237 }, 19238 // Hour [0-23] 19239 H: function H(date, token) { 19240 return addLeadingZeros(date.getUTCHours(), token.length); 19241 }, 19242 // Minute 19243 m: function m(date, token) { 19244 return addLeadingZeros(date.getUTCMinutes(), token.length); 19245 }, 19246 // Second 19247 s: function s(date, token) { 19248 return addLeadingZeros(date.getUTCSeconds(), token.length); 19249 }, 19250 // Fraction of second 19251 S: function S(date, token) { 19252 var numberOfDigits = token.length; 19253 var milliseconds = date.getUTCMilliseconds(); 19254 var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3)); 19255 return addLeadingZeros(fractionalSeconds, token.length); 19256 } 19257 }; 19258 var formatters$3 = formatters$2; 19259 19260 var dayPeriodEnum = { 19261 am: 'am', 19262 pm: 'pm', 19263 midnight: 'midnight', 19264 noon: 'noon', 19265 morning: 'morning', 19266 afternoon: 'afternoon', 19267 evening: 'evening', 19268 night: 'night' 19269 }; 19270 /* 19271 * | | Unit | | Unit | 19272 * |-----|--------------------------------|-----|--------------------------------| 19273 * | a | AM, PM | A* | Milliseconds in day | 19274 * | b | AM, PM, noon, midnight | B | Flexible day period | 19275 * | c | Stand-alone local day of week | C* | Localized hour w/ day period | 19276 * | d | Day of month | D | Day of year | 19277 * | e | Local day of week | E | Day of week | 19278 * | f | | F* | Day of week in month | 19279 * | g* | Modified Julian day | G | Era | 19280 * | h | Hour [1-12] | H | Hour [0-23] | 19281 * | i! | ISO day of week | I! | ISO week of year | 19282 * | j* | Localized hour w/ day period | J* | Localized hour w/o day period | 19283 * | k | Hour [1-24] | K | Hour [0-11] | 19284 * | l* | (deprecated) | L | Stand-alone month | 19285 * | m | Minute | M | Month | 19286 * | n | | N | | 19287 * | o! | Ordinal number modifier | O | Timezone (GMT) | 19288 * | p! | Long localized time | P! | Long localized date | 19289 * | q | Stand-alone quarter | Q | Quarter | 19290 * | r* | Related Gregorian year | R! | ISO week-numbering year | 19291 * | s | Second | S | Fraction of second | 19292 * | t! | Seconds timestamp | T! | Milliseconds timestamp | 19293 * | u | Extended year | U* | Cyclic year | 19294 * | v* | Timezone (generic non-locat.) | V* | Timezone (location) | 19295 * | w | Local week of year | W* | Week of month | 19296 * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) | 19297 * | y | Year (abs) | Y | Local week-numbering year | 19298 * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) | 19299 * 19300 * Letters marked by * are not implemented but reserved by Unicode standard. 19301 * 19302 * Letters marked by ! are non-standard, but implemented by date-fns: 19303 * - `o` modifies the previous token to turn it into an ordinal (see `format` docs) 19304 * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days, 19305 * i.e. 7 for Sunday, 1 for Monday, etc. 19306 * - `I` is ISO week of year, as opposed to `w` which is local week of year. 19307 * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year. 19308 * `R` is supposed to be used in conjunction with `I` and `i` 19309 * for universal ISO week-numbering date, whereas 19310 * `Y` is supposed to be used in conjunction with `w` and `e` 19311 * for week-numbering date specific to the locale. 19312 * - `P` is long localized date format 19313 * - `p` is long localized time format 19314 */ 19315 19316 var formatters = { 19317 // Era 19318 G: function G(date, token, localize) { 19319 var era = date.getUTCFullYear() > 0 ? 1 : 0; 19320 switch (token) { 19321 // AD, BC 19322 case 'G': 19323 case 'GG': 19324 case 'GGG': 19325 return localize.era(era, { 19326 width: 'abbreviated' 19327 }); 19328 // A, B 19329 case 'GGGGG': 19330 return localize.era(era, { 19331 width: 'narrow' 19332 }); 19333 // Anno Domini, Before Christ 19334 case 'GGGG': 19335 default: 19336 return localize.era(era, { 19337 width: 'wide' 19338 }); 19339 } 19340 }, 19341 // Year 19342 y: function y(date, token, localize) { 19343 // Ordinal number 19344 if (token === 'yo') { 19345 var signedYear = date.getUTCFullYear(); 19346 // Returns 1 for 1 BC (which is year 0 in JavaScript) 19347 var year = signedYear > 0 ? signedYear : 1 - signedYear; 19348 return localize.ordinalNumber(year, { 19349 unit: 'year' 19350 }); 19351 } 19352 return formatters$3.y(date, token); 19353 }, 19354 // Local week-numbering year 19355 Y: function Y(date, token, localize, options) { 19356 var signedWeekYear = getUTCWeekYear(date, options); 19357 // Returns 1 for 1 BC (which is year 0 in JavaScript) 19358 var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; 19359 19360 // Two digit year 19361 if (token === 'YY') { 19362 var twoDigitYear = weekYear % 100; 19363 return addLeadingZeros(twoDigitYear, 2); 19364 } 19365 19366 // Ordinal number 19367 if (token === 'Yo') { 19368 return localize.ordinalNumber(weekYear, { 19369 unit: 'year' 19370 }); 19371 } 19372 19373 // Padding 19374 return addLeadingZeros(weekYear, token.length); 19375 }, 19376 // ISO week-numbering year 19377 R: function R(date, token) { 19378 var isoWeekYear = getUTCISOWeekYear(date); 19379 19380 // Padding 19381 return addLeadingZeros(isoWeekYear, token.length); 19382 }, 19383 // Extended year. This is a single number designating the year of this calendar system. 19384 // The main difference between `y` and `u` localizers are B.C. years: 19385 // | Year | `y` | `u` | 19386 // |------|-----|-----| 19387 // | AC 1 | 1 | 1 | 19388 // | BC 1 | 1 | 0 | 19389 // | BC 2 | 2 | -1 | 19390 // Also `yy` always returns the last two digits of a year, 19391 // while `uu` pads single digit years to 2 characters and returns other years unchanged. 19392 u: function u(date, token) { 19393 var year = date.getUTCFullYear(); 19394 return addLeadingZeros(year, token.length); 19395 }, 19396 // Quarter 19397 Q: function Q(date, token, localize) { 19398 var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); 19399 switch (token) { 19400 // 1, 2, 3, 4 19401 case 'Q': 19402 return String(quarter); 19403 // 01, 02, 03, 04 19404 case 'QQ': 19405 return addLeadingZeros(quarter, 2); 19406 // 1st, 2nd, 3rd, 4th 19407 case 'Qo': 19408 return localize.ordinalNumber(quarter, { 19409 unit: 'quarter' 19410 }); 19411 // Q1, Q2, Q3, Q4 19412 case 'QQQ': 19413 return localize.quarter(quarter, { 19414 width: 'abbreviated', 19415 context: 'formatting' 19416 }); 19417 // 1, 2, 3, 4 (narrow quarter; could be not numerical) 19418 case 'QQQQQ': 19419 return localize.quarter(quarter, { 19420 width: 'narrow', 19421 context: 'formatting' 19422 }); 19423 // 1st quarter, 2nd quarter, ... 19424 case 'QQQQ': 19425 default: 19426 return localize.quarter(quarter, { 19427 width: 'wide', 19428 context: 'formatting' 19429 }); 19430 } 19431 }, 19432 // Stand-alone quarter 19433 q: function q(date, token, localize) { 19434 var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); 19435 switch (token) { 19436 // 1, 2, 3, 4 19437 case 'q': 19438 return String(quarter); 19439 // 01, 02, 03, 04 19440 case 'qq': 19441 return addLeadingZeros(quarter, 2); 19442 // 1st, 2nd, 3rd, 4th 19443 case 'qo': 19444 return localize.ordinalNumber(quarter, { 19445 unit: 'quarter' 19446 }); 19447 // Q1, Q2, Q3, Q4 19448 case 'qqq': 19449 return localize.quarter(quarter, { 19450 width: 'abbreviated', 19451 context: 'standalone' 19452 }); 19453 // 1, 2, 3, 4 (narrow quarter; could be not numerical) 19454 case 'qqqqq': 19455 return localize.quarter(quarter, { 19456 width: 'narrow', 19457 context: 'standalone' 19458 }); 19459 // 1st quarter, 2nd quarter, ... 19460 case 'qqqq': 19461 default: 19462 return localize.quarter(quarter, { 19463 width: 'wide', 19464 context: 'standalone' 19465 }); 19466 } 19467 }, 19468 // Month 19469 M: function M(date, token, localize) { 19470 var month = date.getUTCMonth(); 19471 switch (token) { 19472 case 'M': 19473 case 'MM': 19474 return formatters$3.M(date, token); 19475 // 1st, 2nd, ..., 12th 19476 case 'Mo': 19477 return localize.ordinalNumber(month + 1, { 19478 unit: 'month' 19479 }); 19480 // Jan, Feb, ..., Dec 19481 case 'MMM': 19482 return localize.month(month, { 19483 width: 'abbreviated', 19484 context: 'formatting' 19485 }); 19486 // J, F, ..., D 19487 case 'MMMMM': 19488 return localize.month(month, { 19489 width: 'narrow', 19490 context: 'formatting' 19491 }); 19492 // January, February, ..., December 19493 case 'MMMM': 19494 default: 19495 return localize.month(month, { 19496 width: 'wide', 19497 context: 'formatting' 19498 }); 19499 } 19500 }, 19501 // Stand-alone month 19502 L: function L(date, token, localize) { 19503 var month = date.getUTCMonth(); 19504 switch (token) { 19505 // 1, 2, ..., 12 19506 case 'L': 19507 return String(month + 1); 19508 // 01, 02, ..., 12 19509 case 'LL': 19510 return addLeadingZeros(month + 1, 2); 19511 // 1st, 2nd, ..., 12th 19512 case 'Lo': 19513 return localize.ordinalNumber(month + 1, { 19514 unit: 'month' 19515 }); 19516 // Jan, Feb, ..., Dec 19517 case 'LLL': 19518 return localize.month(month, { 19519 width: 'abbreviated', 19520 context: 'standalone' 19521 }); 19522 // J, F, ..., D 19523 case 'LLLLL': 19524 return localize.month(month, { 19525 width: 'narrow', 19526 context: 'standalone' 19527 }); 19528 // January, February, ..., December 19529 case 'LLLL': 19530 default: 19531 return localize.month(month, { 19532 width: 'wide', 19533 context: 'standalone' 19534 }); 19535 } 19536 }, 19537 // Local week of year 19538 w: function w(date, token, localize, options) { 19539 var week = getUTCWeek(date, options); 19540 if (token === 'wo') { 19541 return localize.ordinalNumber(week, { 19542 unit: 'week' 19543 }); 19544 } 19545 return addLeadingZeros(week, token.length); 19546 }, 19547 // ISO week of year 19548 I: function I(date, token, localize) { 19549 var isoWeek = getUTCISOWeek(date); 19550 if (token === 'Io') { 19551 return localize.ordinalNumber(isoWeek, { 19552 unit: 'week' 19553 }); 19554 } 19555 return addLeadingZeros(isoWeek, token.length); 19556 }, 19557 // Day of the month 19558 d: function d(date, token, localize) { 19559 if (token === 'do') { 19560 return localize.ordinalNumber(date.getUTCDate(), { 19561 unit: 'date' 19562 }); 19563 } 19564 return formatters$3.d(date, token); 19565 }, 19566 // Day of year 19567 D: function D(date, token, localize) { 19568 var dayOfYear = getUTCDayOfYear(date); 19569 if (token === 'Do') { 19570 return localize.ordinalNumber(dayOfYear, { 19571 unit: 'dayOfYear' 19572 }); 19573 } 19574 return addLeadingZeros(dayOfYear, token.length); 19575 }, 19576 // Day of week 19577 E: function E(date, token, localize) { 19578 var dayOfWeek = date.getUTCDay(); 19579 switch (token) { 19580 // Tue 19581 case 'E': 19582 case 'EE': 19583 case 'EEE': 19584 return localize.day(dayOfWeek, { 19585 width: 'abbreviated', 19586 context: 'formatting' 19587 }); 19588 // T 19589 case 'EEEEE': 19590 return localize.day(dayOfWeek, { 19591 width: 'narrow', 19592 context: 'formatting' 19593 }); 19594 // Tu 19595 case 'EEEEEE': 19596 return localize.day(dayOfWeek, { 19597 width: 'short', 19598 context: 'formatting' 19599 }); 19600 // Tuesday 19601 case 'EEEE': 19602 default: 19603 return localize.day(dayOfWeek, { 19604 width: 'wide', 19605 context: 'formatting' 19606 }); 19607 } 19608 }, 19609 // Local day of week 19610 e: function e(date, token, localize, options) { 19611 var dayOfWeek = date.getUTCDay(); 19612 var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7; 19613 switch (token) { 19614 // Numerical value (Nth day of week with current locale or weekStartsOn) 19615 case 'e': 19616 return String(localDayOfWeek); 19617 // Padded numerical value 19618 case 'ee': 19619 return addLeadingZeros(localDayOfWeek, 2); 19620 // 1st, 2nd, ..., 7th 19621 case 'eo': 19622 return localize.ordinalNumber(localDayOfWeek, { 19623 unit: 'day' 19624 }); 19625 case 'eee': 19626 return localize.day(dayOfWeek, { 19627 width: 'abbreviated', 19628 context: 'formatting' 19629 }); 19630 // T 19631 case 'eeeee': 19632 return localize.day(dayOfWeek, { 19633 width: 'narrow', 19634 context: 'formatting' 19635 }); 19636 // Tu 19637 case 'eeeeee': 19638 return localize.day(dayOfWeek, { 19639 width: 'short', 19640 context: 'formatting' 19641 }); 19642 // Tuesday 19643 case 'eeee': 19644 default: 19645 return localize.day(dayOfWeek, { 19646 width: 'wide', 19647 context: 'formatting' 19648 }); 19649 } 19650 }, 19651 // Stand-alone local day of week 19652 c: function c(date, token, localize, options) { 19653 var dayOfWeek = date.getUTCDay(); 19654 var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7; 19655 switch (token) { 19656 // Numerical value (same as in `e`) 19657 case 'c': 19658 return String(localDayOfWeek); 19659 // Padded numerical value 19660 case 'cc': 19661 return addLeadingZeros(localDayOfWeek, token.length); 19662 // 1st, 2nd, ..., 7th 19663 case 'co': 19664 return localize.ordinalNumber(localDayOfWeek, { 19665 unit: 'day' 19666 }); 19667 case 'ccc': 19668 return localize.day(dayOfWeek, { 19669 width: 'abbreviated', 19670 context: 'standalone' 19671 }); 19672 // T 19673 case 'ccccc': 19674 return localize.day(dayOfWeek, { 19675 width: 'narrow', 19676 context: 'standalone' 19677 }); 19678 // Tu 19679 case 'cccccc': 19680 return localize.day(dayOfWeek, { 19681 width: 'short', 19682 context: 'standalone' 19683 }); 19684 // Tuesday 19685 case 'cccc': 19686 default: 19687 return localize.day(dayOfWeek, { 19688 width: 'wide', 19689 context: 'standalone' 19690 }); 19691 } 19692 }, 19693 // ISO day of week 19694 i: function i(date, token, localize) { 19695 var dayOfWeek = date.getUTCDay(); 19696 var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek; 19697 switch (token) { 19698 // 2 19699 case 'i': 19700 return String(isoDayOfWeek); 19701 // 02 19702 case 'ii': 19703 return addLeadingZeros(isoDayOfWeek, token.length); 19704 // 2nd 19705 case 'io': 19706 return localize.ordinalNumber(isoDayOfWeek, { 19707 unit: 'day' 19708 }); 19709 // Tue 19710 case 'iii': 19711 return localize.day(dayOfWeek, { 19712 width: 'abbreviated', 19713 context: 'formatting' 19714 }); 19715 // T 19716 case 'iiiii': 19717 return localize.day(dayOfWeek, { 19718 width: 'narrow', 19719 context: 'formatting' 19720 }); 19721 // Tu 19722 case 'iiiiii': 19723 return localize.day(dayOfWeek, { 19724 width: 'short', 19725 context: 'formatting' 19726 }); 19727 // Tuesday 19728 case 'iiii': 19729 default: 19730 return localize.day(dayOfWeek, { 19731 width: 'wide', 19732 context: 'formatting' 19733 }); 19734 } 19735 }, 19736 // AM or PM 19737 a: function a(date, token, localize) { 19738 var hours = date.getUTCHours(); 19739 var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am'; 19740 switch (token) { 19741 case 'a': 19742 case 'aa': 19743 return localize.dayPeriod(dayPeriodEnumValue, { 19744 width: 'abbreviated', 19745 context: 'formatting' 19746 }); 19747 case 'aaa': 19748 return localize.dayPeriod(dayPeriodEnumValue, { 19749 width: 'abbreviated', 19750 context: 'formatting' 19751 }).toLowerCase(); 19752 case 'aaaaa': 19753 return localize.dayPeriod(dayPeriodEnumValue, { 19754 width: 'narrow', 19755 context: 'formatting' 19756 }); 19757 case 'aaaa': 19758 default: 19759 return localize.dayPeriod(dayPeriodEnumValue, { 19760 width: 'wide', 19761 context: 'formatting' 19762 }); 19763 } 19764 }, 19765 // AM, PM, midnight, noon 19766 b: function b(date, token, localize) { 19767 var hours = date.getUTCHours(); 19768 var dayPeriodEnumValue; 19769 if (hours === 12) { 19770 dayPeriodEnumValue = dayPeriodEnum.noon; 19771 } else if (hours === 0) { 19772 dayPeriodEnumValue = dayPeriodEnum.midnight; 19773 } else { 19774 dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am'; 19775 } 19776 switch (token) { 19777 case 'b': 19778 case 'bb': 19779 return localize.dayPeriod(dayPeriodEnumValue, { 19780 width: 'abbreviated', 19781 context: 'formatting' 19782 }); 19783 case 'bbb': 19784 return localize.dayPeriod(dayPeriodEnumValue, { 19785 width: 'abbreviated', 19786 context: 'formatting' 19787 }).toLowerCase(); 19788 case 'bbbbb': 19789 return localize.dayPeriod(dayPeriodEnumValue, { 19790 width: 'narrow', 19791 context: 'formatting' 19792 }); 19793 case 'bbbb': 19794 default: 19795 return localize.dayPeriod(dayPeriodEnumValue, { 19796 width: 'wide', 19797 context: 'formatting' 19798 }); 19799 } 19800 }, 19801 // in the morning, in the afternoon, in the evening, at night 19802 B: function B(date, token, localize) { 19803 var hours = date.getUTCHours(); 19804 var dayPeriodEnumValue; 19805 if (hours >= 17) { 19806 dayPeriodEnumValue = dayPeriodEnum.evening; 19807 } else if (hours >= 12) { 19808 dayPeriodEnumValue = dayPeriodEnum.afternoon; 19809 } else if (hours >= 4) { 19810 dayPeriodEnumValue = dayPeriodEnum.morning; 19811 } else { 19812 dayPeriodEnumValue = dayPeriodEnum.night; 19813 } 19814 switch (token) { 19815 case 'B': 19816 case 'BB': 19817 case 'BBB': 19818 return localize.dayPeriod(dayPeriodEnumValue, { 19819 width: 'abbreviated', 19820 context: 'formatting' 19821 }); 19822 case 'BBBBB': 19823 return localize.dayPeriod(dayPeriodEnumValue, { 19824 width: 'narrow', 19825 context: 'formatting' 19826 }); 19827 case 'BBBB': 19828 default: 19829 return localize.dayPeriod(dayPeriodEnumValue, { 19830 width: 'wide', 19831 context: 'formatting' 19832 }); 19833 } 19834 }, 19835 // Hour [1-12] 19836 h: function h(date, token, localize) { 19837 if (token === 'ho') { 19838 var hours = date.getUTCHours() % 12; 19839 if (hours === 0) hours = 12; 19840 return localize.ordinalNumber(hours, { 19841 unit: 'hour' 19842 }); 19843 } 19844 return formatters$3.h(date, token); 19845 }, 19846 // Hour [0-23] 19847 H: function H(date, token, localize) { 19848 if (token === 'Ho') { 19849 return localize.ordinalNumber(date.getUTCHours(), { 19850 unit: 'hour' 19851 }); 19852 } 19853 return formatters$3.H(date, token); 19854 }, 19855 // Hour [0-11] 19856 K: function K(date, token, localize) { 19857 var hours = date.getUTCHours() % 12; 19858 if (token === 'Ko') { 19859 return localize.ordinalNumber(hours, { 19860 unit: 'hour' 19861 }); 19862 } 19863 return addLeadingZeros(hours, token.length); 19864 }, 19865 // Hour [1-24] 19866 k: function k(date, token, localize) { 19867 var hours = date.getUTCHours(); 19868 if (hours === 0) hours = 24; 19869 if (token === 'ko') { 19870 return localize.ordinalNumber(hours, { 19871 unit: 'hour' 19872 }); 19873 } 19874 return addLeadingZeros(hours, token.length); 19875 }, 19876 // Minute 19877 m: function m(date, token, localize) { 19878 if (token === 'mo') { 19879 return localize.ordinalNumber(date.getUTCMinutes(), { 19880 unit: 'minute' 19881 }); 19882 } 19883 return formatters$3.m(date, token); 19884 }, 19885 // Second 19886 s: function s(date, token, localize) { 19887 if (token === 'so') { 19888 return localize.ordinalNumber(date.getUTCSeconds(), { 19889 unit: 'second' 19890 }); 19891 } 19892 return formatters$3.s(date, token); 19893 }, 19894 // Fraction of second 19895 S: function S(date, token) { 19896 return formatters$3.S(date, token); 19897 }, 19898 // Timezone (ISO-8601. If offset is 0, output is always `'Z'`) 19899 X: function X(date, token, _localize, options) { 19900 var originalDate = options._originalDate || date; 19901 var timezoneOffset = originalDate.getTimezoneOffset(); 19902 if (timezoneOffset === 0) { 19903 return 'Z'; 19904 } 19905 switch (token) { 19906 // Hours and optional minutes 19907 case 'X': 19908 return formatTimezoneWithOptionalMinutes(timezoneOffset); 19909 19910 // Hours, minutes and optional seconds without `:` delimiter 19911 // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets 19912 // so this token always has the same output as `XX` 19913 case 'XXXX': 19914 case 'XX': 19915 // Hours and minutes without `:` delimiter 19916 return formatTimezone(timezoneOffset); 19917 19918 // Hours, minutes and optional seconds with `:` delimiter 19919 // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets 19920 // so this token always has the same output as `XXX` 19921 case 'XXXXX': 19922 case 'XXX': // Hours and minutes with `:` delimiter 19923 default: 19924 return formatTimezone(timezoneOffset, ':'); 19925 } 19926 }, 19927 // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent) 19928 x: function x(date, token, _localize, options) { 19929 var originalDate = options._originalDate || date; 19930 var timezoneOffset = originalDate.getTimezoneOffset(); 19931 switch (token) { 19932 // Hours and optional minutes 19933 case 'x': 19934 return formatTimezoneWithOptionalMinutes(timezoneOffset); 19935 19936 // Hours, minutes and optional seconds without `:` delimiter 19937 // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets 19938 // so this token always has the same output as `xx` 19939 case 'xxxx': 19940 case 'xx': 19941 // Hours and minutes without `:` delimiter 19942 return formatTimezone(timezoneOffset); 19943 19944 // Hours, minutes and optional seconds with `:` delimiter 19945 // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets 19946 // so this token always has the same output as `xxx` 19947 case 'xxxxx': 19948 case 'xxx': // Hours and minutes with `:` delimiter 19949 default: 19950 return formatTimezone(timezoneOffset, ':'); 19951 } 19952 }, 19953 // Timezone (GMT) 19954 O: function O(date, token, _localize, options) { 19955 var originalDate = options._originalDate || date; 19956 var timezoneOffset = originalDate.getTimezoneOffset(); 19957 switch (token) { 19958 // Short 19959 case 'O': 19960 case 'OO': 19961 case 'OOO': 19962 return 'GMT' + formatTimezoneShort(timezoneOffset, ':'); 19963 // Long 19964 case 'OOOO': 19965 default: 19966 return 'GMT' + formatTimezone(timezoneOffset, ':'); 19967 } 19968 }, 19969 // Timezone (specific non-location) 19970 z: function z(date, token, _localize, options) { 19971 var originalDate = options._originalDate || date; 19972 var timezoneOffset = originalDate.getTimezoneOffset(); 19973 switch (token) { 19974 // Short 19975 case 'z': 19976 case 'zz': 19977 case 'zzz': 19978 return 'GMT' + formatTimezoneShort(timezoneOffset, ':'); 19979 // Long 19980 case 'zzzz': 19981 default: 19982 return 'GMT' + formatTimezone(timezoneOffset, ':'); 19983 } 19984 }, 19985 // Seconds timestamp 19986 t: function t(date, token, _localize, options) { 19987 var originalDate = options._originalDate || date; 19988 var timestamp = Math.floor(originalDate.getTime() / 1000); 19989 return addLeadingZeros(timestamp, token.length); 19990 }, 19991 // Milliseconds timestamp 19992 T: function T(date, token, _localize, options) { 19993 var originalDate = options._originalDate || date; 19994 var timestamp = originalDate.getTime(); 19995 return addLeadingZeros(timestamp, token.length); 19996 } 19997 }; 19998 function formatTimezoneShort(offset, dirtyDelimiter) { 19999 var sign = offset > 0 ? '-' : '+'; 20000 var absOffset = Math.abs(offset); 20001 var hours = Math.floor(absOffset / 60); 20002 var minutes = absOffset % 60; 20003 if (minutes === 0) { 20004 return sign + String(hours); 20005 } 20006 var delimiter = dirtyDelimiter || ''; 20007 return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2); 20008 } 20009 function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) { 20010 if (offset % 60 === 0) { 20011 var sign = offset > 0 ? '-' : '+'; 20012 return sign + addLeadingZeros(Math.abs(offset) / 60, 2); 20013 } 20014 return formatTimezone(offset, dirtyDelimiter); 20015 } 20016 function formatTimezone(offset, dirtyDelimiter) { 20017 var delimiter = dirtyDelimiter || ''; 20018 var sign = offset > 0 ? '-' : '+'; 20019 var absOffset = Math.abs(offset); 20020 var hours = addLeadingZeros(Math.floor(absOffset / 60), 2); 20021 var minutes = addLeadingZeros(absOffset % 60, 2); 20022 return sign + hours + delimiter + minutes; 20023 } 20024 var formatters$1 = formatters; 20025 20026 var dateLongFormatter = function dateLongFormatter(pattern, formatLong) { 20027 switch (pattern) { 20028 case 'P': 20029 return formatLong.date({ 20030 width: 'short' 20031 }); 20032 case 'PP': 20033 return formatLong.date({ 20034 width: 'medium' 20035 }); 20036 case 'PPP': 20037 return formatLong.date({ 20038 width: 'long' 20039 }); 20040 case 'PPPP': 20041 default: 20042 return formatLong.date({ 20043 width: 'full' 20044 }); 20045 } 20046 }; 20047 var timeLongFormatter = function timeLongFormatter(pattern, formatLong) { 20048 switch (pattern) { 20049 case 'p': 20050 return formatLong.time({ 20051 width: 'short' 20052 }); 20053 case 'pp': 20054 return formatLong.time({ 20055 width: 'medium' 20056 }); 20057 case 'ppp': 20058 return formatLong.time({ 20059 width: 'long' 20060 }); 20061 case 'pppp': 20062 default: 20063 return formatLong.time({ 20064 width: 'full' 20065 }); 20066 } 20067 }; 20068 var dateTimeLongFormatter = function dateTimeLongFormatter(pattern, formatLong) { 20069 var matchResult = pattern.match(/(P+)(p+)?/) || []; 20070 var datePattern = matchResult[1]; 20071 var timePattern = matchResult[2]; 20072 if (!timePattern) { 20073 return dateLongFormatter(pattern, formatLong); 20074 } 20075 var dateTimeFormat; 20076 switch (datePattern) { 20077 case 'P': 20078 dateTimeFormat = formatLong.dateTime({ 20079 width: 'short' 20080 }); 20081 break; 20082 case 'PP': 20083 dateTimeFormat = formatLong.dateTime({ 20084 width: 'medium' 20085 }); 20086 break; 20087 case 'PPP': 20088 dateTimeFormat = formatLong.dateTime({ 20089 width: 'long' 20090 }); 20091 break; 20092 case 'PPPP': 20093 default: 20094 dateTimeFormat = formatLong.dateTime({ 20095 width: 'full' 20096 }); 20097 break; 20098 } 20099 return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong)); 20100 }; 20101 var longFormatters = { 20102 p: timeLongFormatter, 20103 P: dateTimeLongFormatter 20104 }; 20105 var longFormatters$1 = longFormatters; 20106 20107 var protectedDayOfYearTokens = ['D', 'DD']; 20108 var protectedWeekYearTokens = ['YY', 'YYYY']; 20109 function isProtectedDayOfYearToken(token) { 20110 return protectedDayOfYearTokens.indexOf(token) !== -1; 20111 } 20112 function isProtectedWeekYearToken(token) { 20113 return protectedWeekYearTokens.indexOf(token) !== -1; 20114 } 20115 function throwProtectedError(token, format, input) { 20116 if (token === 'YYYY') { 20117 throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); 20118 } else if (token === 'YY') { 20119 throw new RangeError("Use `yy` instead of `YY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); 20120 } else if (token === 'D') { 20121 throw new RangeError("Use `d` instead of `D` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); 20122 } else if (token === 'DD') { 20123 throw new RangeError("Use `dd` instead of `DD` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); 20124 } 20125 } 20126 20127 var formatDistanceLocale = { 20128 lessThanXSeconds: { 20129 one: 'less than a second', 20130 other: 'less than {{count}} seconds' 20131 }, 20132 xSeconds: { 20133 one: '1 second', 20134 other: '{{count}} seconds' 20135 }, 20136 halfAMinute: 'half a minute', 20137 lessThanXMinutes: { 20138 one: 'less than a minute', 20139 other: 'less than {{count}} minutes' 20140 }, 20141 xMinutes: { 20142 one: '1 minute', 20143 other: '{{count}} minutes' 20144 }, 20145 aboutXHours: { 20146 one: 'about 1 hour', 20147 other: 'about {{count}} hours' 20148 }, 20149 xHours: { 20150 one: '1 hour', 20151 other: '{{count}} hours' 20152 }, 20153 xDays: { 20154 one: '1 day', 20155 other: '{{count}} days' 20156 }, 20157 aboutXWeeks: { 20158 one: 'about 1 week', 20159 other: 'about {{count}} weeks' 20160 }, 20161 xWeeks: { 20162 one: '1 week', 20163 other: '{{count}} weeks' 20164 }, 20165 aboutXMonths: { 20166 one: 'about 1 month', 20167 other: 'about {{count}} months' 20168 }, 20169 xMonths: { 20170 one: '1 month', 20171 other: '{{count}} months' 20172 }, 20173 aboutXYears: { 20174 one: 'about 1 year', 20175 other: 'about {{count}} years' 20176 }, 20177 xYears: { 20178 one: '1 year', 20179 other: '{{count}} years' 20180 }, 20181 overXYears: { 20182 one: 'over 1 year', 20183 other: 'over {{count}} years' 20184 }, 20185 almostXYears: { 20186 one: 'almost 1 year', 20187 other: 'almost {{count}} years' 20188 } 20189 }; 20190 var formatDistance = function formatDistance(token, count, options) { 20191 var result; 20192 var tokenValue = formatDistanceLocale[token]; 20193 if (typeof tokenValue === 'string') { 20194 result = tokenValue; 20195 } else if (count === 1) { 20196 result = tokenValue.one; 20197 } else { 20198 result = tokenValue.other.replace('{{count}}', count.toString()); 20199 } 20200 if (options !== null && options !== void 0 && options.addSuffix) { 20201 if (options.comparison && options.comparison > 0) { 20202 return 'in ' + result; 20203 } else { 20204 return result + ' ago'; 20205 } 20206 } 20207 return result; 20208 }; 20209 var formatDistance$1 = formatDistance; 20210 20211 function buildFormatLongFn(args) { 20212 return function () { 20213 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 20214 // TODO: Remove String() 20215 var width = options.width ? String(options.width) : args.defaultWidth; 20216 var format = args.formats[width] || args.formats[args.defaultWidth]; 20217 return format; 20218 }; 20219 } 20220 20221 var dateFormats = { 20222 full: 'EEEE, MMMM do, y', 20223 "long": 'MMMM do, y', 20224 medium: 'MMM d, y', 20225 "short": 'MM/dd/yyyy' 20226 }; 20227 var timeFormats = { 20228 full: 'h:mm:ss a zzzz', 20229 "long": 'h:mm:ss a z', 20230 medium: 'h:mm:ss a', 20231 "short": 'h:mm a' 20232 }; 20233 var dateTimeFormats = { 20234 full: "{{date}} 'at' {{time}}", 20235 "long": "{{date}} 'at' {{time}}", 20236 medium: '{{date}}, {{time}}', 20237 "short": '{{date}}, {{time}}' 20238 }; 20239 var formatLong = { 20240 date: buildFormatLongFn({ 20241 formats: dateFormats, 20242 defaultWidth: 'full' 20243 }), 20244 time: buildFormatLongFn({ 20245 formats: timeFormats, 20246 defaultWidth: 'full' 20247 }), 20248 dateTime: buildFormatLongFn({ 20249 formats: dateTimeFormats, 20250 defaultWidth: 'full' 20251 }) 20252 }; 20253 var formatLong$1 = formatLong; 20254 20255 var formatRelativeLocale = { 20256 lastWeek: "'last' eeee 'at' p", 20257 yesterday: "'yesterday at' p", 20258 today: "'today at' p", 20259 tomorrow: "'tomorrow at' p", 20260 nextWeek: "eeee 'at' p", 20261 other: 'P' 20262 }; 20263 var formatRelative = function formatRelative(token, _date, _baseDate, _options) { 20264 return formatRelativeLocale[token]; 20265 }; 20266 var formatRelative$1 = formatRelative; 20267 20268 function buildLocalizeFn(args) { 20269 return function (dirtyIndex, options) { 20270 var context = options !== null && options !== void 0 && options.context ? String(options.context) : 'standalone'; 20271 var valuesArray; 20272 if (context === 'formatting' && args.formattingValues) { 20273 var defaultWidth = args.defaultFormattingWidth || args.defaultWidth; 20274 var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth; 20275 valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth]; 20276 } else { 20277 var _defaultWidth = args.defaultWidth; 20278 var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth; 20279 valuesArray = args.values[_width] || args.values[_defaultWidth]; 20280 } 20281 var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; 20282 // @ts-ignore: For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it! 20283 return valuesArray[index]; 20284 }; 20285 } 20286 20287 var eraValues = { 20288 narrow: ['B', 'A'], 20289 abbreviated: ['BC', 'AD'], 20290 wide: ['Before Christ', 'Anno Domini'] 20291 }; 20292 var quarterValues = { 20293 narrow: ['1', '2', '3', '4'], 20294 abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'], 20295 wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter'] 20296 }; 20297 20298 // Note: in English, the names of days of the week and months are capitalized. 20299 // If you are making a new locale based on this one, check if the same is true for the language you're working on. 20300 // Generally, formatted dates should look like they are in the middle of a sentence, 20301 // e.g. in Spanish language the weekdays and months should be in the lowercase. 20302 var monthValues = { 20303 narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], 20304 abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], 20305 wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] 20306 }; 20307 var dayValues = { 20308 narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'], 20309 "short": ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], 20310 abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], 20311 wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] 20312 }; 20313 var dayPeriodValues = { 20314 narrow: { 20315 am: 'a', 20316 pm: 'p', 20317 midnight: 'mi', 20318 noon: 'n', 20319 morning: 'morning', 20320 afternoon: 'afternoon', 20321 evening: 'evening', 20322 night: 'night' 20323 }, 20324 abbreviated: { 20325 am: 'AM', 20326 pm: 'PM', 20327 midnight: 'midnight', 20328 noon: 'noon', 20329 morning: 'morning', 20330 afternoon: 'afternoon', 20331 evening: 'evening', 20332 night: 'night' 20333 }, 20334 wide: { 20335 am: 'a.m.', 20336 pm: 'p.m.', 20337 midnight: 'midnight', 20338 noon: 'noon', 20339 morning: 'morning', 20340 afternoon: 'afternoon', 20341 evening: 'evening', 20342 night: 'night' 20343 } 20344 }; 20345 var formattingDayPeriodValues = { 20346 narrow: { 20347 am: 'a', 20348 pm: 'p', 20349 midnight: 'mi', 20350 noon: 'n', 20351 morning: 'in the morning', 20352 afternoon: 'in the afternoon', 20353 evening: 'in the evening', 20354 night: 'at night' 20355 }, 20356 abbreviated: { 20357 am: 'AM', 20358 pm: 'PM', 20359 midnight: 'midnight', 20360 noon: 'noon', 20361 morning: 'in the morning', 20362 afternoon: 'in the afternoon', 20363 evening: 'in the evening', 20364 night: 'at night' 20365 }, 20366 wide: { 20367 am: 'a.m.', 20368 pm: 'p.m.', 20369 midnight: 'midnight', 20370 noon: 'noon', 20371 morning: 'in the morning', 20372 afternoon: 'in the afternoon', 20373 evening: 'in the evening', 20374 night: 'at night' 20375 } 20376 }; 20377 var ordinalNumber = function ordinalNumber(dirtyNumber, _options) { 20378 var number = Number(dirtyNumber); 20379 20380 // If ordinal numbers depend on context, for example, 20381 // if they are different for different grammatical genders, 20382 // use `options.unit`. 20383 // 20384 // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear', 20385 // 'day', 'hour', 'minute', 'second'. 20386 20387 var rem100 = number % 100; 20388 if (rem100 > 20 || rem100 < 10) { 20389 switch (rem100 % 10) { 20390 case 1: 20391 return number + 'st'; 20392 case 2: 20393 return number + 'nd'; 20394 case 3: 20395 return number + 'rd'; 20396 } 20397 } 20398 return number + 'th'; 20399 }; 20400 var localize = { 20401 ordinalNumber: ordinalNumber, 20402 era: buildLocalizeFn({ 20403 values: eraValues, 20404 defaultWidth: 'wide' 20405 }), 20406 quarter: buildLocalizeFn({ 20407 values: quarterValues, 20408 defaultWidth: 'wide', 20409 argumentCallback: function argumentCallback(quarter) { 20410 return quarter - 1; 20411 } 20412 }), 20413 month: buildLocalizeFn({ 20414 values: monthValues, 20415 defaultWidth: 'wide' 20416 }), 20417 day: buildLocalizeFn({ 20418 values: dayValues, 20419 defaultWidth: 'wide' 20420 }), 20421 dayPeriod: buildLocalizeFn({ 20422 values: dayPeriodValues, 20423 defaultWidth: 'wide', 20424 formattingValues: formattingDayPeriodValues, 20425 defaultFormattingWidth: 'wide' 20426 }) 20427 }; 20428 var localize$1 = localize; 20429 20430 function buildMatchFn(args) { 20431 return function (string) { 20432 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 20433 var width = options.width; 20434 var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth]; 20435 var matchResult = string.match(matchPattern); 20436 if (!matchResult) { 20437 return null; 20438 } 20439 var matchedString = matchResult[0]; 20440 var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth]; 20441 var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function (pattern) { 20442 return pattern.test(matchedString); 20443 }) : findKey(parsePatterns, function (pattern) { 20444 return pattern.test(matchedString); 20445 }); 20446 var value; 20447 value = args.valueCallback ? args.valueCallback(key) : key; 20448 value = options.valueCallback ? options.valueCallback(value) : value; 20449 var rest = string.slice(matchedString.length); 20450 return { 20451 value: value, 20452 rest: rest 20453 }; 20454 }; 20455 } 20456 function findKey(object, predicate) { 20457 for (var key in object) { 20458 if (object.hasOwnProperty(key) && predicate(object[key])) { 20459 return key; 20460 } 20461 } 20462 return undefined; 20463 } 20464 function findIndex(array, predicate) { 20465 for (var key = 0; key < array.length; key++) { 20466 if (predicate(array[key])) { 20467 return key; 20468 } 20469 } 20470 return undefined; 20471 } 20472 20473 function buildMatchPatternFn(args) { 20474 return function (string) { 20475 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 20476 var matchResult = string.match(args.matchPattern); 20477 if (!matchResult) return null; 20478 var matchedString = matchResult[0]; 20479 var parseResult = string.match(args.parsePattern); 20480 if (!parseResult) return null; 20481 var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0]; 20482 value = options.valueCallback ? options.valueCallback(value) : value; 20483 var rest = string.slice(matchedString.length); 20484 return { 20485 value: value, 20486 rest: rest 20487 }; 20488 }; 20489 } 20490 20491 var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; 20492 var parseOrdinalNumberPattern = /\d+/i; 20493 var matchEraPatterns = { 20494 narrow: /^(b|a)/i, 20495 abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, 20496 wide: /^(before christ|before common era|anno domini|common era)/i 20497 }; 20498 var parseEraPatterns = { 20499 any: [/^b/i, /^(a|c)/i] 20500 }; 20501 var matchQuarterPatterns = { 20502 narrow: /^[1234]/i, 20503 abbreviated: /^q[1234]/i, 20504 wide: /^[1234](th|st|nd|rd)? quarter/i 20505 }; 20506 var parseQuarterPatterns = { 20507 any: [/1/i, /2/i, /3/i, /4/i] 20508 }; 20509 var matchMonthPatterns = { 20510 narrow: /^[jfmasond]/i, 20511 abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, 20512 wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i 20513 }; 20514 var parseMonthPatterns = { 20515 narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], 20516 any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] 20517 }; 20518 var matchDayPatterns = { 20519 narrow: /^[smtwf]/i, 20520 "short": /^(su|mo|tu|we|th|fr|sa)/i, 20521 abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, 20522 wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i 20523 }; 20524 var parseDayPatterns = { 20525 narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], 20526 any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] 20527 }; 20528 var matchDayPeriodPatterns = { 20529 narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, 20530 any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i 20531 }; 20532 var parseDayPeriodPatterns = { 20533 any: { 20534 am: /^a/i, 20535 pm: /^p/i, 20536 midnight: /^mi/i, 20537 noon: /^no/i, 20538 morning: /morning/i, 20539 afternoon: /afternoon/i, 20540 evening: /evening/i, 20541 night: /night/i 20542 } 20543 }; 20544 var match = { 20545 ordinalNumber: buildMatchPatternFn({ 20546 matchPattern: matchOrdinalNumberPattern, 20547 parsePattern: parseOrdinalNumberPattern, 20548 valueCallback: function valueCallback(value) { 20549 return parseInt(value, 10); 20550 } 20551 }), 20552 era: buildMatchFn({ 20553 matchPatterns: matchEraPatterns, 20554 defaultMatchWidth: 'wide', 20555 parsePatterns: parseEraPatterns, 20556 defaultParseWidth: 'any' 20557 }), 20558 quarter: buildMatchFn({ 20559 matchPatterns: matchQuarterPatterns, 20560 defaultMatchWidth: 'wide', 20561 parsePatterns: parseQuarterPatterns, 20562 defaultParseWidth: 'any', 20563 valueCallback: function valueCallback(index) { 20564 return index + 1; 20565 } 20566 }), 20567 month: buildMatchFn({ 20568 matchPatterns: matchMonthPatterns, 20569 defaultMatchWidth: 'wide', 20570 parsePatterns: parseMonthPatterns, 20571 defaultParseWidth: 'any' 20572 }), 20573 day: buildMatchFn({ 20574 matchPatterns: matchDayPatterns, 20575 defaultMatchWidth: 'wide', 20576 parsePatterns: parseDayPatterns, 20577 defaultParseWidth: 'any' 20578 }), 20579 dayPeriod: buildMatchFn({ 20580 matchPatterns: matchDayPeriodPatterns, 20581 defaultMatchWidth: 'any', 20582 parsePatterns: parseDayPeriodPatterns, 20583 defaultParseWidth: 'any' 20584 }) 20585 }; 20586 var match$1 = match; 20587 20588 /** 20589 * @type {Locale} 20590 * @category Locales 20591 * @summary English locale (United States). 20592 * @language English 20593 * @iso-639-2 eng 20594 * @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp} 20595 * @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss} 20596 */ 20597 var locale = { 20598 code: 'en-US', 20599 formatDistance: formatDistance$1, 20600 formatLong: formatLong$1, 20601 formatRelative: formatRelative$1, 20602 localize: localize$1, 20603 match: match$1, 20604 options: { 20605 weekStartsOn: 0 /* Sunday */, 20606 firstWeekContainsDate: 1 20607 } 20608 }; 20609 var defaultLocale = locale; 20610 20611 // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token 20612 // (one of the certain letters followed by `o`) 20613 // - (\w)\1* matches any sequences of the same letter 20614 // - '' matches two quote characters in a row 20615 // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), 20616 // except a single quote symbol, which ends the sequence. 20617 // Two quote characters do not end the sequence. 20618 // If there is no matching single quote
20619 // then the sequence will continue until the end of the string. 20620 // - . matches any single character unmatched by previous parts of the RegExps 20621 var formattingTokensRegExp$1 = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; 20622 20623 // This RegExp catches symbols escaped by quotes, and also 20624 // sequences of symbols P, p, and the combinations like `PPPPPPPppppp` 20625 var longFormattingTokensRegExp$1 = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; 20626 var escapedStringRegExp$1 = /^'([^]*?)'?$/; 20627 var doubleQuoteRegExp$1 = /''/g; 20628 var unescapedLatinCharacterRegExp$1 = /[a-zA-Z]/; 20629 20630 /** 20631 * @name format 20632 * @category Common Helpers 20633 * @summary Format the date. 20634 * 20635 * @description 20636 * Return the formatted date string in the given format. The result may vary by locale. 20637 * 20638 * > â ï¸ Please note that the `format` tokens differ from Moment.js and other libraries. 20639 * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 20640 * 20641 * The characters wrapped between two single quotes characters (') are escaped. 20642 * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. 20643 * (see the last example) 20644 * 20645 * Format of the string is based on Unicode Technical Standard #35: 20646 * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table 20647 * with a few additions (see note 7 below the table). 20648 * 20649 * Accepted patterns: 20650 * | Unit | Pattern | Result examples | Notes | 20651 * |---------------------------------|---------|-----------------------------------|-------| 20652 * | Era | G..GGG | AD, BC | | 20653 * | | GGGG | Anno Domini, Before Christ | 2 | 20654 * | | GGGGG | A, B | | 20655 * | Calendar year | y | 44, 1, 1900, 2017 | 5 | 20656 * | | yo | 44th, 1st, 0th, 17th | 5,7 | 20657 * | | yy | 44, 01, 00, 17 | 5 | 20658 * | | yyy | 044, 001, 1900, 2017 | 5 | 20659 * | | yyyy | 0044, 0001, 1900, 2017 | 5 | 20660 * | | yyyyy | ... | 3,5 | 20661 * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 | 20662 * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 | 20663 * | | YY | 44, 01, 00, 17 | 5,8 | 20664 * | | YYY | 044, 001, 1900, 2017 | 5 | 20665 * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 | 20666 * | | YYYYY | ... | 3,5 | 20667 * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 | 20668 * | | RR | -43, 00, 01, 1900, 2017 | 5,7 | 20669 * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 | 20670 * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 | 20671 * | | RRRRR | ... | 3,5,7 | 20672 * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 | 20673 * | | uu | -43, 01, 1900, 2017 | 5 | 20674 * | | uuu | -043, 001, 1900, 2017 | 5 | 20675 * | | uuuu | -0043, 0001, 1900, 2017 | 5 | 20676 * | | uuuuu | ... | 3,5 | 20677 * | Quarter (formatting) | Q | 1, 2, 3, 4 | | 20678 * | | Qo | 1st, 2nd, 3rd, 4th | 7 | 20679 * | | QQ | 01, 02, 03, 04 | | 20680 * | | QQQ | Q1, Q2, Q3, Q4 | | 20681 * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | 20682 * | | QQQQQ | 1, 2, 3, 4 | 4 | 20683 * | Quarter (stand-alone) | q | 1, 2, 3, 4 | | 20684 * | | qo | 1st, 2nd, 3rd, 4th | 7 | 20685 * | | qq | 01, 02, 03, 04 | | 20686 * | | qqq | Q1, Q2, Q3, Q4 | | 20687 * | | qqqq | 1st quarter, 2nd quarter, ... | 2 | 20688 * | | qqqqq | 1, 2, 3, 4 | 4 | 20689 * | Month (formatting) | M | 1, 2, ..., 12 | | 20690 * | | Mo | 1st, 2nd, ..., 12th | 7 | 20691 * | | MM | 01, 02, ..., 12 | | 20692 * | | MMM | Jan, Feb, ..., Dec | | 20693 * | | MMMM | January, February, ..., December | 2 | 20694 * | | MMMMM | J, F, ..., D | | 20695 * | Month (stand-alone) | L | 1, 2, ..., 12 | | 20696 * | | Lo | 1st, 2nd, ..., 12th | 7 | 20697 * | | LL | 01, 02, ..., 12 | | 20698 * | | LLL | Jan, Feb, ..., Dec | | 20699 * | | LLLL | January, February, ..., December | 2 | 20700 * | | LLLLL | J, F, ..., D | | 20701 * | Local week of year | w | 1, 2, ..., 53 | | 20702 * | | wo | 1st, 2nd, ..., 53th | 7 | 20703 * | | ww | 01, 02, ..., 53 | | 20704 * | ISO week of year | I | 1, 2, ..., 53 | 7 | 20705 * | | Io | 1st, 2nd, ..., 53th | 7 | 20706 * | | II | 01, 02, ..., 53 | 7 | 20707 * | Day of month | d | 1, 2, ..., 31 | | 20708 * | | do | 1st, 2nd, ..., 31st | 7 | 20709 * | | dd | 01, 02, ..., 31 | | 20710 * | Day of year | D | 1, 2, ..., 365, 366 | 9 | 20711 * | | Do | 1st, 2nd, ..., 365th, 366th | 7 | 20712 * | | DD | 01, 02, ..., 365, 366 | 9 | 20713 * | | DDD | 001, 002, ..., 365, 366 | | 20714 * | | DDDD | ... | 3 | 20715 * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | | 20716 * | | EEEE | Monday, Tuesday, ..., Sunday | 2 | 20717 * | | EEEEE | M, T, W, T, F, S, S | | 20718 * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | 20719 * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 | 20720 * | | io | 1st, 2nd, ..., 7th | 7 | 20721 * | | ii | 01, 02, ...,
2072107 | 7 | 20722 * | | iii | Mon, Tue, Wed, ..., Sun | 7 | 20723 * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 | 20724 * | | iiiii | M, T, W, T, F, S, S | 7 | 20725 * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 | 20726 * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | | 20727 * | | eo | 2nd, 3rd, ..., 1st | 7 | 20728 * | | ee | 02, 03, ..., 01 | | 20729 * | | eee | Mon, Tue, Wed, ..., Sun | | 20730 * | | eeee | Monday, Tuesday, ..., Sunday | 2 | 20731 * | | eeeee | M, T, W, T, F, S, S | | 20732 * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | 20733 * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | | 20734 * | | co | 2nd, 3rd, ..., 1st | 7 | 20735 * | | cc | 02, 03, ..., 01 | | 20736 * | | ccc | Mon, Tue, Wed, ..., Sun | | 20737 * | | cccc | Monday, Tuesday, ..., Sunday | 2 | 20738 * | | ccccc | M, T, W, T, F, S, S | | 20739 * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | 20740 * | AM, PM | a..aa | AM, PM | | 20741 * | | aaa | am, pm | | 20742 * | | aaaa | a.m., p.m. | 2 | 20743 * | | aaaaa | a, p | | 20744 * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | | 20745 * | | bbb | am, pm, noon, midnight | | 20746 * | | bbbb | a.m., p.m., noon, midnight | 2 | 20747 * | | bbbbb | a, p, n, mi | | 20748 * | Flexible day period | B..BBB | at night, in the morning, ... | | 20749 * | | BBBB | at night, in the morning, ... | 2 | 20750 * | | BBBBB | at night, in the morning, ... | | 20751 * | Hour [1-12] | h | 1, 2, ..., 11, 12 | | 20752 * | | ho | 1st, 2nd, ..., 11th, 12th | 7 | 20753 * | | hh | 01, 02, ..., 11, 12 | | 20754 * | Hour [0-23] | H | 0, 1, 2, ..., 23 | | 20755 * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 | 20756 * | | HH | 00, 01, 02, ..., 23 | | 20757 * | Hour [0-11] | K | 1, 2, ..., 11, 0 | | 20758 * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 | 20759 * | | KK | 01, 02, ..., 11, 00 | | 20760 * | Hour [1-24] | k | 24, 1, 2, ..., 23 | | 20761 * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 | 20762 * | | kk | 24, 01, 02, ..., 23 | | 20763 * | Minute | m | 0, 1, ..., 59 | | 20764 * | | mo | 0th, 1st, ..., 59th | 7 | 20765 * | | mm | 00, 01, ..., 59 | | 20766 * | Second | s | 0, 1, ..., 59 | | 20767 * | | so | 0th, 1st, ..., 59th | 7 | 20768 * | | ss | 00, 01, ..., 59 | | 20769 * | Fraction of second | S | 0, 1, ..., 9 | | 20770 * | | SS | 00, 01, ..., 99 | | 20771 * | | SSS | 000, 001, ..., 999 | | 20772 * | | SSSS | ... | 3 | 20773 * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | | 20774 * | | XX | -0800, +0530, Z | | 20775 * | | XXX | -08:00, +05:30, Z | | 20776 * | | XXXX | -0800, +0530, Z, +123456 | 2 | 20777 * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | 20778 * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | | 20779 * | | xx | -0800, +0530, +0000 | | 20780 * | | xxx | -08:00, +05:30, +00:00 | 2 | 20781 * | | xxxx | -0800, +0530, +0000, +123456 | | 20782 * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | 20783 * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | | 20784 * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 | 20785 * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 | 20786 * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 | 20787 * | Seconds timestamp | t | 512969520 | 7 | 20788 * | | tt | ... | 3,7 | 20789 * | Milliseconds timestamp | T | 512969520900 | 7 | 20790 * | | TT | ... | 3,7 | 20791 * | Long localized date | P | 04/29/1453 | 7 | 20792 * | | PP | Apr 29, 1453 | 7 | 20793 * | | PPP | April 29th, 1453 | 7 | 20794 * | | PPPP | Friday, April 29th, 1453 | 2,7 | 20795 * | Long localized time | p | 12:00 AM | 7 | 20796 * | | pp | 12:00:00 AM | 7 | 20797 * | | ppp | 12:00:00 AM GMT+2 | 7 | 20798 * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 | 20799 * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 | 20800 * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 | 20801 * | | PPPppp | April 29th, 1453 at ... | 7 | 20802 * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 | 20803 * Notes: 20804 * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale 20805 * are the same as "stand-alone" units, but are different in some languages. 20806 * "Formatting" units are declined according to the rules of the language 20807 * in the context of a date. "Stand-alone" units are always nominative singular: 20808 * 20809 * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` 20810 * 20811 * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` 20812 * 20813 * 2. Any sequence of the identical letters is a pattern, unless it is escaped by 20814 * the single quote characters (see below). 20815 * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`) 20816 * the output will be the same as default pattern for this unit, usually 20817 * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units 20818 * are marked with "2" in the last column of the table. 20819 * 20820 * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'` 20821 * 20822 * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'` 20823 * 20824 * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'` 20825 * 20826 * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'` 20827 * 20828 * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'` 20829 * 20830 * 3. Some patterns could be unlimited length (such as `yyyyyyyy`). 20831 * The output will be padded with zeros to match the length of the pattern. 20832 * 20833 * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'` 20834 * 20835 * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. 20836 * These tokens represent the shortest form of the quarter. 20837 * 20838 * 5. The main difference between `y` and `u` patterns are B.C. years: 20839 * 20840 * | Year | `y` | `u` | 20841 * |------|-----|-----| 20842 * | AC 1 | 1 | 1 | 20843 * | BC 1 | 1 | 0 | 20844 * | BC 2 | 2 | -1 | 20845 * 20846 * Also `yy` always returns the last two digits of a year, 20847 * while `uu` pads single digit years to 2 characters and returns other years unchanged: 20848 * 20849 * | Year | `yy` | `uu` | 20850 * |------|------|------| 20851 * | 1 | 01 | 01 | 20852 * | 14 | 14 | 14 | 20853 * | 376 | 76 | 376 | 20854 * | 1453 | 53 | 1453 | 20855 * 20856 * The same difference is true for local and ISO week-numbering years (`Y` and `R`), 20857 * except local week-numbering years are dependent on `options.weekStartsOn` 20858 * and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear} 20859 * and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}). 20860 * 20861 * 6. Specific non-location timezones are currently unavailable in `date-fns`, 20862 * so right now these tokens fall back to GMT timezones. 20863 * 20864 * 7. These patterns are not in the Unicode Technical Standard #35: 20865 * - `i`: ISO day of week 20866 * - `I`: ISO week of year 20867 * - `R`: ISO week-numbering year 20868 * - `t`: seconds timestamp 20869 * - `T`: milliseconds timestamp 20870 * - `o`: ordinal number modifier 20871 * - `P`: long localized date 20872 * - `p`: long localized time 20873 * 20874 * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. 20875 * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 20876 * 20877 * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month. 20878 * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 20879 * 20880 * @param {Date|Number} date - the original date 20881 * @param {String} format - the string of tokens 20882 * @param {Object} [options] - an object with options. 20883 * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} 20884 * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) 20885 * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is 20886 * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; 20887 * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 20888 * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; 20889 * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 20890 * @returns {String} the formatted date string 20891 * @throws {TypeError} 2 arguments required 20892 * @throws {RangeError} `date` must not be Invalid Date 20893 * @throws {RangeError} `options.locale` must contain `localize` property 20894 * @throws {RangeError} `options.locale` must contain `formatLong` property 20895 * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 20896 * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 20897 * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 20898 * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 20899 * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 20900 * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 20901 * @throws {RangeError}
vendor: 12,097 bytes, lines 20901-21191
20901 format string contains an unescaped latin alphabet character 20902 * 20903 * @example 20904 * // Represent 11 February 2014 in middle-endian format: 20905 * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy') 20906 * //=> '02/11/2014' 20907 * 20908 * @example 20909 * // Represent 2 July 2014 in Esperanto: 20910 * import { eoLocale } from 'date-fns/locale/eo' 20911 * const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", { 20912 * locale: eoLocale 20913 * }) 20914 * //=> '2-a de julio 2014' 20915 * 20916 * @example 20917 * // Escape string by single quote characters: 20918 * const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'") 20919 * //=> "3 o'clock" 20920 */ 20921 20922 function format(dirtyDate, dirtyFormatStr, options) { 20923 var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; 20924 requiredArgs(2, arguments); 20925 var formatStr = String(dirtyFormatStr); 20926 var defaultOptions = getDefaultOptions(); 20927 var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : defaultLocale; 20928 var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); 20929 20930 // Test if weekStartsOn is between 1 and 7 _and_ is not NaN 20931 if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { 20932 throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); 20933 } 20934 var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); 20935 20936 // Test if weekStartsOn is between 0 and 6 _and_ is not NaN 20937 if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { 20938 throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); 20939 } 20940 if (!locale.localize) { 20941 throw new RangeError('locale must contain localize property'); 20942 } 20943 if (!locale.formatLong) { 20944 throw new RangeError('locale must contain formatLong property'); 20945 } 20946 var originalDate = toDate(dirtyDate); 20947 if (!isValid(originalDate)) { 20948 throw new RangeError('Invalid time value'); 20949 } 20950 20951 // Convert the date in system timezone to the same date in UTC+00:00 timezone. 20952 // This ensures that when UTC functions will be implemented, locales will be compatible with them. 20953 // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376 20954 var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate); 20955 var utcDate = subMilliseconds(originalDate, timezoneOffset); 20956 var formatterOptions = { 20957 firstWeekContainsDate: firstWeekContainsDate, 20958 weekStartsOn: weekStartsOn, 20959 locale: locale, 20960 _originalDate: originalDate 20961 }; 20962 var result = formatStr.match(longFormattingTokensRegExp$1).map(function (substring) { 20963 var firstCharacter = substring[0]; 20964 if (firstCharacter === 'p' || firstCharacter === 'P') { 20965 var longFormatter = longFormatters$1[firstCharacter]; 20966 return longFormatter(substring, locale.formatLong); 20967 } 20968 return substring; 20969 }).join('').match(formattingTokensRegExp$1).map(function (substring) { 20970 // Replace two single quote characters with one single quote character 20971 if (substring === "''") { 20972 return "'"; 20973 } 20974 var firstCharacter = substring[0]; 20975 if (firstCharacter === "'") { 20976 return cleanEscapedString$1(substring); 20977 } 20978 var formatter = formatters$1[firstCharacter]; 20979 if (formatter) { 20980 if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) { 20981 throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); 20982 } 20983 if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) { 20984 throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); 20985 } 20986 return formatter(utcDate, substring, locale.localize, formatterOptions); 20987 } 20988 if (firstCharacter.match(unescapedLatinCharacterRegExp$1)) { 20989 throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); 20990 } 20991 return substring; 20992 }).join(''); 20993 return result; 20994 } 20995 function cleanEscapedString$1(input) { 20996 var matched = input.match(escapedStringRegExp$1); 20997 if (!matched) { 20998 return input; 20999 } 21000 return matched[1].replace(doubleQuoteRegExp$1, "'"); 21001 } 21002 21003 function assign(target, object) { 21004 if (target == null) { 21005 throw new TypeError('assign requires that input parameter not be null or undefined'); 21006 } 21007 for (var property in object) { 21008 if (Object.prototype.hasOwnProperty.call(object, property)) { 21009 target[property] = object[property]; 21010 } 21011 } 21012 return target; 21013 } 21014 21015 function _arrayLikeToArray(r, a) { 21016 (null == a || a > r.length) && (a = r.length); 21017 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; 21018 return n; 21019 } 21020 21021 function _unsupportedIterableToArray(r, a) { 21022 if (r) { 21023 if ("string" == typeof r) return _arrayLikeToArray(r, a); 21024 var t = {}.toString.call(r).slice(8, -1); 21025 return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; 21026 } 21027 } 21028 21029 function _createForOfIteratorHelper(r, e) { 21030 var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; 21031 if (!t) { 21032 if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { 21033 t && (r = t); 21034 var _n = 0, 21035 F = function F() {}; 21036 return { 21037 s: F, 21038 n: function n() { 21039 return _n >= r.length ? { 21040 done: !0 21041 } : { 21042 done: !1, 21043 value: r[_n++] 21044 }; 21045 }, 21046 e: function e(r) { 21047 throw r; 21048 }, 21049 f: F 21050 }; 21051 } 21052 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); 21053 } 21054 var o, 21055 a = !0, 21056 u = !1; 21057 return { 21058 s: function s() { 21059 t = t.call(r); 21060 }, 21061 n: function n() { 21062 var r = t.next(); 21063 return a = r.done, r; 21064 }, 21065 e: function e(r) { 21066 u = !0, o = r; 21067 }, 21068 f: function f() { 21069 try { 21070 a || null == t["return"] || t["return"](); 21071 } finally { 21072 if (u) throw o; 21073 } 21074 } 21075 }; 21076 } 21077 21078 function _assertThisInitialized(e) { 21079 if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); 21080 return e; 21081 } 21082 21083 function _setPrototypeOf(t, e) { 21084 return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { 21085 return t.__proto__ = e, t; 21086 }, _setPrototypeOf(t, e); 21087 } 21088 21089 function _inherits(t, e) { 21090 if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); 21091 t.prototype = Object.create(e && e.prototype, { 21092 constructor: { 21093 value: t, 21094 writable: !0, 21095 configurable: !0 21096 } 21097 }), Object.defineProperty(t, "prototype", { 21098 writable: !1 21099 }), e && _setPrototypeOf(t, e); 21100 } 21101 21102 function _getPrototypeOf(t) { 21103 return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { 21104 return t.__proto__ || Object.getPrototypeOf(t); 21105 }, _getPrototypeOf(t); 21106 } 21107 21108 function _isNativeReflectConstruct() { 21109 try { 21110 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); 21111 } catch (t) {} 21112 return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { 21113 return !!t; 21114 })(); 21115 } 21116 21117 function _possibleConstructorReturn(t, e) { 21118 if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; 21119 if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); 21120 return _assertThisInitialized(t); 21121 } 21122 21123 function _createSuper(t) { 21124 var r = _isNativeReflectConstruct(); 21125 return function () { 21126 var e, 21127 o = _getPrototypeOf(t); 21128 if (r) { 21129 var s = _getPrototypeOf(this).constructor; 21130 e = Reflect.construct(o, arguments, s); 21131 } else e = o.apply(this, arguments); 21132 return _possibleConstructorReturn(this, e); 21133 }; 21134 } 21135 21136 function _classCallCheck(a, n) { 21137 if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); 21138 } 21139 21140 function toPrimitive(t, r) { 21141 if ("object" != _typeof(t) || !t) return t; 21142 var e = t[Symbol.toPrimitive]; 21143 if (void 0 !== e) { 21144 var i = e.call(t, r || "default"); 21145 if ("object" != _typeof(i)) return i; 21146 throw new TypeError("@@toPrimitive must return a primitive value."); 21147 } 21148 return ("string" === r ? String : Number)(t); 21149 } 21150 21151 function toPropertyKey(t) { 21152 var i = toPrimitive(t, "string"); 21153 return "symbol" == _typeof(i) ? i : i + ""; 21154 } 21155 21156 function _defineProperties(e, r) { 21157 for (var t = 0; t < r.length; t++) { 21158 var o = r[t]; 21159 o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, toPropertyKey(o.key), o); 21160 } 21161 } 21162 function _createClass(e, r, t) { 21163 return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { 21164 writable: !1 21165 }), e; 21166 } 21167 21168 function _defineProperty(e, r, t) { 21169 return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, { 21170 value: t, 21171 enumerable: !0, 21172 configurable: !0, 21173 writable: !0 21174 }) : e[r] = t, e; 21175 } 21176 21177 var TIMEZONE_UNIT_PRIORITY = 10; 21178 var Setter = /*#__PURE__*/function () { 21179 function Setter() { 21180 _classCallCheck(this, Setter); 21181 _defineProperty(this, "priority", void 0); 21182 _defineProperty(this, "subPriority", 0); 21183 } 21184 _createClass(Setter, [{ 21185 key: "validate", 21186 value: function validate(_utcDate, _options) { 21187 return true; 21188 } 21189 }]); 21190 return Setter; 21191 }();
vendor: 26,842 bytes, lines 21192-21973
21192 var ValueSetter = /*#__PURE__*/function (_Setter) { 21193 _inherits(ValueSetter, _Setter); 21194 var _super = _createSuper(ValueSetter); 21195 function ValueSetter(value, validateValue, setValue, priority, subPriority) { 21196 var _this; 21197 _classCallCheck(this, ValueSetter); 21198 _this = _super.call(this); 21199 _this.value = value; 21200 _this.validateValue = validateValue; 21201 _this.setValue = setValue; 21202 _this.priority = priority; 21203 if (subPriority) { 21204 _this.subPriority = subPriority; 21205 } 21206 return _this; 21207 } 21208 _createClass(ValueSetter, [{ 21209 key: "validate", 21210 value: function validate(utcDate, options) { 21211 return this.validateValue(utcDate, this.value, options); 21212 } 21213 }, { 21214 key: "set", 21215 value: function set(utcDate, flags, options) { 21216 return this.setValue(utcDate, flags, this.value, options); 21217 } 21218 }]); 21219 return ValueSetter; 21220 }(Setter); 21221 var DateToSystemTimezoneSetter = /*#__PURE__*/function (_Setter2) { 21222 _inherits(DateToSystemTimezoneSetter, _Setter2); 21223 var _super2 = _createSuper(DateToSystemTimezoneSetter); 21224 function DateToSystemTimezoneSetter() { 21225 var _this2; 21226 _classCallCheck(this, DateToSystemTimezoneSetter); 21227 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 21228 args[_key] = arguments[_key]; 21229 } 21230 _this2 = _super2.call.apply(_super2, [this].concat(args)); 21231 _defineProperty(_assertThisInitialized(_this2), "priority", TIMEZONE_UNIT_PRIORITY); 21232 _defineProperty(_assertThisInitialized(_this2), "subPriority", -1); 21233 return _this2; 21234 } 21235 _createClass(DateToSystemTimezoneSetter, [{ 21236 key: "set", 21237 value: function set(date, flags) { 21238 if (flags.timestampIsSet) { 21239 return date; 21240 } 21241 var convertedDate = new Date(0); 21242 convertedDate.setFullYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); 21243 convertedDate.setHours(date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()); 21244 return convertedDate; 21245 } 21246 }]); 21247 return DateToSystemTimezoneSetter; 21248 }(Setter); 21249 21250 var Parser = /*#__PURE__*/function () { 21251 function Parser() { 21252 _classCallCheck(this, Parser); 21253 _defineProperty(this, "incompatibleTokens", void 0); 21254 _defineProperty(this, "priority", void 0); 21255 _defineProperty(this, "subPriority", void 0); 21256 } 21257 _createClass(Parser, [{ 21258 key: "run", 21259 value: function run(dateString, token, match, options) { 21260 var result = this.parse(dateString, token, match, options); 21261 if (!result) { 21262 return null; 21263 } 21264 return { 21265 setter: new ValueSetter(result.value, this.validate, this.set, this.priority, this.subPriority), 21266 rest: result.rest 21267 }; 21268 } 21269 }, { 21270 key: "validate", 21271 value: function validate(_utcDate, _value, _options) { 21272 return true; 21273 } 21274 }]); 21275 return Parser; 21276 }(); 21277 21278 var EraParser = /*#__PURE__*/function (_Parser) { 21279 _inherits(EraParser, _Parser); 21280 var _super = _createSuper(EraParser); 21281 function EraParser() { 21282 var _this; 21283 _classCallCheck(this, EraParser); 21284 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 21285 args[_key] = arguments[_key]; 21286 } 21287 _this = _super.call.apply(_super, [this].concat(args)); 21288 _defineProperty(_assertThisInitialized(_this), "priority", 140); 21289 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['R', 'u', 't', 'T']); 21290 return _this; 21291 } 21292 _createClass(EraParser, [{ 21293 key: "parse", 21294 value: function parse(dateString, token, match) { 21295 switch (token) { 21296 // AD, BC 21297 case 'G': 21298 case 'GG': 21299 case 'GGG': 21300 return match.era(dateString, { 21301 width: 'abbreviated' 21302 }) || match.era(dateString, { 21303 width: 'narrow' 21304 }); 21305 // A, B 21306 case 'GGGGG': 21307 return match.era(dateString, { 21308 width: 'narrow' 21309 }); 21310 // Anno Domini, Before Christ 21311 case 'GGGG': 21312 default: 21313 return match.era(dateString, { 21314 width: 'wide' 21315 }) || match.era(dateString, { 21316 width: 'abbreviated' 21317 }) || match.era(dateString, { 21318 width: 'narrow' 21319 }); 21320 } 21321 } 21322 }, { 21323 key: "set", 21324 value: function set(date, flags, value) { 21325 flags.era = value; 21326 date.setUTCFullYear(value, 0, 1); 21327 date.setUTCHours(0, 0, 0, 0); 21328 return date; 21329 } 21330 }]); 21331 return EraParser; 21332 }(Parser); 21333 21334 var numericPatterns = { 21335 month: /^(1[0-2]|0?\d)/, 21336 // 0 to 12 21337 date: /^(3[0-1]|[0-2]?\d)/, 21338 // 0 to 31 21339 dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/, 21340 // 0 to 366 21341 week: /^(5[0-3]|[0-4]?\d)/, 21342 // 0 to 53 21343 hour23h: /^(2[0-3]|[0-1]?\d)/, 21344 // 0 to 23 21345 hour24h: /^(2[0-4]|[0-1]?\d)/, 21346 // 0 to 24 21347 hour11h: /^(1[0-1]|0?\d)/, 21348 // 0 to 11 21349 hour12h: /^(1[0-2]|0?\d)/, 21350 // 0 to 12 21351 minute: /^[0-5]?\d/, 21352 // 0 to 59 21353 second: /^[0-5]?\d/, 21354 // 0 to 59 21355 21356 singleDigit: /^\d/, 21357 // 0 to 9 21358 twoDigits: /^\d{1,2}/, 21359 // 0 to 99 21360 threeDigits: /^\d{1,3}/, 21361 // 0 to 999 21362 fourDigits: /^\d{1,4}/, 21363 // 0 to 9999 21364 21365 anyDigitsSigned: /^-?\d+/, 21366 singleDigitSigned: /^-?\d/, 21367 // 0 to 9, -0 to -9 21368 twoDigitsSigned: /^-?\d{1,2}/, 21369 // 0 to 99, -0 to -99 21370 threeDigitsSigned: /^-?\d{1,3}/, 21371 // 0 to 999, -0 to -999 21372 fourDigitsSigned: /^-?\d{1,4}/ // 0 to 9999, -0 to -9999 21373 }; 21374 var timezonePatterns = { 21375 basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/, 21376 basic: /^([+-])(\d{2})(\d{2})|Z/, 21377 basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/, 21378 extended: /^([+-])(\d{2}):(\d{2})|Z/, 21379 extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/ 21380 }; 21381 21382 function mapValue(parseFnResult, mapFn) { 21383 if (!parseFnResult) { 21384 return parseFnResult; 21385 } 21386 return { 21387 value: mapFn(parseFnResult.value), 21388 rest: parseFnResult.rest 21389 }; 21390 } 21391 function parseNumericPattern(pattern, dateString) { 21392 var matchResult = dateString.match(pattern); 21393 if (!matchResult) { 21394 return null; 21395 } 21396 return { 21397 value: parseInt(matchResult[0], 10), 21398 rest: dateString.slice(matchResult[0].length) 21399 }; 21400 } 21401 function parseTimezonePattern(pattern, dateString) { 21402 var matchResult = dateString.match(pattern); 21403 if (!matchResult) { 21404 return null; 21405 } 21406 21407 // Input is 'Z' 21408 if (matchResult[0] === 'Z') { 21409 return { 21410 value: 0, 21411 rest: dateString.slice(1) 21412 }; 21413 } 21414 var sign = matchResult[1] === '+' ? 1 : -1; 21415 var hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0; 21416 var minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0; 21417 var seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0; 21418 return { 21419 value: sign * (hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * millisecondsInSecond), 21420 rest: dateString.slice(matchResult[0].length) 21421 }; 21422 } 21423 function parseAnyDigitsSigned(dateString) { 21424 return parseNumericPattern(numericPatterns.anyDigitsSigned, dateString); 21425 } 21426 function parseNDigits(n, dateString) { 21427 switch (n) { 21428 case 1: 21429 return parseNumericPattern(numericPatterns.singleDigit, dateString); 21430 case 2: 21431 return parseNumericPattern(numericPatterns.twoDigits, dateString); 21432 case 3: 21433 return parseNumericPattern(numericPatterns.threeDigits, dateString); 21434 case 4: 21435 return parseNumericPattern(numericPatterns.fourDigits, dateString); 21436 default: 21437 return parseNumericPattern(new RegExp('^\\d{1,' + n + '}'), dateString); 21438 } 21439 } 21440 function parseNDigitsSigned(n, dateString) { 21441 switch (n) { 21442 case 1: 21443 return parseNumericPattern(numericPatterns.singleDigitSigned, dateString); 21444 case 2: 21445 return parseNumericPattern(numericPatterns.twoDigitsSigned, dateString); 21446 case 3: 21447 return parseNumericPattern(numericPatterns.threeDigitsSigned, dateString); 21448 case 4: 21449 return parseNumericPattern(numericPatterns.fourDigitsSigned, dateString); 21450 default: 21451 return parseNumericPattern(new RegExp('^-?\\d{1,' + n + '}'), dateString); 21452 } 21453 } 21454 function dayPeriodEnumToHours(dayPeriod) { 21455 switch (dayPeriod) { 21456 case 'morning': 21457 return 4; 21458 case 'evening': 21459 return 17; 21460 case 'pm': 21461 case 'noon': 21462 case 'afternoon': 21463 return 12; 21464 case 'am': 21465 case 'midnight': 21466 case 'night': 21467 default: 21468 return 0; 21469 } 21470 } 21471 function normalizeTwoDigitYear(twoDigitYear, currentYear) { 21472 var isCommonEra = currentYear > 0; 21473 // Absolute number of the current year: 21474 // 1 -> 1 AC 21475 // 0 -> 1 BC 21476 // -1 -> 2 BC 21477 var absCurrentYear = isCommonEra ? currentYear : 1 - currentYear; 21478 var result; 21479 if (absCurrentYear <= 50) { 21480 result = twoDigitYear || 100; 21481 } else { 21482 var rangeEnd = absCurrentYear + 50; 21483 var rangeEndCentury = Math.floor(rangeEnd / 100) * 100; 21484 var isPreviousCentury = twoDigitYear >= rangeEnd % 100; 21485 result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0); 21486 } 21487 return isCommonEra ? result : 1 - result; 21488 } 21489 function isLeapYearIndex$1(year) { 21490 return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; 21491 } 21492 21493 // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns 21494 // | Year | y | yy | yyy | yyyy | yyyyy | 21495 // |----------|-------|----|-------|-------|-------| 21496 // | AD 1 | 1 | 01 | 001 | 0001 | 00001 | 21497 // | AD 12 | 12 | 12 | 012 | 0012 | 00012 | 21498 // | AD 123 | 123 | 23 | 123 | 0123 | 00123 | 21499 // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 | 21500 // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 | 21501 var YearParser = /*#__PURE__*/function (_Parser) { 21502 _inherits(YearParser, _Parser); 21503 var _super = _createSuper(YearParser); 21504 function YearParser() { 21505 var _this; 21506 _classCallCheck(this, YearParser); 21507 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 21508 args[_key] = arguments[_key]; 21509 } 21510 _this = _super.call.apply(_super, [this].concat(args)); 21511 _defineProperty(_assertThisInitialized(_this), "priority", 130); 21512 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['Y', 'R', 'u', 'w', 'I', 'i', 'e', 'c', 't', 'T']); 21513 return _this; 21514 } 21515 _createClass(YearParser, [{ 21516 key: "parse", 21517 value: function parse(dateString, token, match) { 21518 var valueCallback = function valueCallback(year) { 21519 return { 21520 year: year, 21521 isTwoDigitYear: token === 'yy' 21522 }; 21523 }; 21524 switch (token) { 21525 case 'y': 21526 return mapValue(parseNDigits(4, dateString), valueCallback); 21527 case 'yo': 21528 return mapValue(match.ordinalNumber(dateString, { 21529 unit: 'year' 21530 }), valueCallback); 21531 default: 21532 return mapValue(parseNDigits(token.length, dateString), valueCallback); 21533 } 21534 } 21535 }, { 21536 key: "validate", 21537 value: function validate(_date, value) { 21538 return value.isTwoDigitYear || value.year > 0; 21539 } 21540 }, { 21541 key: "set", 21542 value: function set(date, flags, value) { 21543 var currentYear = date.getUTCFullYear(); 21544 if (value.isTwoDigitYear) { 21545 var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear); 21546 date.setUTCFullYear(normalizedTwoDigitYear, 0, 1); 21547 date.setUTCHours(0, 0, 0, 0); 21548 return date; 21549 } 21550 var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year; 21551 date.setUTCFullYear(year, 0, 1); 21552 date.setUTCHours(0, 0, 0, 0); 21553 return date; 21554 } 21555 }]); 21556 return YearParser; 21557 }(Parser); 21558 21559 // Local week-numbering year 21560 var LocalWeekYearParser = /*#__PURE__*/function (_Parser) { 21561 _inherits(LocalWeekYearParser, _Parser); 21562 var _super = _createSuper(LocalWeekYearParser); 21563 function LocalWeekYearParser() { 21564 var _this; 21565 _classCallCheck(this, LocalWeekYearParser); 21566 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 21567 args[_key] = arguments[_key]; 21568 } 21569 _this = _super.call.apply(_super, [this].concat(args)); 21570 _defineProperty(_assertThisInitialized(_this), "priority", 130); 21571 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['y', 'R', 'u', 'Q', 'q', 'M', 'L', 'I', 'd', 'D', 'i', 't', 'T']); 21572 return _this; 21573 } 21574 _createClass(LocalWeekYearParser, [{ 21575 key: "parse", 21576 value: function parse(dateString, token, match) { 21577 var valueCallback = function valueCallback(year) { 21578 return { 21579 year: year, 21580 isTwoDigitYear: token === 'YY' 21581 }; 21582 }; 21583 switch (token) { 21584 case 'Y': 21585 return mapValue(parseNDigits(4, dateString), valueCallback); 21586 case 'Yo': 21587 return mapValue(match.ordinalNumber(dateString, { 21588 unit: 'year' 21589 }), valueCallback); 21590 default: 21591 return mapValue(parseNDigits(token.length, dateString), valueCallback); 21592 } 21593 } 21594 }, { 21595 key: "validate", 21596 value: function validate(_date, value) { 21597 return value.isTwoDigitYear || value.year > 0; 21598 } 21599 }, { 21600 key: "set", 21601 value: function set(date, flags, value, options) { 21602 var currentYear = getUTCWeekYear(date, options); 21603 if (value.isTwoDigitYear) { 21604 var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear); 21605 date.setUTCFullYear(normalizedTwoDigitYear, 0, options.firstWeekContainsDate); 21606 date.setUTCHours(0, 0, 0, 0); 21607 return startOfUTCWeek(date, options); 21608 } 21609 var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year; 21610 date.setUTCFullYear(year, 0, options.firstWeekContainsDate); 21611 date.setUTCHours(0, 0, 0, 0); 21612 return startOfUTCWeek(date, options); 21613 } 21614 }]); 21615 return LocalWeekYearParser; 21616 }(Parser); 21617 21618 var ISOWeekYearParser = /*#__PURE__*/function (_Parser) { 21619 _inherits(ISOWeekYearParser, _Parser); 21620 var _super = _createSuper(ISOWeekYearParser); 21621 function ISOWeekYearParser() { 21622 var _this; 21623 _classCallCheck(this, ISOWeekYearParser); 21624 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 21625 args[_key] = arguments[_key]; 21626 } 21627 _this = _super.call.apply(_super, [this].concat(args)); 21628 _defineProperty(_assertThisInitialized(_this), "priority", 130); 21629 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['G', 'y', 'Y', 'u', 'Q', 'q', 'M', 'L', 'w', 'd', 'D', 'e', 'c', 't', 'T']); 21630 return _this; 21631 } 21632 _createClass(ISOWeekYearParser, [{ 21633 key: "parse", 21634 value: function parse(dateString, token) { 21635 if (token === 'R') { 21636 return parseNDigitsSigned(4, dateString); 21637 } 21638 return parseNDigitsSigned(token.length, dateString); 21639 } 21640 }, { 21641 key: "set", 21642 value: function set(_date, _flags, value) { 21643 var firstWeekOfYear = new Date(0); 21644 firstWeekOfYear.setUTCFullYear(value, 0, 4); 21645 firstWeekOfYear.setUTCHours(0, 0, 0, 0); 21646 return startOfUTCISOWeek(firstWeekOfYear); 21647 } 21648 }]); 21649 return ISOWeekYearParser; 21650 }(Parser); 21651 21652 var ExtendedYearParser = /*#__PURE__*/function (_Parser) { 21653 _inherits(ExtendedYearParser, _Parser); 21654 var _super = _createSuper(ExtendedYearParser); 21655 function ExtendedYearParser() { 21656 var _this; 21657 _classCallCheck(this, ExtendedYearParser); 21658 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 21659 args[_key] = arguments[_key]; 21660 } 21661 _this = _super.call.apply(_super, [this].concat(args)); 21662 _defineProperty(_assertThisInitialized(_this), "priority", 130); 21663 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['G', 'y', 'Y', 'R', 'w', 'I', 'i', 'e', 'c', 't', 'T']); 21664 return _this; 21665 } 21666 _createClass(ExtendedYearParser, [{ 21667 key: "parse", 21668 value: function parse(dateString, token) { 21669 if (token === 'u') { 21670 return parseNDigitsSigned(4, dateString); 21671 } 21672 return parseNDigitsSigned(token.length, dateString); 21673 } 21674 }, { 21675 key: "set", 21676 value: function set(date, _flags, value) { 21677 date.setUTCFullYear(value, 0, 1); 21678 date.setUTCHours(0, 0, 0, 0); 21679 return date; 21680 } 21681 }]); 21682 return ExtendedYearParser; 21683 }(Parser); 21684 21685 var QuarterParser = /*#__PURE__*/function (_Parser) { 21686 _inherits(QuarterParser, _Parser); 21687 var _super = _createSuper(QuarterParser); 21688 function QuarterParser() { 21689 var _this; 21690 _classCallCheck(this, QuarterParser); 21691 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 21692 args[_key] = arguments[_key]; 21693 } 21694 _this = _super.call.apply(_super, [this].concat(args)); 21695 _defineProperty(_assertThisInitialized(_this), "priority", 120); 21696 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['Y', 'R', 'q', 'M', 'L', 'w', 'I', 'd', 'D', 'i', 'e', 'c', 't', 'T']); 21697 return _this; 21698 } 21699 _createClass(QuarterParser, [{ 21700 key: "parse", 21701 value: function parse(dateString, token, match) { 21702 switch (token) { 21703 // 1, 2, 3, 4 21704 case 'Q': 21705 case 'QQ': 21706 // 01, 02, 03, 04 21707 return parseNDigits(token.length, dateString); 21708 // 1st, 2nd, 3rd, 4th 21709 case 'Qo': 21710 return match.ordinalNumber(dateString, { 21711 unit: 'quarter' 21712 }); 21713 // Q1, Q2, Q3, Q4 21714 case 'QQQ': 21715 return match.quarter(dateString, { 21716 width: 'abbreviated', 21717 context: 'formatting' 21718 }) || match.quarter(dateString, { 21719 width: 'narrow', 21720 context: 'formatting' 21721 }); 21722 // 1, 2, 3, 4 (narrow quarter; could be not numerical) 21723 case 'QQQQQ': 21724 return match.quarter(dateString, { 21725 width: 'narrow', 21726 context: 'formatting' 21727 }); 21728 // 1st quarter, 2nd quarter, ... 21729 case 'QQQQ': 21730 default: 21731 return match.quarter(dateString, { 21732 width: 'wide', 21733 context: 'formatting' 21734 }) || match.quarter(dateString, { 21735 width: 'abbreviated', 21736 context: 'formatting' 21737 }) || match.quarter(dateString, { 21738 width: 'narrow', 21739 context: 'formatting' 21740 }); 21741 } 21742 } 21743 }, { 21744 key: "validate", 21745 value: function validate(_date, value) { 21746 return value >= 1 && value <= 4; 21747 } 21748 }, { 21749 key: "set", 21750 value: function set(date, _flags, value) { 21751 date.setUTCMonth((value - 1) * 3, 1); 21752 date.setUTCHours(0, 0, 0, 0); 21753 return date; 21754 } 21755 }]); 21756 return QuarterParser; 21757 }(Parser); 21758 21759 var StandAloneQuarterParser = /*#__PURE__*/function (_Parser) { 21760 _inherits(StandAloneQuarterParser, _Parser); 21761 var _super = _createSuper(StandAloneQuarterParser); 21762 function StandAloneQuarterParser() { 21763 var _this; 21764 _classCallCheck(this, StandAloneQuarterParser); 21765 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 21766 args[_key] = arguments[_key]; 21767 } 21768 _this = _super.call.apply(_super, [this].concat(args)); 21769 _defineProperty(_assertThisInitialized(_this), "priority", 120); 21770 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['Y', 'R', 'Q', 'M', 'L', 'w', 'I', 'd', 'D', 'i', 'e', 'c', 't', 'T']); 21771 return _this; 21772 } 21773 _createClass(StandAloneQuarterParser, [{ 21774 key: "parse", 21775 value: function parse(dateString, token, match) { 21776 switch (token) { 21777 // 1, 2, 3, 4 21778 case 'q': 21779 case 'qq': 21780 // 01, 02, 03, 04 21781 return parseNDigits(token.length, dateString); 21782 // 1st, 2nd, 3rd, 4th 21783 case 'qo': 21784 return match.ordinalNumber(dateString, { 21785 unit: 'quarter' 21786 }); 21787 // Q1, Q2, Q3, Q4 21788 case 'qqq': 21789 return match.quarter(dateString, { 21790 width: 'abbreviated', 21791 context: 'standalone' 21792 }) || match.quarter(dateString, { 21793 width: 'narrow', 21794 context: 'standalone' 21795 }); 21796 // 1, 2, 3, 4 (narrow quarter; could be not numerical) 21797 case 'qqqqq': 21798 return match.quarter(dateString, { 21799 width: 'narrow', 21800 context: 'standalone' 21801 }); 21802 // 1st quarter, 2nd quarter, ... 21803 case 'qqqq': 21804 default: 21805 return match.quarter(dateString, { 21806 width: 'wide', 21807 context: 'standalone' 21808 }) || match.quarter(dateString, { 21809 width: 'abbreviated', 21810 context: 'standalone' 21811 }) || match.quarter(dateString, { 21812 width: 'narrow', 21813 context: 'standalone' 21814 }); 21815 } 21816 } 21817 }, { 21818 key: "validate", 21819 value: function validate(_date, value) { 21820 return value >= 1 && value <= 4; 21821 } 21822 }, { 21823 key: "set", 21824 value: function set(date, _flags, value) { 21825 date.setUTCMonth((value - 1) * 3, 1); 21826 date.setUTCHours(0, 0, 0, 0); 21827 return date; 21828 } 21829 }]); 21830 return StandAloneQuarterParser; 21831 }(Parser); 21832 21833 var MonthParser = /*#__PURE__*/function (_Parser) { 21834 _inherits(MonthParser, _Parser); 21835 var _super = _createSuper(MonthParser); 21836 function MonthParser() { 21837 var _this; 21838 _classCallCheck(this, MonthParser); 21839 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 21840 args[_key] = arguments[_key]; 21841 } 21842 _this = _super.call.apply(_super, [this].concat(args)); 21843 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'L', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); 21844 _defineProperty(_assertThisInitialized(_this), "priority", 110); 21845 return _this; 21846 } 21847 _createClass(MonthParser, [{ 21848 key: "parse", 21849 value: function parse(dateString, token, match) { 21850 var valueCallback = function valueCallback(value) { 21851 return value - 1; 21852 }; 21853 switch (token) { 21854 // 1, 2, ..., 12 21855 case 'M': 21856 return mapValue(parseNumericPattern(numericPatterns.month, dateString), valueCallback); 21857 // 01, 02, ..., 12 21858 case 'MM': 21859 return mapValue(parseNDigits(2, dateString), valueCallback); 21860 // 1st, 2nd, ..., 12th 21861 case 'Mo': 21862 return mapValue(match.ordinalNumber(dateString, { 21863 unit: 'month' 21864 }), valueCallback); 21865 // Jan, Feb, ..., Dec 21866 case 'MMM': 21867 return match.month(dateString, { 21868 width: 'abbreviated', 21869 context: 'formatting' 21870 }) || match.month(dateString, { 21871 width: 'narrow', 21872 context: 'formatting' 21873 }); 21874 // J, F, ..., D 21875 case 'MMMMM': 21876 return match.month(dateString, { 21877 width: 'narrow', 21878 context: 'formatting' 21879 }); 21880 // January, February, ..., December 21881 case 'MMMM': 21882 default: 21883 return match.month(dateString, { 21884 width: 'wide', 21885 context: 'formatting' 21886 }) || match.month(dateString, { 21887 width: 'abbreviated', 21888 context: 'formatting' 21889 }) || match.month(dateString, { 21890 width: 'narrow', 21891 context: 'formatting' 21892 }); 21893 } 21894 } 21895 }, { 21896 key: "validate", 21897 value: function validate(_date, value) { 21898 return value >= 0 && value <= 11; 21899 } 21900 }, { 21901 key: "set", 21902 value: function set(date, _flags, value) { 21903 date.setUTCMonth(value, 1); 21904 date.setUTCHours(0, 0, 0, 0); 21905 return date; 21906 } 21907 }]); 21908 return MonthParser; 21909 }(Parser); 21910 21911 var StandAloneMonthParser = /*#__PURE__*/function (_Parser) { 21912 _inherits(StandAloneMonthParser, _Parser); 21913 var _super = _createSuper(StandAloneMonthParser); 21914 function StandAloneMonthParser() { 21915 var _this; 21916 _classCallCheck(this, StandAloneMonthParser); 21917 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 21918 args[_key] = arguments[_key]; 21919 } 21920 _this = _super.call.apply(_super, [this].concat(args)); 21921 _defineProperty(_assertThisInitialized(_this), "priority", 110); 21922 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'M', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); 21923 return _this; 21924 } 21925 _createClass(StandAloneMonthParser, [{ 21926 key: "parse", 21927 value: function parse(dateString, token, match) { 21928 var valueCallback = function valueCallback(value) { 21929 return value - 1; 21930 }; 21931 switch (token) { 21932 // 1, 2, ..., 12 21933 case 'L': 21934 return mapValue(parseNumericPattern(numericPatterns.month, dateString), valueCallback); 21935 // 01, 02, ..., 12 21936 case 'LL': 21937 return mapValue(parseNDigits(2, dateString), valueCallback); 21938 // 1st, 2nd, ..., 12th 21939 case 'Lo': 21940 return mapValue(match.ordinalNumber(dateString, { 21941 unit: 'month' 21942 }), valueCallback); 21943 // Jan, Feb, ..., Dec 21944 case 'LLL': 21945 return match.month(dateString, { 21946 width: 'abbreviated', 21947 context: 'standalone' 21948 }) || match.month(dateString, { 21949 width: 'narrow', 21950 context: 'standalone' 21951 }); 21952 // J, F, ..., D 21953 case 'LLLLL': 21954 return match.month(dateString, { 21955 width: 'narrow', 21956 context: 'standalone' 21957 }); 21958 // January, February, ..., December 21959 case 'LLLL': 21960 default: 21961 return match.month(dateString, { 21962 width: 'wide', 21963 context: 'standalone' 21964 }) || match.month(dateString, { 21965 width: 'abbreviated', 21966 context: 'standalone' 21967 }) || match.month(dateString, { 21968 width: 'narrow', 21969 context: 'standalone' 21970 }); 21971 } 21972 } 21973 }, {
vendor: 11,471 bytes, lines 21974-22284
21974 key: "validate", 21975 value: function validate(_date, value) { 21976 return value >= 0 && value <= 11; 21977 } 21978 }, { 21979 key: "set", 21980 value: function set(date, _flags, value) { 21981 date.setUTCMonth(value, 1); 21982 date.setUTCHours(0, 0, 0, 0); 21983 return date; 21984 } 21985 }]); 21986 return StandAloneMonthParser; 21987 }(Parser); 21988 21989 function setUTCWeek(dirtyDate, dirtyWeek, options) { 21990 requiredArgs(2, arguments); 21991 var date = toDate(dirtyDate); 21992 var week = toInteger(dirtyWeek); 21993 var diff = getUTCWeek(date, options) - week; 21994 date.setUTCDate(date.getUTCDate() - diff * 7); 21995 return date; 21996 } 21997 21998 var LocalWeekParser = /*#__PURE__*/function (_Parser) { 21999 _inherits(LocalWeekParser, _Parser); 22000 var _super = _createSuper(LocalWeekParser); 22001 function LocalWeekParser() { 22002 var _this; 22003 _classCallCheck(this, LocalWeekParser); 22004 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22005 args[_key] = arguments[_key]; 22006 } 22007 _this = _super.call.apply(_super, [this].concat(args)); 22008 _defineProperty(_assertThisInitialized(_this), "priority", 100); 22009 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'i', 't', 'T']); 22010 return _this; 22011 } 22012 _createClass(LocalWeekParser, [{ 22013 key: "parse", 22014 value: function parse(dateString, token, match) { 22015 switch (token) { 22016 case 'w': 22017 return parseNumericPattern(numericPatterns.week, dateString); 22018 case 'wo': 22019 return match.ordinalNumber(dateString, { 22020 unit: 'week' 22021 }); 22022 default: 22023 return parseNDigits(token.length, dateString); 22024 } 22025 } 22026 }, { 22027 key: "validate", 22028 value: function validate(_date, value) { 22029 return value >= 1 && value <= 53; 22030 } 22031 }, { 22032 key: "set", 22033 value: function set(date, _flags, value, options) { 22034 return startOfUTCWeek(setUTCWeek(date, value, options), options); 22035 } 22036 }]); 22037 return LocalWeekParser; 22038 }(Parser); 22039 22040 function setUTCISOWeek(dirtyDate, dirtyISOWeek) { 22041 requiredArgs(2, arguments); 22042 var date = toDate(dirtyDate); 22043 var isoWeek = toInteger(dirtyISOWeek); 22044 var diff = getUTCISOWeek(date) - isoWeek; 22045 date.setUTCDate(date.getUTCDate() - diff * 7); 22046 return date; 22047 } 22048 22049 var ISOWeekParser = /*#__PURE__*/function (_Parser) { 22050 _inherits(ISOWeekParser, _Parser); 22051 var _super = _createSuper(ISOWeekParser); 22052 function ISOWeekParser() { 22053 var _this; 22054 _classCallCheck(this, ISOWeekParser); 22055 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22056 args[_key] = arguments[_key]; 22057 } 22058 _this = _super.call.apply(_super, [this].concat(args)); 22059 _defineProperty(_assertThisInitialized(_this), "priority", 100); 22060 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['y', 'Y', 'u', 'q', 'Q', 'M', 'L', 'w', 'd', 'D', 'e', 'c', 't', 'T']); 22061 return _this; 22062 } 22063 _createClass(ISOWeekParser, [{ 22064 key: "parse", 22065 value: function parse(dateString, token, match) { 22066 switch (token) { 22067 case 'I': 22068 return parseNumericPattern(numericPatterns.week, dateString); 22069 case 'Io': 22070 return match.ordinalNumber(dateString, { 22071 unit: 'week' 22072 }); 22073 default: 22074 return parseNDigits(token.length, dateString); 22075 } 22076 } 22077 }, { 22078 key: "validate", 22079 value: function validate(_date, value) { 22080 return value >= 1 && value <= 53; 22081 } 22082 }, { 22083 key: "set", 22084 value: function set(date, _flags, value) { 22085 return startOfUTCISOWeek(setUTCISOWeek(date, value)); 22086 } 22087 }]); 22088 return ISOWeekParser; 22089 }(Parser); 22090 22091 var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; 22092 var DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; 22093 22094 // Day of the month 22095 var DateParser = /*#__PURE__*/function (_Parser) { 22096 _inherits(DateParser, _Parser); 22097 var _super = _createSuper(DateParser); 22098 function DateParser() { 22099 var _this; 22100 _classCallCheck(this, DateParser); 22101 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22102 args[_key] = arguments[_key]; 22103 } 22104 _this = _super.call.apply(_super, [this].concat(args)); 22105 _defineProperty(_assertThisInitialized(_this), "priority", 90); 22106 _defineProperty(_assertThisInitialized(_this), "subPriority", 1); 22107 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); 22108 return _this; 22109 } 22110 _createClass(DateParser, [{ 22111 key: "parse", 22112 value: function parse(dateString, token, match) { 22113 switch (token) { 22114 case 'd': 22115 return parseNumericPattern(numericPatterns.date, dateString); 22116 case 'do': 22117 return match.ordinalNumber(dateString, { 22118 unit: 'date' 22119 }); 22120 default: 22121 return parseNDigits(token.length, dateString); 22122 } 22123 } 22124 }, { 22125 key: "validate", 22126 value: function validate(date, value) { 22127 var year = date.getUTCFullYear(); 22128 var isLeapYear = isLeapYearIndex$1(year); 22129 var month = date.getUTCMonth(); 22130 if (isLeapYear) { 22131 return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month]; 22132 } else { 22133 return value >= 1 && value <= DAYS_IN_MONTH[month]; 22134 } 22135 } 22136 }, { 22137 key: "set", 22138 value: function set(date, _flags, value) { 22139 date.setUTCDate(value); 22140 date.setUTCHours(0, 0, 0, 0); 22141 return date; 22142 } 22143 }]); 22144 return DateParser; 22145 }(Parser); 22146 22147 var DayOfYearParser = /*#__PURE__*/function (_Parser) { 22148 _inherits(DayOfYearParser, _Parser); 22149 var _super = _createSuper(DayOfYearParser); 22150 function DayOfYearParser() { 22151 var _this; 22152 _classCallCheck(this, DayOfYearParser); 22153 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22154 args[_key] = arguments[_key]; 22155 } 22156 _this = _super.call.apply(_super, [this].concat(args)); 22157 _defineProperty(_assertThisInitialized(_this), "priority", 90); 22158 _defineProperty(_assertThisInitialized(_this), "subpriority", 1); 22159 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'M', 'L', 'w', 'I', 'd', 'E', 'i', 'e', 'c', 't', 'T']); 22160 return _this; 22161 } 22162 _createClass(DayOfYearParser, [{ 22163 key: "parse", 22164 value: function parse(dateString, token, match) { 22165 switch (token) { 22166 case 'D': 22167 case 'DD': 22168 return parseNumericPattern(numericPatterns.dayOfYear, dateString); 22169 case 'Do': 22170 return match.ordinalNumber(dateString, { 22171 unit: 'date' 22172 }); 22173 default: 22174 return parseNDigits(token.length, dateString); 22175 } 22176 } 22177 }, { 22178 key: "validate", 22179 value: function validate(date, value) { 22180 var year = date.getUTCFullYear(); 22181 var isLeapYear = isLeapYearIndex$1(year); 22182 if (isLeapYear) { 22183 return value >= 1 && value <= 366; 22184 } else { 22185 return value >= 1 && value <= 365; 22186 } 22187 } 22188 }, { 22189 key: "set", 22190 value: function set(date, _flags, value) { 22191 date.setUTCMonth(0, value); 22192 date.setUTCHours(0, 0, 0, 0); 22193 return date; 22194 } 22195 }]); 22196 return DayOfYearParser; 22197 }(Parser); 22198 22199 function setUTCDay(dirtyDate, dirtyDay, options) { 22200 var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; 22201 requiredArgs(2, arguments); 22202 var defaultOptions = getDefaultOptions(); 22203 var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); 22204 22205 // Test if weekStartsOn is between 0 and 6 _and_ is not NaN 22206 if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { 22207 throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); 22208 } 22209 var date = toDate(dirtyDate); 22210 var day = toInteger(dirtyDay); 22211 var currentDay = date.getUTCDay(); 22212 var remainder = day % 7; 22213 var dayIndex = (remainder + 7) % 7; 22214 var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay; 22215 date.setUTCDate(date.getUTCDate() + diff); 22216 return date; 22217 } 22218 22219 var DayParser = /*#__PURE__*/function (_Parser) { 22220 _inherits(DayParser, _Parser); 22221 var _super = _createSuper(DayParser); 22222 function DayParser() { 22223 var _this; 22224 _classCallCheck(this, DayParser); 22225 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22226 args[_key] = arguments[_key]; 22227 } 22228 _this = _super.call.apply(_super, [this].concat(args)); 22229 _defineProperty(_assertThisInitialized(_this), "priority", 90); 22230 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['D', 'i', 'e', 'c', 't', 'T']); 22231 return _this; 22232 } 22233 _createClass(DayParser, [{ 22234 key: "parse", 22235 value: function parse(dateString, token, match) { 22236 switch (token) { 22237 // Tue 22238 case 'E': 22239 case 'EE': 22240 case 'EEE': 22241 return match.day(dateString, { 22242 width: 'abbreviated', 22243 context: 'formatting' 22244 }) || match.day(dateString, { 22245 width: 'short', 22246 context: 'formatting' 22247 }) || match.day(dateString, { 22248 width: 'narrow', 22249 context: 'formatting' 22250 }); 22251 // T 22252 case 'EEEEE': 22253 return match.day(dateString, { 22254 width: 'narrow', 22255 context: 'formatting' 22256 }); 22257 // Tu 22258 case 'EEEEEE': 22259 return match.day(dateString, { 22260 width: 'short', 22261 context: 'formatting' 22262 }) || match.day(dateString, { 22263 width: 'narrow', 22264 context: 'formatting' 22265 }); 22266 // Tuesday 22267 case 'EEEE': 22268 default: 22269 return match.day(dateString, { 22270 width: 'wide', 22271 context: 'formatting' 22272 }) || match.day(dateString, { 22273 width: 'abbreviated', 22274 context: 'formatting' 22275 }) || match.day(dateString, { 22276 width: 'short', 22277 context: 'formatting' 22278 }) || match.day(dateString, { 22279 width: 'narrow', 22280 context: 'formatting' 22281 }); 22282 } 22283 } 22284 }, {
vendor: 6,259 bytes, lines 22285-22470
22285 key: "validate", 22286 value: function validate(_date, value) { 22287 return value >= 0 && value <= 6; 22288 } 22289 }, { 22290 key: "set", 22291 value: function set(date, _flags, value, options) { 22292 date = setUTCDay(date, value, options); 22293 date.setUTCHours(0, 0, 0, 0); 22294 return date; 22295 } 22296 }]); 22297 return DayParser; 22298 }(Parser); 22299 22300 var LocalDayParser = /*#__PURE__*/function (_Parser) { 22301 _inherits(LocalDayParser, _Parser); 22302 var _super = _createSuper(LocalDayParser); 22303 function LocalDayParser() { 22304 var _this; 22305 _classCallCheck(this, LocalDayParser); 22306 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22307 args[_key] = arguments[_key]; 22308 } 22309 _this = _super.call.apply(_super, [this].concat(args)); 22310 _defineProperty(_assertThisInitialized(_this), "priority", 90); 22311 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'E', 'i', 'c', 't', 'T']); 22312 return _this; 22313 } 22314 _createClass(LocalDayParser, [{ 22315 key: "parse", 22316 value: function parse(dateString, token, match, options) { 22317 var valueCallback = function valueCallback(value) { 22318 var wholeWeekDays = Math.floor((value - 1) / 7) * 7; 22319 return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays; 22320 }; 22321 switch (token) { 22322 // 3 22323 case 'e': 22324 case 'ee': 22325 // 03 22326 return mapValue(parseNDigits(token.length, dateString), valueCallback); 22327 // 3rd 22328 case 'eo': 22329 return mapValue(match.ordinalNumber(dateString, { 22330 unit: 'day' 22331 }), valueCallback); 22332 // Tue 22333 case 'eee': 22334 return match.day(dateString, { 22335 width: 'abbreviated', 22336 context: 'formatting' 22337 }) || match.day(dateString, { 22338 width: 'short', 22339 context: 'formatting' 22340 }) || match.day(dateString, { 22341 width: 'narrow', 22342 context: 'formatting' 22343 }); 22344 // T 22345 case 'eeeee': 22346 return match.day(dateString, { 22347 width: 'narrow', 22348 context: 'formatting' 22349 }); 22350 // Tu 22351 case 'eeeeee': 22352 return match.day(dateString, { 22353 width: 'short', 22354 context: 'formatting' 22355 }) || match.day(dateString, { 22356 width: 'narrow', 22357 context: 'formatting' 22358 }); 22359 // Tuesday 22360 case 'eeee': 22361 default: 22362 return match.day(dateString, { 22363 width: 'wide', 22364 context: 'formatting' 22365 }) || match.day(dateString, { 22366 width: 'abbreviated', 22367 context: 'formatting' 22368 }) || match.day(dateString, { 22369 width: 'short', 22370 context: 'formatting' 22371 }) || match.day(dateString, { 22372 width: 'narrow', 22373 context: 'formatting' 22374 }); 22375 } 22376 } 22377 }, { 22378 key: "validate", 22379 value: function validate(_date, value) { 22380 return value >= 0 && value <= 6; 22381 } 22382 }, { 22383 key: "set", 22384 value: function set(date, _flags, value, options) { 22385 date = setUTCDay(date, value, options); 22386 date.setUTCHours(0, 0, 0, 0); 22387 return date; 22388 } 22389 }]); 22390 return LocalDayParser; 22391 }(Parser); 22392 22393 var StandAloneLocalDayParser = /*#__PURE__*/function (_Parser) { 22394 _inherits(StandAloneLocalDayParser, _Parser); 22395 var _super = _createSuper(StandAloneLocalDayParser); 22396 function StandAloneLocalDayParser() { 22397 var _this; 22398 _classCallCheck(this, StandAloneLocalDayParser); 22399 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22400 args[_key] = arguments[_key]; 22401 } 22402 _this = _super.call.apply(_super, [this].concat(args)); 22403 _defineProperty(_assertThisInitialized(_this), "priority", 90); 22404 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'E', 'i', 'e', 't', 'T']); 22405 return _this; 22406 } 22407 _createClass(StandAloneLocalDayParser, [{ 22408 key: "parse", 22409 value: function parse(dateString, token, match, options) { 22410 var valueCallback = function valueCallback(value) { 22411 var wholeWeekDays = Math.floor((value - 1) / 7) * 7; 22412 return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays; 22413 }; 22414 switch (token) { 22415 // 3 22416 case 'c': 22417 case 'cc': 22418 // 03 22419 return mapValue(parseNDigits(token.length, dateString), valueCallback); 22420 // 3rd 22421 case 'co': 22422 return mapValue(match.ordinalNumber(dateString, { 22423 unit: 'day' 22424 }), valueCallback); 22425 // Tue 22426 case 'ccc': 22427 return match.day(dateString, { 22428 width: 'abbreviated', 22429 context: 'standalone' 22430 }) || match.day(dateString, { 22431 width: 'short', 22432 context: 'standalone' 22433 }) || match.day(dateString, { 22434 width: 'narrow', 22435 context: 'standalone' 22436 }); 22437 // T 22438 case 'ccccc': 22439 return match.day(dateString, { 22440 width: 'narrow', 22441 context: 'standalone' 22442 }); 22443 // Tu 22444 case 'cccccc': 22445 return match.day(dateString, { 22446 width: 'short', 22447 context: 'standalone' 22448 }) || match.day(dateString, { 22449 width: 'narrow', 22450 context: 'standalone' 22451 }); 22452 // Tuesday 22453 case 'cccc': 22454 default: 22455 return match.day(dateString, { 22456 width: 'wide', 22457 context: 'standalone' 22458 }) || match.day(dateString, { 22459 width: 'abbreviated', 22460 context: 'standalone' 22461 }) || match.day(dateString, { 22462 width: 'short', 22463 context: 'standalone' 22464 }) || match.day(dateString, { 22465 width: 'narrow', 22466 context: 'standalone' 22467 }); 22468 } 22469 } 22470 }, {
vendor: 5,581 bytes, lines 22471-22644
22471 key: "validate", 22472 value: function validate(_date, value) { 22473 return value >= 0 && value <= 6; 22474 } 22475 }, { 22476 key: "set", 22477 value: function set(date, _flags, value, options) { 22478 date = setUTCDay(date, value, options); 22479 date.setUTCHours(0, 0, 0, 0); 22480 return date; 22481 } 22482 }]); 22483 return StandAloneLocalDayParser; 22484 }(Parser); 22485 22486 function setUTCISODay(dirtyDate, dirtyDay) { 22487 requiredArgs(2, arguments); 22488 var day = toInteger(dirtyDay); 22489 if (day % 7 === 0) { 22490 day = day - 7; 22491 } 22492 var weekStartsOn = 1; 22493 var date = toDate(dirtyDate); 22494 var currentDay = date.getUTCDay(); 22495 var remainder = day % 7; 22496 var dayIndex = (remainder + 7) % 7; 22497 var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay; 22498 date.setUTCDate(date.getUTCDate() + diff); 22499 return date; 22500 } 22501 22502 var ISODayParser = /*#__PURE__*/function (_Parser) { 22503 _inherits(ISODayParser, _Parser); 22504 var _super = _createSuper(ISODayParser); 22505 function ISODayParser() { 22506 var _this; 22507 _classCallCheck(this, ISODayParser); 22508 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22509 args[_key] = arguments[_key]; 22510 } 22511 _this = _super.call.apply(_super, [this].concat(args)); 22512 _defineProperty(_assertThisInitialized(_this), "priority", 90); 22513 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['y', 'Y', 'u', 'q', 'Q', 'M', 'L', 'w', 'd', 'D', 'E', 'e', 'c', 't', 'T']); 22514 return _this; 22515 } 22516 _createClass(ISODayParser, [{ 22517 key: "parse", 22518 value: function parse(dateString, token, match) { 22519 var valueCallback = function valueCallback(value) { 22520 if (value === 0) { 22521 return 7; 22522 } 22523 return value; 22524 }; 22525 switch (token) { 22526 // 2 22527 case 'i': 22528 case 'ii': 22529 // 02 22530 return parseNDigits(token.length, dateString); 22531 // 2nd 22532 case 'io': 22533 return match.ordinalNumber(dateString, { 22534 unit: 'day' 22535 }); 22536 // Tue 22537 case 'iii': 22538 return mapValue(match.day(dateString, { 22539 width: 'abbreviated', 22540 context: 'formatting' 22541 }) || match.day(dateString, { 22542 width: 'short', 22543 context: 'formatting' 22544 }) || match.day(dateString, { 22545 width: 'narrow', 22546 context: 'formatting' 22547 }), valueCallback); 22548 // T 22549 case 'iiiii': 22550 return mapValue(match.day(dateString, { 22551 width: 'narrow', 22552 context: 'formatting' 22553 }), valueCallback); 22554 // Tu 22555 case 'iiiiii': 22556 return mapValue(match.day(dateString, { 22557 width: 'short', 22558 context: 'formatting' 22559 }) || match.day(dateString, { 22560 width: 'narrow', 22561 context: 'formatting' 22562 }), valueCallback); 22563 // Tuesday 22564 case 'iiii': 22565 default: 22566 return mapValue(match.day(dateString, { 22567 width: 'wide', 22568 context: 'formatting' 22569 }) || match.day(dateString, { 22570 width: 'abbreviated', 22571 context: 'formatting' 22572 }) || match.day(dateString, { 22573 width: 'short', 22574 context: 'formatting' 22575 }) || match.day(dateString, { 22576 width: 'narrow', 22577 context: 'formatting' 22578 }), valueCallback); 22579 } 22580 } 22581 }, { 22582 key: "validate", 22583 value: function validate(_date, value) { 22584 return value >= 1 && value <= 7; 22585 } 22586 }, { 22587 key: "set", 22588 value: function set(date, _flags, value) { 22589 date = setUTCISODay(date, value); 22590 date.setUTCHours(0, 0, 0, 0); 22591 return date; 22592 } 22593 }]); 22594 return ISODayParser; 22595 }(Parser); 22596 22597 var AMPMParser = /*#__PURE__*/function (_Parser) { 22598 _inherits(AMPMParser, _Parser); 22599 var _super = _createSuper(AMPMParser); 22600 function AMPMParser() { 22601 var _this; 22602 _classCallCheck(this, AMPMParser); 22603 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22604 args[_key] = arguments[_key]; 22605 } 22606 _this = _super.call.apply(_super, [this].concat(args)); 22607 _defineProperty(_assertThisInitialized(_this), "priority", 80); 22608 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['b', 'B', 'H', 'k', 't', 'T']); 22609 return _this; 22610 } 22611 _createClass(AMPMParser, [{ 22612 key: "parse", 22613 value: function parse(dateString, token, match) { 22614 switch (token) { 22615 case 'a': 22616 case 'aa': 22617 case 'aaa': 22618 return match.dayPeriod(dateString, { 22619 width: 'abbreviated', 22620 context: 'formatting' 22621 }) || match.dayPeriod(dateString, { 22622 width: 'narrow', 22623 context: 'formatting' 22624 }); 22625 case 'aaaaa': 22626 return match.dayPeriod(dateString, { 22627 width: 'narrow', 22628 context: 'formatting' 22629 }); 22630 case 'aaaa': 22631 default: 22632 return match.dayPeriod(dateString, { 22633 width: 'wide', 22634 context: 'formatting' 22635 }) || match.dayPeriod(dateString, { 22636 width: 'abbreviated', 22637 context: 'formatting' 22638 }) || match.dayPeriod(dateString, { 22639 width: 'narrow', 22640 context: 'formatting' 22641 }); 22642 } 22643 } 22644 }, {
vendor: 23,390 bytes, lines 22645-23281
22645 key: "set", 22646 value: function set(date, _flags, value) { 22647 date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0); 22648 return date; 22649 } 22650 }]); 22651 return AMPMParser; 22652 }(Parser); 22653 22654 var AMPMMidnightParser = /*#__PURE__*/function (_Parser) { 22655 _inherits(AMPMMidnightParser, _Parser); 22656 var _super = _createSuper(AMPMMidnightParser); 22657 function AMPMMidnightParser() { 22658 var _this; 22659 _classCallCheck(this, AMPMMidnightParser); 22660 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22661 args[_key] = arguments[_key]; 22662 } 22663 _this = _super.call.apply(_super, [this].concat(args)); 22664 _defineProperty(_assertThisInitialized(_this), "priority", 80); 22665 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['a', 'B', 'H', 'k', 't', 'T']); 22666 return _this; 22667 } 22668 _createClass(AMPMMidnightParser, [{ 22669 key: "parse", 22670 value: function parse(dateString, token, match) { 22671 switch (token) { 22672 case 'b': 22673 case 'bb': 22674 case 'bbb': 22675 return match.dayPeriod(dateString, { 22676 width: 'abbreviated', 22677 context: 'formatting' 22678 }) || match.dayPeriod(dateString, { 22679 width: 'narrow', 22680 context: 'formatting' 22681 }); 22682 case 'bbbbb': 22683 return match.dayPeriod(dateString, { 22684 width: 'narrow', 22685 context: 'formatting' 22686 }); 22687 case 'bbbb': 22688 default: 22689 return match.dayPeriod(dateString, { 22690 width: 'wide', 22691 context: 'formatting' 22692 }) || match.dayPeriod(dateString, { 22693 width: 'abbreviated', 22694 context: 'formatting' 22695 }) || match.dayPeriod(dateString, { 22696 width: 'narrow', 22697 context: 'formatting' 22698 }); 22699 } 22700 } 22701 }, { 22702 key: "set", 22703 value: function set(date, _flags, value) { 22704 date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0); 22705 return date; 22706 } 22707 }]); 22708 return AMPMMidnightParser; 22709 }(Parser); 22710 22711 var DayPeriodParser = /*#__PURE__*/function (_Parser) { 22712 _inherits(DayPeriodParser, _Parser); 22713 var _super = _createSuper(DayPeriodParser); 22714 function DayPeriodParser() { 22715 var _this; 22716 _classCallCheck(this, DayPeriodParser); 22717 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22718 args[_key] = arguments[_key]; 22719 } 22720 _this = _super.call.apply(_super, [this].concat(args)); 22721 _defineProperty(_assertThisInitialized(_this), "priority", 80); 22722 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['a', 'b', 't', 'T']); 22723 return _this; 22724 } 22725 _createClass(DayPeriodParser, [{ 22726 key: "parse", 22727 value: function parse(dateString, token, match) { 22728 switch (token) { 22729 case 'B': 22730 case 'BB': 22731 case 'BBB': 22732 return match.dayPeriod(dateString, { 22733 width: 'abbreviated', 22734 context: 'formatting' 22735 }) || match.dayPeriod(dateString, { 22736 width: 'narrow', 22737 context: 'formatting' 22738 }); 22739 case 'BBBBB': 22740 return match.dayPeriod(dateString, { 22741 width: 'narrow', 22742 context: 'formatting' 22743 }); 22744 case 'BBBB': 22745 default: 22746 return match.dayPeriod(dateString, { 22747 width: 'wide', 22748 context: 'formatting' 22749 }) || match.dayPeriod(dateString, { 22750 width: 'abbreviated', 22751 context: 'formatting' 22752 }) || match.dayPeriod(dateString, { 22753 width: 'narrow', 22754 context: 'formatting' 22755 }); 22756 } 22757 } 22758 }, { 22759 key: "set", 22760 value: function set(date, _flags, value) { 22761 date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0); 22762 return date; 22763 } 22764 }]); 22765 return DayPeriodParser; 22766 }(Parser); 22767 22768 var Hour1to12Parser = /*#__PURE__*/function (_Parser) { 22769 _inherits(Hour1to12Parser, _Parser); 22770 var _super = _createSuper(Hour1to12Parser); 22771 function Hour1to12Parser() { 22772 var _this; 22773 _classCallCheck(this, Hour1to12Parser); 22774 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22775 args[_key] = arguments[_key]; 22776 } 22777 _this = _super.call.apply(_super, [this].concat(args)); 22778 _defineProperty(_assertThisInitialized(_this), "priority", 70); 22779 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['H', 'K', 'k', 't', 'T']); 22780 return _this; 22781 } 22782 _createClass(Hour1to12Parser, [{ 22783 key: "parse", 22784 value: function parse(dateString, token, match) { 22785 switch (token) { 22786 case 'h': 22787 return parseNumericPattern(numericPatterns.hour12h, dateString); 22788 case 'ho': 22789 return match.ordinalNumber(dateString, { 22790 unit: 'hour' 22791 }); 22792 default: 22793 return parseNDigits(token.length, dateString); 22794 } 22795 } 22796 }, { 22797 key: "validate", 22798 value: function validate(_date, value) { 22799 return value >= 1 && value <= 12; 22800 } 22801 }, { 22802 key: "set", 22803 value: function set(date, _flags, value) { 22804 var isPM = date.getUTCHours() >= 12; 22805 if (isPM && value < 12) { 22806 date.setUTCHours(value + 12, 0, 0, 0); 22807 } else if (!isPM && value === 12) { 22808 date.setUTCHours(0, 0, 0, 0); 22809 } else { 22810 date.setUTCHours(value, 0, 0, 0); 22811 } 22812 return date; 22813 } 22814 }]); 22815 return Hour1to12Parser; 22816 }(Parser); 22817 22818 var Hour0to23Parser = /*#__PURE__*/function (_Parser) { 22819 _inherits(Hour0to23Parser, _Parser); 22820 var _super = _createSuper(Hour0to23Parser); 22821 function Hour0to23Parser() { 22822 var _this; 22823 _classCallCheck(this, Hour0to23Parser); 22824 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22825 args[_key] = arguments[_key]; 22826 } 22827 _this = _super.call.apply(_super, [this].concat(args)); 22828 _defineProperty(_assertThisInitialized(_this), "priority", 70); 22829 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['a', 'b', 'h', 'K', 'k', 't', 'T']); 22830 return _this; 22831 } 22832 _createClass(Hour0to23Parser, [{ 22833 key: "parse", 22834 value: function parse(dateString, token, match) { 22835 switch (token) { 22836 case 'H': 22837 return parseNumericPattern(numericPatterns.hour23h, dateString); 22838 case 'Ho': 22839 return match.ordinalNumber(dateString, { 22840 unit: 'hour' 22841 }); 22842 default: 22843 return parseNDigits(token.length, dateString); 22844 } 22845 } 22846 }, { 22847 key: "validate", 22848 value: function validate(_date, value) { 22849 return value >= 0 && value <= 23; 22850 } 22851 }, { 22852 key: "set", 22853 value: function set(date, _flags, value) { 22854 date.setUTCHours(value, 0, 0, 0); 22855 return date; 22856 } 22857 }]); 22858 return Hour0to23Parser; 22859 }(Parser); 22860 22861 var Hour0To11Parser = /*#__PURE__*/function (_Parser) { 22862 _inherits(Hour0To11Parser, _Parser); 22863 var _super = _createSuper(Hour0To11Parser); 22864 function Hour0To11Parser() { 22865 var _this; 22866 _classCallCheck(this, Hour0To11Parser); 22867 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22868 args[_key] = arguments[_key]; 22869 } 22870 _this = _super.call.apply(_super, [this].concat(args)); 22871 _defineProperty(_assertThisInitialized(_this), "priority", 70); 22872 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['h', 'H', 'k', 't', 'T']); 22873 return _this; 22874 } 22875 _createClass(Hour0To11Parser, [{ 22876 key: "parse", 22877 value: function parse(dateString, token, match) { 22878 switch (token) { 22879 case 'K': 22880 return parseNumericPattern(numericPatterns.hour11h, dateString); 22881 case 'Ko': 22882 return match.ordinalNumber(dateString, { 22883 unit: 'hour' 22884 }); 22885 default: 22886 return parseNDigits(token.length, dateString); 22887 } 22888 } 22889 }, { 22890 key: "validate", 22891 value: function validate(_date, value) { 22892 return value >= 0 && value <= 11; 22893 } 22894 }, { 22895 key: "set", 22896 value: function set(date, _flags, value) { 22897 var isPM = date.getUTCHours() >= 12; 22898 if (isPM && value < 12) { 22899 date.setUTCHours(value + 12, 0, 0, 0); 22900 } else { 22901 date.setUTCHours(value, 0, 0, 0); 22902 } 22903 return date; 22904 } 22905 }]); 22906 return Hour0To11Parser; 22907 }(Parser); 22908 22909 var Hour1To24Parser = /*#__PURE__*/function (_Parser) { 22910 _inherits(Hour1To24Parser, _Parser); 22911 var _super = _createSuper(Hour1To24Parser); 22912 function Hour1To24Parser() { 22913 var _this; 22914 _classCallCheck(this, Hour1To24Parser); 22915 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22916 args[_key] = arguments[_key]; 22917 } 22918 _this = _super.call.apply(_super, [this].concat(args)); 22919 _defineProperty(_assertThisInitialized(_this), "priority", 70); 22920 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['a', 'b', 'h', 'H', 'K', 't', 'T']); 22921 return _this; 22922 } 22923 _createClass(Hour1To24Parser, [{ 22924 key: "parse", 22925 value: function parse(dateString, token, match) { 22926 switch (token) { 22927 case 'k': 22928 return parseNumericPattern(numericPatterns.hour24h, dateString); 22929 case 'ko': 22930 return match.ordinalNumber(dateString, { 22931 unit: 'hour' 22932 }); 22933 default: 22934 return parseNDigits(token.length, dateString); 22935 } 22936 } 22937 }, { 22938 key: "validate", 22939 value: function validate(_date, value) { 22940 return value >= 1 && value <= 24; 22941 } 22942 }, { 22943 key: "set", 22944 value: function set(date, _flags, value) { 22945 var hours = value <= 24 ? value % 24 : value; 22946 date.setUTCHours(hours, 0, 0, 0); 22947 return date; 22948 } 22949 }]); 22950 return Hour1To24Parser; 22951 }(Parser); 22952 22953 var MinuteParser = /*#__PURE__*/function (_Parser) { 22954 _inherits(MinuteParser, _Parser); 22955 var _super = _createSuper(MinuteParser); 22956 function MinuteParser() { 22957 var _this; 22958 _classCallCheck(this, MinuteParser); 22959 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 22960 args[_key] = arguments[_key]; 22961 } 22962 _this = _super.call.apply(_super, [this].concat(args)); 22963 _defineProperty(_assertThisInitialized(_this), "priority", 60); 22964 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['t', 'T']); 22965 return _this; 22966 } 22967 _createClass(MinuteParser, [{ 22968 key: "parse", 22969 value: function parse(dateString, token, match) { 22970 switch (token) { 22971 case 'm': 22972 return parseNumericPattern(numericPatterns.minute, dateString); 22973 case 'mo': 22974 return match.ordinalNumber(dateString, { 22975 unit: 'minute' 22976 }); 22977 default: 22978 return parseNDigits(token.length, dateString); 22979 } 22980 } 22981 }, { 22982 key: "validate", 22983 value: function validate(_date, value) { 22984 return value >= 0 && value <= 59; 22985 } 22986 }, { 22987 key: "set", 22988 value: function set(date, _flags, value) { 22989 date.setUTCMinutes(value, 0, 0); 22990 return date; 22991 } 22992 }]); 22993 return MinuteParser; 22994 }(Parser); 22995 22996 var SecondParser = /*#__PURE__*/function (_Parser) { 22997 _inherits(SecondParser, _Parser); 22998 var _super = _createSuper(SecondParser); 22999 function SecondParser() { 23000 var _this; 23001 _classCallCheck(this, SecondParser); 23002 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 23003 args[_key] = arguments[_key]; 23004 } 23005 _this = _super.call.apply(_super, [this].concat(args)); 23006 _defineProperty(_assertThisInitialized(_this), "priority", 50); 23007 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['t', 'T']); 23008 return _this; 23009 } 23010 _createClass(SecondParser, [{ 23011 key: "parse", 23012 value: function parse(dateString, token, match) { 23013 switch (token) { 23014 case 's': 23015 return parseNumericPattern(numericPatterns.second, dateString); 23016 case 'so': 23017 return match.ordinalNumber(dateString, { 23018 unit: 'second' 23019 }); 23020 default: 23021 return parseNDigits(token.length, dateString); 23022 } 23023 } 23024 }, { 23025 key: "validate", 23026 value: function validate(_date, value) { 23027 return value >= 0 && value <= 59; 23028 } 23029 }, { 23030 key: "set", 23031 value: function set(date, _flags, value) { 23032 date.setUTCSeconds(value, 0); 23033 return date; 23034 } 23035 }]); 23036 return SecondParser; 23037 }(Parser); 23038 23039 var FractionOfSecondParser = /*#__PURE__*/function (_Parser) { 23040 _inherits(FractionOfSecondParser, _Parser); 23041 var _super = _createSuper(FractionOfSecondParser); 23042 function FractionOfSecondParser() { 23043 var _this; 23044 _classCallCheck(this, FractionOfSecondParser); 23045 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 23046 args[_key] = arguments[_key]; 23047 } 23048 _this = _super.call.apply(_super, [this].concat(args)); 23049 _defineProperty(_assertThisInitialized(_this), "priority", 30); 23050 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['t', 'T']); 23051 return _this; 23052 } 23053 _createClass(FractionOfSecondParser, [{ 23054 key: "parse", 23055 value: function parse(dateString, token) { 23056 var valueCallback = function valueCallback(value) { 23057 return Math.floor(value * Math.pow(10, -token.length + 3)); 23058 }; 23059 return mapValue(parseNDigits(token.length, dateString), valueCallback); 23060 } 23061 }, { 23062 key: "set", 23063 value: function set(date, _flags, value) { 23064 date.setUTCMilliseconds(value); 23065 return date; 23066 } 23067 }]); 23068 return FractionOfSecondParser; 23069 }(Parser); 23070 23071 var ISOTimezoneWithZParser = /*#__PURE__*/function (_Parser) { 23072 _inherits(ISOTimezoneWithZParser, _Parser); 23073 var _super = _createSuper(ISOTimezoneWithZParser); 23074 function ISOTimezoneWithZParser() { 23075 var _this; 23076 _classCallCheck(this, ISOTimezoneWithZParser); 23077 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 23078 args[_key] = arguments[_key]; 23079 } 23080 _this = _super.call.apply(_super, [this].concat(args)); 23081 _defineProperty(_assertThisInitialized(_this), "priority", 10); 23082 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['t', 'T', 'x']); 23083 return _this; 23084 } 23085 _createClass(ISOTimezoneWithZParser, [{ 23086 key: "parse", 23087 value: function parse(dateString, token) { 23088 switch (token) { 23089 case 'X': 23090 return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, dateString); 23091 case 'XX': 23092 return parseTimezonePattern(timezonePatterns.basic, dateString); 23093 case 'XXXX': 23094 return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, dateString); 23095 case 'XXXXX': 23096 return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, dateString); 23097 case 'XXX': 23098 default: 23099 return parseTimezonePattern(timezonePatterns.extended, dateString); 23100 } 23101 } 23102 }, { 23103 key: "set", 23104 value: function set(date, flags, value) { 23105 if (flags.timestampIsSet) { 23106 return date; 23107 } 23108 return new Date(date.getTime() - value); 23109 } 23110 }]); 23111 return ISOTimezoneWithZParser; 23112 }(Parser); 23113 23114 var ISOTimezoneParser = /*#__PURE__*/function (_Parser) { 23115 _inherits(ISOTimezoneParser, _Parser); 23116 var _super = _createSuper(ISOTimezoneParser); 23117 function ISOTimezoneParser() { 23118 var _this; 23119 _classCallCheck(this, ISOTimezoneParser); 23120 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 23121 args[_key] = arguments[_key]; 23122 } 23123 _this = _super.call.apply(_super, [this].concat(args)); 23124 _defineProperty(_assertThisInitialized(_this), "priority", 10); 23125 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", ['t', 'T', 'X']); 23126 return _this; 23127 } 23128 _createClass(ISOTimezoneParser, [{ 23129 key: "parse", 23130 value: function parse(dateString, token) { 23131 switch (token) { 23132 case 'x': 23133 return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, dateString); 23134 case 'xx': 23135 return parseTimezonePattern(timezonePatterns.basic, dateString); 23136 case 'xxxx': 23137 return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, dateString); 23138 case 'xxxxx': 23139 return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, dateString); 23140 case 'xxx': 23141 default: 23142 return parseTimezonePattern(timezonePatterns.extended, dateString); 23143 } 23144 } 23145 }, { 23146 key: "set", 23147 value: function set(date, flags, value) { 23148 if (flags.timestampIsSet) { 23149 return date; 23150 } 23151 return new Date(date.getTime() - value); 23152 } 23153 }]); 23154 return ISOTimezoneParser; 23155 }(Parser); 23156 23157 var TimestampSecondsParser = /*#__PURE__*/function (_Parser) { 23158 _inherits(TimestampSecondsParser, _Parser); 23159 var _super = _createSuper(TimestampSecondsParser); 23160 function TimestampSecondsParser() { 23161 var _this; 23162 _classCallCheck(this, TimestampSecondsParser); 23163 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 23164 args[_key] = arguments[_key]; 23165 } 23166 _this = _super.call.apply(_super, [this].concat(args)); 23167 _defineProperty(_assertThisInitialized(_this), "priority", 40); 23168 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", '*'); 23169 return _this; 23170 } 23171 _createClass(TimestampSecondsParser, [{ 23172 key: "parse", 23173 value: function parse(dateString) { 23174 return parseAnyDigitsSigned(dateString); 23175 } 23176 }, { 23177 key: "set", 23178 value: function set(_date, _flags, value) { 23179 return [new Date(value * 1000), { 23180 timestampIsSet: true 23181 }]; 23182 } 23183 }]); 23184 return TimestampSecondsParser; 23185 }(Parser); 23186 23187 var TimestampMillisecondsParser = /*#__PURE__*/function (_Parser) { 23188 _inherits(TimestampMillisecondsParser, _Parser); 23189 var _super = _createSuper(TimestampMillisecondsParser); 23190 function TimestampMillisecondsParser() { 23191 var _this; 23192 _classCallCheck(this, TimestampMillisecondsParser); 23193 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { 23194 args[_key] = arguments[_key]; 23195 } 23196 _this = _super.call.apply(_super, [this].concat(args)); 23197 _defineProperty(_assertThisInitialized(_this), "priority", 20); 23198 _defineProperty(_assertThisInitialized(_this), "incompatibleTokens", '*'); 23199 return _this; 23200 } 23201 _createClass(TimestampMillisecondsParser, [{ 23202 key: "parse", 23203 value: function parse(dateString) { 23204 return parseAnyDigitsSigned(dateString); 23205 } 23206 }, { 23207 key: "set", 23208 value: function set(_date, _flags, value) { 23209 return [new Date(value), { 23210 timestampIsSet: true 23211 }]; 23212 } 23213 }]); 23214 return TimestampMillisecondsParser; 23215 }(Parser); 23216 23217 /* 23218 * | | Unit | | Unit | 23219 * |-----|--------------------------------|-----|--------------------------------| 23220 * | a | AM, PM | A* | Milliseconds in day | 23221 * | b | AM, PM, noon, midnight | B | Flexible day period | 23222 * | c | Stand-alone local day of week | C* | Localized hour w/ day period | 23223 * | d | Day of month | D | Day of year | 23224 * | e | Local day of week | E | Day of week | 23225 * | f | | F* | Day of week in month | 23226 * | g* | Modified Julian day | G | Era | 23227 * | h | Hour [1-12] | H | Hour [0-23] | 23228 * | i! | ISO day of week | I! | ISO week of year | 23229 * | j* | Localized hour w/ day period | J* | Localized hour w/o day period | 23230 * | k | Hour [1-24] | K | Hour [0-11] | 23231 * | l* | (deprecated) | L | Stand-alone month | 23232 * | m | Minute | M | Month | 23233 * | n | | N | | 23234 * | o! | Ordinal number modifier | O* | Timezone (GMT) | 23235 * | p | | P | | 23236 * | q | Stand-alone quarter | Q | Quarter | 23237 * | r* | Related Gregorian year | R! | ISO week-numbering year | 23238 * | s | Second | S | Fraction of second | 23239 * | t! | Seconds timestamp | T! | Milliseconds timestamp | 23240 * | u | Extended year | U* | Cyclic year | 23241 * | v* | Timezone (generic non-locat.) | V* | Timezone (location) | 23242 * | w | Local week of year | W* | Week of month | 23243 * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) | 23244 * | y | Year (abs) | Y | Local week-numbering year | 23245 * | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) | 23246 * 23247 * Letters marked by * are not implemented but reserved by Unicode standard. 23248 * 23249 * Letters marked by ! are non-standard, but implemented by date-fns: 23250 * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs) 23251 * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days, 23252 * i.e. 7 for Sunday, 1 for Monday, etc. 23253 * - `I` is ISO week of year, as opposed to `w` which is local week of year. 23254 * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year. 23255 * `R` is supposed to be used in conjunction with `I` and `i` 23256 * for universal ISO week-numbering date, whereas 23257 * `Y` is supposed to be used in conjunction with `w` and `e` 23258 * for week-numbering date specific to the locale. 23259 */ 23260 var parsers = { 23261 G: new EraParser(), 23262 y: new YearParser(), 23263 Y: new LocalWeekYearParser(), 23264 R: new ISOWeekYearParser(), 23265 u: new ExtendedYearParser(), 23266 Q: new QuarterParser(), 23267 q: new StandAloneQuarterParser(), 23268 M: new MonthParser(), 23269 L: new StandAloneMonthParser(), 23270 w: new LocalWeekParser(), 23271 I: new ISOWeekParser(), 23272 d: new DateParser(), 23273 D: new DayOfYearParser(), 23274 E: new DayParser(), 23275 e: new LocalDayParser(), 23276 c: new StandAloneLocalDayParser(), 23277 i: new ISODayParser(), 23278 a: new AMPMParser(), 23279 b: new AMPMMidnightParser(), 23280 B: new DayPeriodParser(), 23281 h: new Hour1to12Parser(),
23282 H: new Hour0to23Parser(), 23283 K: new Hour0To11Parser(), 23284 k: new Hour1To24Parser(), 23285 m: new MinuteParser(), 23286 s: new SecondParser(), 23287 S: new FractionOfSecondParser(), 23288 X: new ISOTimezoneWithZParser(), 23289 x: new ISOTimezoneParser(), 23290 t: new TimestampSecondsParser(), 23291 T: new TimestampMillisecondsParser() 23292 }; 23293 23294 // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token 23295 // (one of the certain letters followed by `o`) 23296 // - (\w)\1* matches any sequences of the same letter 23297 // - '' matches two quote characters in a row 23298 // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), 23299 // except a single quote symbol, which ends the sequence. 23300 // Two quote characters do not end the sequence. 23301 // If there is no matching single quote 23302 // then the sequence will continue until the end of the string. 23303 // - . matches any single character unmatched by previous parts of the RegExps 23304 var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; 23305 23306 // This RegExp catches symbols escaped by quotes, and also 23307 // sequences of symbols P, p, and the combinations like `PPPPPPPppppp` 23308 var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; 23309 var escapedStringRegExp = /^'([^]*?)'?$/; 23310 var doubleQuoteRegExp = /''/g; 23311 var notWhitespaceRegExp = /\S/; 23312 var unescapedLatinCharacterRegExp = /[a-zA-Z]/; 23313 23314 /** 23315 * @name parse 23316 * @category Common Helpers 23317 * @summary Parse the date. 23318 * 23319 * @description 23320 * Return the date parsed from string using the given format string. 23321 * 23322 * > â ï¸ Please note that the `format` tokens differ from Moment.js and other libraries. 23323 * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 23324 * 23325 * The characters in the format string wrapped between two single quotes characters (') are escaped. 23326 * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. 23327 * 23328 * Format of the format string is based on Unicode Technical Standard #35: 23329 * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table 23330 * with a few additions (see note 5 below the table). 23331 * 23332 * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited 23333 * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception: 23334 * 23335 * ```javascript 23336 * parse('23 AM', 'HH a', new Date()) 23337 * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time 23338 * ``` 23339 * 23340 * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true 23341 * 23342 * Accepted format string patterns: 23343 * | Unit |Prior| Pattern | Result examples | Notes | 23344 * |---------------------------------|-----|---------|-----------------------------------|-------| 23345 * | Era | 140 | G..GGG | AD, BC | | 23346 * | | | GGGG | Anno Domini, Before Christ | 2 | 23347 * | | | GGGGG | A, B | | 23348 * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 | 23349 * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 | 23350 * | | | yy | 44, 01, 00, 17 | 4 | 23351 * | | | yyy | 044, 001, 123, 999 | 4 | 23352 * | | | yyyy | 0044, 0001, 1900, 2017 | 4 | 23353 * | | | yyyyy | ... | 2,4 | 23354 * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 | 23355 * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 | 23356 * | | | YY | 44, 01, 00, 17 | 4,6 | 23357 * | | | YYY | 044, 001, 123, 999 | 4 | 23358 * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 | 23359 * | | | YYYYY | ... | 2,4 | 23360 * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 | 23361 * | | | RR | -43, 01, 00, 17 | 4,5 | 23362 * | | | RRR | -043, 001, 123, 999, -999 | 4,5 | 23363 * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 | 23364 * | | | RRRRR | ... | 2,4,5 | 23365 * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 | 23366 * | | | uu | -43, 01, 99, -99 | 4 | 23367 * | | | uuu | -043, 001, 123, 999, -999 | 4 | 23368 * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 | 23369 * | | | uuuuu | ... | 2,4 | 23370 * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | | 23371 * | | | Qo | 1st, 2nd, 3rd, 4th | 5 | 23372 * | | | QQ | 01, 02, 03, 04 | | 23373 * | | | QQQ | Q1, Q2, Q3, Q4 | | 23374 * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | 23375 * | | | QQQQQ | 1, 2, 3, 4 | 4 | 23376 * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | | 23377 * | | | qo | 1st, 2nd, 3rd, 4th | 5 | 23378 * | | | qq | 01, 02, 03, 04 | | 23379 * | | | qqq | Q1, Q2, Q3, Q4 | | 23380 * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 | 23381 * | | | qqqqq | 1, 2, 3, 4 | 3 | 23382 * | Month (formatting) | 110 | M | 1, 2, ..., 12 | | 23383 * | | | Mo | 1st, 2nd, ..., 12th | 5 | 23384 * | | | MM | 01, 02, ..., 12 | | 23385 * | | | MMM | Jan, Feb, ..., Dec | | 23386 * | | | MMMM | January, February, ..., December | 2 | 23387 * | | | MMMMM | J, F, ..., D | | 23388 * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | | 23389 * | | | Lo | 1st, 2nd, ..., 12th | 5 | 23390 * | | | LL | 01, 02, ..., 12 | | 23391 * | | | LLL | Jan, Feb, ..., Dec | | 23392 * | | | LLLL | January, February, ..., December | 2 | 23393 * | | | LLLLL | J, F, ..., D | | 23394 * | Local week of year | 100 | w | 1, 2, ..., 53 | | 23395 * | | | wo | 1st, 2nd, ..., 53th | 5 | 23396 * | | | ww | 01, 02, ..., 53 | | 23397 * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 | 23398 * | | | Io | 1st, 2nd, ..., 53th | 5 | 23399 * | | | II | 01, 02, ..., 53 | 5 | 23400 * | Day of month | 90 | d | 1, 2, ..., 31 | | 23401 * | | | do | 1st, 2nd, ..., 31st | 5 | 23402 * | | | dd | 01, 02, ..., 31 | | 23403 * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 | 23404 * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 | 23405 * | | | DD | 01, 02, ..., 365, 366 | 7 | 23406 * | | | DDD | 001, 002, ..., 365, 366 | | 23407 * | | | DDDD | ... | 2 | 23408 * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | | 23409 * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 | 23410 * | | | EEEEE | M, T, W, T, F, S, S | | 23411 * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | 23412 * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 | 23413 * | | | io | 1st, 2nd, ..., 7th | 5 | 23414 * | | | ii | 01, 02, ...,
2341407 | 5 | 23415 * | | | iii | Mon, Tue, Wed, ..., Sun | 5 | 23416 * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 | 23417 * | | | iiiii | M, T, W, T, F, S, S | 5 | 23418 * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 | 23419 * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | | 23420 * | | | eo | 2nd, 3rd, ..., 1st | 5 | 23421 * | | | ee | 02, 03, ..., 01 | | 23422 * | | | eee | Mon, Tue, Wed, ..., Sun | | 23423 * | | | eeee | Monday, Tuesday, ..., Sunday | 2 | 23424 * | | | eeeee | M, T, W, T, F, S, S | | 23425 * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | 23426 * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | | 23427 * | | | co | 2nd, 3rd, ..., 1st | 5 | 23428 * | | | cc | 02, 03, ..., 01 | | 23429 * | | | ccc | Mon, Tue, Wed, ..., Sun | | 23430 * | | | cccc | Monday, Tuesday, ..., Sunday | 2 | 23431 * | | | ccccc | M, T, W, T, F, S, S | | 23432 * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | 23433 * | AM, PM | 80 | a..aaa | AM, PM | | 23434 * | | | aaaa | a.m., p.m. | 2 | 23435 * | | | aaaaa | a, p | | 23436 * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | | 23437 * | | | bbbb | a.m., p.m., noon, midnight | 2 | 23438 * | | | bbbbb | a, p, n, mi | | 23439 * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | | 23440 * | | | BBBB | at night, in the morning, ... | 2 | 23441 * | | | BBBBB | at night, in the morning, ... | | 23442 * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | | 23443 * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 | 23444 * | | | hh | 01, 02, ..., 11, 12 | | 23445 * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | | 23446 * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 | 23447 * | | | HH | 00, 01, 02, ..., 23 | | 23448 * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | | 23449 * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 | 23450 * | | | KK | 01, 02, ..., 11, 00 | | 23451 * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | | 23452 * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 | 23453 * | | | kk | 24, 01, 02, ..., 23 | | 23454 * | Minute | 60 | m | 0, 1, ..., 59 | | 23455 * | | | mo | 0th, 1st, ..., 59th | 5 | 23456 * | | | mm | 00, 01, ..., 59 | | 23457 * | Second | 50 | s | 0, 1, ..., 59 | | 23458 * | | | so | 0th, 1st, ..., 59th | 5 | 23459 * | | | ss | 00, 01, ..., 59 | | 23460 * | Seconds timestamp | 40 | t | 512969520 | | 23461 * | | | tt | ... | 2 | 23462 * | Fraction of second | 30 | S | 0, 1, ..., 9 | | 23463 * | | | SS | 00, 01, ..., 99 | | 23464 * | | | SSS | 000, 001, ..., 999 | | 23465 * | | | SSSS | ... | 2 | 23466 * | Milliseconds timestamp | 20 | T | 512969520900 | | 23467 * | | | TT | ... | 2 | 23468 * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | | 23469 * | | | XX | -0800, +0530, Z | | 23470 * | | | XXX | -08:00, +05:30, Z | | 23471 * | | | XXXX | -0800, +0530, Z, +123456 | 2 | 23472 * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | 23473 * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | | 23474 * | | | xx | -0800, +0530, +0000 | | 23475 * | | | xxx | -08:00, +05:30, +00:00 | 2 | 23476 * | | | xxxx | -0800, +0530, +0000, +123456 | | 23477 * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | 23478 * | Long localized date | NA | P | 05/29/1453 | 5,8 | 23479 * | | | PP | May 29, 1453 | | 23480 * | | | PPP | May 29th, 1453 | | 23481 * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 | 23482 * | Long localized time | NA | p | 12:00 AM | 5,8 | 23483 * | | | pp | 12:00:00 AM | | 23484 * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | | 23485 * | | | PPpp | May 29, 1453, 12:00:00 AM | | 23486 * | | | PPPpp | May 29th, 1453 at ... | | 23487 * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 | 23488 * Notes: 23489 * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale 23490 * are the same as "stand-alone" units, but are different in some languages. 23491 * "Formatting" units are declined according to the rules of the language 23492 * in the context of a date. "Stand-alone" units are always nominative singular. 23493 * In `format` function, they will produce different result: 23494 * 23495 * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` 23496 * 23497 * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` 23498 * 23499 * `parse` will try to match both formatting and stand-alone units interchangably. 23500 * 23501 * 2. Any sequence of the identical letters is a pattern, unless it is escaped by 23502 * the single quote characters (see below). 23503 * If the sequence is longer than listed in table: 23504 * - for numerical units (`yyyyyyyy`) `parse` will try to match a number 23505 * as wide as the sequence 23506 * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit. 23507 * These variations are marked with "2" in the last column of the table. 23508 * 23509 * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. 23510 * These tokens represent the shortest form of the quarter. 23511 * 23512 * 4. The main difference between `y` and `u` patterns are B.C. years: 23513 * 23514 * | Year | `y` | `u` | 23515 * |------|-----|-----| 23516 * | AC 1 | 1 | 1 | 23517 * | BC 1 | 1 | 0 | 23518 * | BC 2 | 2 | -1 | 23519 * 23520 * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`: 23521 * 23522 * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00` 23523 * 23524 * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00` 23525 * 23526 * while `uu` will just assign the year as is: 23527 * 23528 * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00` 23529 * 23530 * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00` 23531 * 23532 * The same difference is true for local and ISO week-numbering years (`Y` and `R`), 23533 * except local week-numbering years are dependent on `options.weekStartsOn` 23534 * and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear} 23535 * and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}). 23536 * 23537 * 5. These patterns are not in the Unicode Technical Standard #35: 23538 * - `i`: ISO day of week 23539 * - `I`: ISO week of year 23540 * - `R`: ISO week-numbering year 23541 * - `o`: ordinal number modifier 23542 * - `P`: long localized date 23543 * - `p`: long localized time 23544 * 23545 * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. 23546 * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 23547 * 23548 * 7. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month. 23549 * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 23550 *
23551 * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based 23552 * on the given locale. 23553 * 23554 * using `en-US` locale: `P` => `MM/dd/yyyy` 23555 * using `en-US` locale: `p` => `hh:mm a` 23556 * using `pt-BR` locale: `P` => `dd/MM/yyyy` 23557 * using `pt-BR` locale: `p` => `HH:mm` 23558 * 23559 * Values will be assigned to the date in the descending order of its unit's priority. 23560 * Units of an equal priority overwrite each other in the order of appearance. 23561 * 23562 * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year), 23563 * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing. 23564 * 23565 * `referenceDate` must be passed for correct work of the function. 23566 * If you're not sure which `referenceDate` to supply, create a new instance of Date: 23567 * `parse('02/11/2014', 'MM/dd/yyyy', new Date())` 23568 * In this case parsing will be done in the context of the current date. 23569 * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`, 23570 * then `Invalid Date` will be returned. 23571 * 23572 * The result may vary by locale. 23573 * 23574 * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned. 23575 * 23576 * If parsing failed, `Invalid Date` will be returned. 23577 * Invalid Date is a Date, whose time value is NaN. 23578 * Time value of Date: http://es5.github.io/#x15.9.1.1 23579 * 23580 * @param {String} dateString - the string to parse 23581 * @param {String} formatString - the string of tokens 23582 * @param {Date|Number} referenceDate - defines values missing from the parsed dateString 23583 * @param {Object} [options] - an object with options. 23584 * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} 23585 * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) 23586 * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year 23587 * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; 23588 * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 23589 * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; 23590 * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 23591 * @returns {Date} the parsed date 23592 * @throws {TypeError} 3 arguments required 23593 * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 23594 * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 23595 * @throws {RangeError} `options.locale` must contain `match` property 23596 * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 23597 * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 23598 * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 23599 * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md 23600 * @throws {RangeError} format string contains an unescaped latin alphabet character 23601 * 23602 * @example 23603 * // Parse 11 February 2014 from middle-endian format: 23604 * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date()) 23605 * //=> Tue Feb 11 2014 00:00:00 23606 * 23607 * @example 23608 * // Parse 28th of February in Esperanto locale in the context of 2010 year: 23609 * import eo from 'date-fns/locale/eo' 23610 * var result = parse('28-a de februaro', "do 'de' MMMM", new Date(2010, 0, 1), { 23611 * locale: eo 23612 * }) 23613 * //=> Sun Feb 28 2010 00:00:00 23614 */ 23615 function parse(dirtyDateString, dirtyFormatString, dirtyReferenceDate, options) { 23616 var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; 23617 requiredArgs(3, arguments);
vendor: 13,123 bytes, lines 23618-23917
23618 var dateString = String(dirtyDateString); 23619 var formatString = String(dirtyFormatString); 23620 var defaultOptions = getDefaultOptions(); 23621 var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : defaultLocale; 23622 if (!locale.match) { 23623 throw new RangeError('locale must contain match property'); 23624 } 23625 var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); 23626 23627 // Test if weekStartsOn is between 1 and 7 _and_ is not NaN 23628 if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { 23629 throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); 23630 } 23631 var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); 23632 23633 // Test if weekStartsOn is between 0 and 6 _and_ is not NaN 23634 if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { 23635 throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); 23636 } 23637 if (formatString === '') { 23638 if (dateString === '') { 23639 return toDate(dirtyReferenceDate); 23640 } else { 23641 return new Date(NaN); 23642 } 23643 } 23644 var subFnOptions = { 23645 firstWeekContainsDate: firstWeekContainsDate, 23646 weekStartsOn: weekStartsOn, 23647 locale: locale 23648 }; 23649 23650 // If timezone isn't specified, it will be set to the system timezone 23651 var setters = [new DateToSystemTimezoneSetter()]; 23652 var tokens = formatString.match(longFormattingTokensRegExp).map(function (substring) { 23653 var firstCharacter = substring[0]; 23654 if (firstCharacter in longFormatters$1) { 23655 var longFormatter = longFormatters$1[firstCharacter]; 23656 return longFormatter(substring, locale.formatLong); 23657 } 23658 return substring; 23659 }).join('').match(formattingTokensRegExp); 23660 var usedTokens = []; 23661 var _iterator = _createForOfIteratorHelper(tokens), 23662 _step; 23663 try { 23664 var _loop = function _loop() { 23665 var token = _step.value; 23666 if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(token)) { 23667 throwProtectedError(token, formatString, dirtyDateString); 23668 } 23669 if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(token)) { 23670 throwProtectedError(token, formatString, dirtyDateString); 23671 } 23672 var firstCharacter = token[0]; 23673 var parser = parsers[firstCharacter]; 23674 if (parser) { 23675 var incompatibleTokens = parser.incompatibleTokens; 23676 if (Array.isArray(incompatibleTokens)) { 23677 var incompatibleToken = usedTokens.find(function (usedToken) { 23678 return incompatibleTokens.includes(usedToken.token) || usedToken.token === firstCharacter; 23679 }); 23680 if (incompatibleToken) { 23681 throw new RangeError("The format string mustn't contain `".concat(incompatibleToken.fullToken, "` and `").concat(token, "` at the same time")); 23682 } 23683 } else if (parser.incompatibleTokens === '*' && usedTokens.length > 0) { 23684 throw new RangeError("The format string mustn't contain `".concat(token, "` and any other token at the same time")); 23685 } 23686 usedTokens.push({ 23687 token: firstCharacter, 23688 fullToken: token 23689 }); 23690 var parseResult = parser.run(dateString, token, locale.match, subFnOptions); 23691 if (!parseResult) { 23692 return { 23693 v: new Date(NaN) 23694 }; 23695 } 23696 setters.push(parseResult.setter); 23697 dateString = parseResult.rest; 23698 } else { 23699 if (firstCharacter.match(unescapedLatinCharacterRegExp)) { 23700 throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); 23701 } 23702 23703 // Replace two single quote characters with one single quote character 23704 if (token === "''") { 23705 token = "'"; 23706 } else if (firstCharacter === "'") { 23707 token = cleanEscapedString(token); 23708 } 23709 23710 // Cut token from string, or, if string doesn't match the token, return Invalid Date 23711 if (dateString.indexOf(token) === 0) { 23712 dateString = dateString.slice(token.length); 23713 } else { 23714 return { 23715 v: new Date(NaN) 23716 }; 23717 } 23718 } 23719 }; 23720 for (_iterator.s(); !(_step = _iterator.n()).done;) { 23721 var _ret = _loop(); 23722 if (_typeof(_ret) === "object") return _ret.v; 23723 } 23724 23725 // Check if the remaining input contains something other than whitespace 23726 } catch (err) { 23727 _iterator.e(err); 23728 } finally { 23729 _iterator.f(); 23730 } 23731 if (dateString.length > 0 && notWhitespaceRegExp.test(dateString)) { 23732 return new Date(NaN); 23733 } 23734 var uniquePrioritySetters = setters.map(function (setter) { 23735 return setter.priority; 23736 }).sort(function (a, b) { 23737 return b - a; 23738 }).filter(function (priority, index, array) { 23739 return array.indexOf(priority) === index; 23740 }).map(function (priority) { 23741 return setters.filter(function (setter) { 23742 return setter.priority === priority; 23743 }).sort(function (a, b) { 23744 return b.subPriority - a.subPriority; 23745 }); 23746 }).map(function (setterArray) { 23747 return setterArray[0]; 23748 }); 23749 var date = toDate(dirtyReferenceDate); 23750 if (isNaN(date.getTime())) { 23751 return new Date(NaN); 23752 } 23753 23754 // Convert the date in system timezone to the same date in UTC+00:00 timezone. 23755 var utcDate = subMilliseconds(date, getTimezoneOffsetInMilliseconds(date)); 23756 var flags = {}; 23757 var _iterator2 = _createForOfIteratorHelper(uniquePrioritySetters), 23758 _step2; 23759 try { 23760 for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { 23761 var setter = _step2.value; 23762 if (!setter.validate(utcDate, subFnOptions)) { 23763 return new Date(NaN); 23764 } 23765 var result = setter.set(utcDate, flags, subFnOptions); 23766 // Result is tuple (date, flags) 23767 if (Array.isArray(result)) { 23768 utcDate = result[0]; 23769 assign(flags, result[1]); 23770 // Result is date 23771 } else { 23772 utcDate = result; 23773 } 23774 } 23775 } catch (err) { 23776 _iterator2.e(err); 23777 } finally { 23778 _iterator2.f(); 23779 } 23780 return utcDate; 23781 } 23782 function cleanEscapedString(input) { 23783 return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'"); 23784 } 23785 23786 /** 23787 * @name startOfHour 23788 * @category Hour Helpers 23789 * @summary Return the start of an hour for the given date. 23790 * 23791 * @description 23792 * Return the start of an hour for the given date. 23793 * The result will be in the local timezone. 23794 * 23795 * @param {Date|Number} date - the original date 23796 * @returns {Date} the start of an hour 23797 * @throws {TypeError} 1 argument required 23798 * 23799 * @example 23800 * // The start of an hour for 2 September 2014 11:55:00: 23801 * const result = startOfHour(new Date(2014, 8, 2, 11, 55)) 23802 * //=> Tue Sep 02 2014 11:00:00 23803 */ 23804 function startOfHour(dirtyDate) { 23805 requiredArgs(1, arguments); 23806 var date = toDate(dirtyDate); 23807 date.setMinutes(0, 0, 0); 23808 return date; 23809 } 23810 23811 /** 23812 * @name startOfSecond 23813 * @category Second Helpers 23814 * @summary Return the start of a second for the given date. 23815 * 23816 * @description 23817 * Return the start of a second for the given date. 23818 * The result will be in the local timezone. 23819 * 23820 * @param {Date|Number} date - the original date 23821 * @returns {Date} the start of a second 23822 * @throws {TypeError} 1 argument required 23823 * 23824 * @example 23825 * // The start of a second for 1 December 2014 22:15:45.400: 23826 * const result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) 23827 * //=> Mon Dec 01 2014 22:15:45.000 23828 */ 23829 function startOfSecond(dirtyDate) { 23830 requiredArgs(1, arguments); 23831 var date = toDate(dirtyDate); 23832 date.setMilliseconds(0); 23833 return date; 23834 } 23835 23836 /** 23837 * @name parseISO 23838 * @category Common Helpers 23839 * @summary Parse ISO string 23840 * 23841 * @description 23842 * Parse the given string in ISO 8601 format and return an instance of Date. 23843 * 23844 * Function accepts complete ISO 8601 formats as well as partial implementations. 23845 * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 23846 * 23847 * If the argument isn't a string, the function cannot parse the string or 23848 * the values are invalid, it returns Invalid Date. 23849 * 23850 * @param {String} argument - the value to convert 23851 * @param {Object} [options] - an object with options. 23852 * @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format 23853 * @returns {Date} the parsed date in the local time zone 23854 * @throws {TypeError} 1 argument required 23855 * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2 23856 * 23857 * @example 23858 * // Convert string '2014-02-11T11:30:30' to date: 23859 * const result = parseISO('2014-02-11T11:30:30') 23860 * //=> Tue Feb 11 2014 11:30:30 23861 * 23862 * @example 23863 * // Convert string '+02014101' to date, 23864 * // if the additional number of digits in the extended year format is 1: 23865 * const result = parseISO('+02014101', { additionalDigits: 1 }) 23866 * //=> Fri Apr 11 2014 00:00:00 23867 */ 23868 function parseISO(argument, options) { 23869 var _options$additionalDi; 23870 requiredArgs(1, arguments); 23871 var additionalDigits = toInteger((_options$additionalDi = options === null || options === void 0 ? void 0 : options.additionalDigits) !== null && _options$additionalDi !== void 0 ? _options$additionalDi : 2); 23872 if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) { 23873 throw new RangeError('additionalDigits must be 0, 1 or 2'); 23874 } 23875 if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) { 23876 return new Date(NaN); 23877 } 23878 var dateStrings = splitDateString(argument); 23879 var date; 23880 if (dateStrings.date) { 23881 var parseYearResult = parseYear(dateStrings.date, additionalDigits); 23882 date = parseDate(parseYearResult.restDateString, parseYearResult.year); 23883 } 23884 if (!date || isNaN(date.getTime())) { 23885 return new Date(NaN); 23886 } 23887 var timestamp = date.getTime(); 23888 var time = 0; 23889 var offset; 23890 if (dateStrings.time) { 23891 time = parseTime(dateStrings.time); 23892 if (isNaN(time)) { 23893 return new Date(NaN); 23894 } 23895 } 23896 if (dateStrings.timezone) { 23897 offset = parseTimezone(dateStrings.timezone); 23898 if (isNaN(offset)) { 23899 return new Date(NaN); 23900 } 23901 } else { 23902 var dirtyDate = new Date(timestamp + time); 23903 // js parsed string assuming it's in UTC timezone 23904 // but we need it to be parsed in our timezone 23905 // so we use utc values to build date in our timezone. 23906 // Year values from 0 to 99 map to the years 1900 to 1999 23907 // so set year explicitly with setFullYear. 23908 var result = new Date(0); 23909 result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate()); 23910 result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds()); 23911 return result; 23912 } 23913 return new Date(timestamp + time + offset); 23914 } 23915 var patterns = { 23916 dateTimeDelimiter: /[T ]/, 23917 timeZoneDelimiter: /[Z ]/i,
vendor: 1,056 bytes, lines 23918-23945
23918 timezone: /([Z+-].*)$/ 23919 }; 23920 var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/; 23921 var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/; 23922 var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/; 23923 function splitDateString(dateString) { 23924 var dateStrings = {}; 23925 var array = dateString.split(patterns.dateTimeDelimiter); 23926 var timeString; 23927 23928 // The regex match should only return at maximum two array elements. 23929 // [date], [time], or [date, time]. 23930 if (array.length > 2) { 23931 return dateStrings; 23932 } 23933 if (/:/.test(array[0])) { 23934 timeString = array[0]; 23935 } else { 23936 dateStrings.date = array[0]; 23937 timeString = array[1]; 23938 if (patterns.timeZoneDelimiter.test(dateStrings.date)) { 23939 dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0]; 23940 timeString = dateString.substr(dateStrings.date.length, dateString.length); 23941 } 23942 } 23943 if (timeString) { 23944 var token = patterns.timezone.exec(timeString); 23945 if (token) {
vendor: 8,091 bytes, lines 23946-24200
23946 dateStrings.time = timeString.replace(token[1], ''); 23947 dateStrings.timezone = token[1]; 23948 } else { 23949 dateStrings.time = timeString; 23950 } 23951 } 23952 return dateStrings; 23953 } 23954 function parseYear(dateString, additionalDigits) { 23955 var regex = new RegExp('^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)'); 23956 var captures = dateString.match(regex); 23957 // Invalid ISO-formatted year 23958 if (!captures) return { 23959 year: NaN, 23960 restDateString: '' 23961 }; 23962 var year = captures[1] ? parseInt(captures[1]) : null; 23963 var century = captures[2] ? parseInt(captures[2]) : null; 23964 23965 // either year or century is null, not both 23966 return { 23967 year: century === null ? year : century * 100, 23968 restDateString: dateString.slice((captures[1] || captures[2]).length) 23969 }; 23970 } 23971 function parseDate(dateString, year) { 23972 // Invalid ISO-formatted year 23973 if (year === null) return new Date(NaN); 23974 var captures = dateString.match(dateRegex); 23975 // Invalid ISO-formatted string 23976 if (!captures) return new Date(NaN); 23977 var isWeekDate = !!captures[4]; 23978 var dayOfYear = parseDateUnit(captures[1]); 23979 var month = parseDateUnit(captures[2]) - 1; 23980 var day = parseDateUnit(captures[3]); 23981 var week = parseDateUnit(captures[4]); 23982 var dayOfWeek = parseDateUnit(captures[5]) - 1; 23983 if (isWeekDate) { 23984 if (!validateWeekDate(year, week, dayOfWeek)) { 23985 return new Date(NaN); 23986 } 23987 return dayOfISOWeekYear(year, week, dayOfWeek); 23988 } else { 23989 var date = new Date(0); 23990 if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) { 23991 return new Date(NaN); 23992 } 23993 date.setUTCFullYear(year, month, Math.max(dayOfYear, day)); 23994 return date; 23995 } 23996 } 23997 function parseDateUnit(value) { 23998 return value ? parseInt(value) : 1; 23999 } 24000 function parseTime(timeString) { 24001 var captures = timeString.match(timeRegex); 24002 if (!captures) return NaN; // Invalid ISO-formatted time 24003 24004 var hours = parseTimeUnit(captures[1]); 24005 var minutes = parseTimeUnit(captures[2]); 24006 var seconds = parseTimeUnit(captures[3]); 24007 if (!validateTime(hours, minutes, seconds)) { 24008 return NaN; 24009 } 24010 return hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * 1000; 24011 } 24012 function parseTimeUnit(value) { 24013 return value && parseFloat(value.replace(',', '.')) || 0; 24014 } 24015 function parseTimezone(timezoneString) { 24016 if (timezoneString === 'Z') return 0; 24017 var captures = timezoneString.match(timezoneRegex); 24018 if (!captures) return 0; 24019 var sign = captures[1] === '+' ? -1 : 1; 24020 var hours = parseInt(captures[2]); 24021 var minutes = captures[3] && parseInt(captures[3]) || 0; 24022 if (!validateTimezone(hours, minutes)) { 24023 return NaN; 24024 } 24025 return sign * (hours * millisecondsInHour + minutes * millisecondsInMinute); 24026 } 24027 function dayOfISOWeekYear(isoWeekYear, week, day) { 24028 var date = new Date(0); 24029 date.setUTCFullYear(isoWeekYear, 0, 4); 24030 var fourthOfJanuaryDay = date.getUTCDay() || 7; 24031 var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay; 24032 date.setUTCDate(date.getUTCDate() + diff); 24033 return date; 24034 } 24035 24036 // Validation functions 24037 24038 // February is null to handle the leap year (using ||) 24039 var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; 24040 function isLeapYearIndex(year) { 24041 return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; 24042 } 24043 function validateDate(year, month, date) { 24044 return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28)); 24045 } 24046 function validateDayOfYearDate(year, dayOfYear) { 24047 return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365); 24048 } 24049 function validateWeekDate(_year, week, day) { 24050 return week >= 1 && week <= 53 && day >= 0 && day <= 6; 24051 } 24052 function validateTime(hours, minutes, seconds) { 24053 if (hours === 24) { 24054 return minutes === 0 && seconds === 0; 24055 } 24056 return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25; 24057 } 24058 function validateTimezone(_hours, minutes) { 24059 return minutes >= 0 && minutes <= 59; 24060 } 24061 24062 var FORMATS = { 24063 datetime: 'MMM d, yyyy, h:mm:ss aaaa', 24064 millisecond: 'h:mm:ss.SSS aaaa', 24065 second: 'h:mm:ss aaaa', 24066 minute: 'h:mm aaaa', 24067 hour: 'ha', 24068 day: 'MMM d', 24069 week: 'PP', 24070 month: 'MMM yyyy', 24071 quarter: 'qqq - yyyy', 24072 year: 'yyyy' 24073 }; 24074 adapters._date.override({ 24075 _id: 'date-fns', 24076 // DEBUG 24077 24078 formats: function formats() { 24079 return FORMATS; 24080 }, 24081 parse: function parse$1(value, fmt) { 24082 if (value === null || typeof value === 'undefined') { 24083 return null; 24084 } 24085 var type = _typeof$1(value); 24086 if (type === 'number' || value instanceof Date) { 24087 value = toDate(value); 24088 } else if (type === 'string') { 24089 if (typeof fmt === 'string') { 24090 value = parse(value, fmt, new Date(), this.options); 24091 } else { 24092 value = parseISO(value, this.options); 24093 } 24094 } 24095 return isValid(value) ? value.getTime() : null; 24096 }, 24097 format: function format$1(time, fmt) { 24098 return format(time, fmt, this.options); 24099 }, 24100 add: function add(time, amount, unit) { 24101 switch (unit) { 24102 case 'millisecond': 24103 return addMilliseconds(time, amount); 24104 case 'second': 24105 return addSeconds(time, amount); 24106 case 'minute': 24107 return addMinutes(time, amount); 24108 case 'hour': 24109 return addHours(time, amount); 24110 case 'day': 24111 return addDays(time, amount); 24112 case 'week': 24113 return addWeeks(time, amount); 24114 case 'month': 24115 return addMonths(time, amount); 24116 case 'quarter': 24117 return addQuarters(time, amount); 24118 case 'year': 24119 return addYears(time, amount); 24120 default: 24121 return time; 24122 } 24123 }, 24124 diff: function diff(max, min, unit) { 24125 switch (unit) { 24126 case 'millisecond': 24127 return differenceInMilliseconds(max, min); 24128 case 'second': 24129 return differenceInSeconds(max, min); 24130 case 'minute': 24131 return differenceInMinutes(max, min); 24132 case 'hour': 24133 return differenceInHours(max, min); 24134 case 'day': 24135 return differenceInDays(max, min); 24136 case 'week': 24137 return differenceInWeeks(max, min); 24138 case 'month': 24139 return differenceInMonths(max, min); 24140 case 'quarter': 24141 return differenceInQuarters(max, min); 24142 case 'year': 24143 return differenceInYears(max, min); 24144 default: 24145 return 0; 24146 } 24147 }, 24148 startOf: function startOf(time, unit, weekday) { 24149 switch (unit) { 24150 case 'second': 24151 return startOfSecond(time); 24152 case 'minute': 24153 return startOfMinute(time); 24154 case 'hour': 24155 return startOfHour(time); 24156 case 'day': 24157 return startOfDay(time); 24158 case 'week': 24159 return startOfWeek(time); 24160 case 'isoWeek': 24161 return startOfWeek(time, { 24162 weekStartsOn: +weekday 24163 }); 24164 case 'month': 24165 return startOfMonth(time); 24166 case 'quarter': 24167 return startOfQuarter(time); 24168 case 'year': 24169 return startOfYear(time); 24170 default: 24171 return time; 24172 } 24173 }, 24174 endOf: function endOf(time, unit) { 24175 switch (unit) { 24176 case 'second': 24177 return endOfSecond(time); 24178 case 'minute': 24179 return endOfMinute(time); 24180 case 'hour': 24181 return endOfHour(time); 24182 case 'day': 24183 return endOfDay(time); 24184 case 'week': 24185 return endOfWeek(time); 24186 case 'month': 24187 return endOfMonth(time); 24188 case 'quarter': 24189 return endOfQuarter(time); 24190 case 'year': 24191 return endOfYear(time); 24192 default: 24193 return time; 24194 } 24195 } 24196 }); 24197 24198 // for plugins 24199 // match src/index.umd.ts in Chart.js 24200 // except for platforms (not exported)
24201 Chart.helpers = _objectSpread2({}, helpers); 24202 Chart._adapters = adapters; 24203 Chart.Animation = Animation; 24204 Chart.Animations = Animations; 24205 Chart.animator = animator; 24206 Chart.controllers = registry.controllers.items; 24207 Chart.DatasetController = DatasetController; 24208 Chart.Element = Element; 24209 Chart.elements = elements; 24210 Chart.Interaction = Interaction; 24211 Chart.layouts = layouts; 24212 Chart.Scale = Scale; 24213 Chart.Ticks = Ticks; 24214 Object.assign(Chart, controllers, scales, elements, plugins); 24215 Chart.Chart = Chart; 24216 24217 return Chart; 24218 24219}));
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.