PageSourceSearch

https://vniispk.ru/ui/v3/chart.js

js vniispk.ru collected 2026-10-02 17:03:34 UTC 816,233 bytes, 27,118 lines download raw bytes

vendor: 8,299 bytes, lines 1-288
1/*!
2 * Chart.js v3.4.1
3 * https://www.chartjs.org
4 * (c) 2021 Chart.js Contributors
5 * Released under the MIT License
6 *
7 * chartjs-adapter-date-fns v2.0.0
8 * https://www.chartjs.org
9 * (c) 2021 chartjs-adapter-date-fns Contributors
10 * Released under the MIT license
11 *
12 * date-fns v2.21.1
13 * https://date-fns.org
14 * (c) 2020 Sasha Koss and Lesha Koss
15 * Released under the MIT License
16 */
17
18(function (global, factory) {
19  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
20  typeof define === 'function' && define.amd ? define(factory) :
21  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Chart = factory());
22}(this, (function () { 'use strict';
23
24  function _typeof(obj) {
25    "@babel/helpers - typeof";
26
27    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
28      _typeof = function (obj) {
29        return typeof obj;
30      };
31    } else {
32      _typeof = function (obj) {
33        return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
34      };
35    }
36
37    return _typeof(obj);
38  }
39
40  function _classCallCheck(instance, Constructor) {
41    if (!(instance instanceof Constructor)) {
42      throw new TypeError("Cannot call a class as a function");
43    }
44  }
45
46  function _defineProperties(target, props) {
47    for (var i = 0; i < props.length; i++) {
48      var descriptor = props[i];
49      descriptor.enumerable = descriptor.enumerable || false;
50      descriptor.configurable = true;
51      if ("value" in descriptor) descriptor.writable = true;
52      Object.defineProperty(target, descriptor.key, descriptor);
53    }
54  }
55
56  function _createClass(Constructor, protoProps, staticProps) {
57    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
58    if (staticProps) _defineProperties(Constructor, staticProps);
59    return Constructor;
60  }
61
62  function _defineProperty(obj, key, value) {
63    if (key in obj) {
64      Object.defineProperty(obj, key, {
65        value: value,
66        enumerable: true,
67        configurable: true,
68        writable: true
69      });
70    } else {
71      obj[key] = value;
72    }
73
74    return obj;
75  }
76
77  function ownKeys(object, enumerableOnly) {
78    var keys = Object.keys(object);
79
80    if (Object.getOwnPropertySymbols) {
81      var symbols = Object.getOwnPropertySymbols(object);
82      if (enumerableOnly) symbols = symbols.filter(function (sym) {
83        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
84      });
85      keys.push.apply(keys, symbols);
86    }
87
88    return keys;
89  }
90
91  function _objectSpread2(target) {
92    for (var i = 1; i < arguments.length; i++) {
93      var source = arguments[i] != null ? arguments[i] : {};
94
95      if (i % 2) {
96        ownKeys(Object(source), true).forEach(function (key) {
97          _defineProperty(target, key, source[key]);
98        });
99      } else if (Object.getOwnPropertyDescriptors) {
100        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
101      } else {
102        ownKeys(Object(source)).forEach(function (key) {
103          Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
104        });
105      }
106    }
107
108    return target;
109  }
110
111  function _inherits(subClass, superClass) {
112    if (typeof superClass !== "function" && superClass !== null) {
113      throw new TypeError("Super expression must either be null or a function");
114    }
115
116    subClass.prototype = Object.create(superClass && superClass.prototype, {
117      constructor: {
118        value: subClass,
119        writable: true,
120        configurable: true
121      }
122    });
123    if (superClass) _setPrototypeOf(subClass, superClass);
124  }
125
126  function _getPrototypeOf(o) {
127    _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
128      return o.__proto__ || Object.getPrototypeOf(o);
129    };
130    return _getPrototypeOf(o);
131  }
132
133  function _setPrototypeOf(o, p) {
134    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
135      o.__proto__ = p;
136      return o;
137    };
138
139    return _setPrototypeOf(o, p);
140  }
141
142  function _isNativeReflectConstruct() {
143    if (typeof Reflect === "undefined" || !Reflect.construct) return false;
144    if (Reflect.construct.sham) return false;
145    if (typeof Proxy === "function") return true;
146
147    try {
148      Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
149      return true;
150    } catch (e) {
151      return false;
152    }
153  }
154
155  function _assertThisInitialized(self) {
156    if (self === void 0) {
157      throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
158    }
159
160    return self;
161  }
162
163  function _possibleConstructorReturn(self, call) {
164    if (call && (typeof call === "object" || typeof call === "function")) {
165      return call;
166    }
167
168    return _assertThisInitialized(self);
169  }
170
171  function _createSuper(Derived) {
172    var hasNativeReflectConstruct = _isNativeReflectConstruct();
173
174    return function _createSuperInternal() {
175      var Super = _getPrototypeOf(Derived),
176          result;
177
178      if (hasNativeReflectConstruct) {
179        var NewTarget = _getPrototypeOf(this).constructor;
180
181        result = Reflect.construct(Super, arguments, NewTarget);
182      } else {
183        result = Super.apply(this, arguments);
184      }
185
186      return _possibleConstructorReturn(this, result);
187    };
188  }
189
190  function _superPropBase(object, property) {
191    while (!Object.prototype.hasOwnProperty.call(object, property)) {
192      object = _getPrototypeOf(object);
193      if (object === null) break;
194    }
195
196    return object;
197  }
198
199  function _get(target, property, receiver) {
200    if (typeof Reflect !== "undefined" && Reflect.get) {
201      _get = Reflect.get;
202    } else {
203      _get = function _get(target, property, receiver) {
204        var base = _superPropBase(target, property);
205
206        if (!base) return;
207        var desc = Object.getOwnPropertyDescriptor(base, property);
208
209        if (desc.get) {
210          return desc.get.call(receiver);
211        }
212
213        return desc.value;
214      };
215    }
216
217    return _get(target, property, receiver || target);
218  }
219
220  function _slicedToArray(arr, i) {
221    return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
222  }
223
224  function _toConsumableArray(arr) {
225    return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
226  }
227
228  function _arrayWithoutHoles(arr) {
229    if (Array.isArray(arr)) return _arrayLikeToArray(arr);
230  }
231
232  function _arrayWithHoles(arr) {
233    if (Array.isArray(arr)) return arr;
234  }
235
236  function _iterableToArray(iter) {
237    if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
238  }
239
240  function _iterableToArrayLimit(arr, i) {
241    if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
242    var _arr = [];
243    var _n = true;
244    var _d = false;
245    var _e = undefined;
246
247    try {
248      for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
249        _arr.push(_s.value);
250
251        if (i && _arr.length === i) break;
252      }
253    } catch (err) {
254      _d = true;
255      _e = err;
256    } finally {
257      try {
258        if (!_n && _i["return"] != null) _i["return"]();
259      } finally {
260        if (_d) throw _e;
261      }
262    }
263
264    return _arr;
265  }
266
267  function _unsupportedIterableToArray(o, minLen) {
268    if (!o) return;
269    if (typeof o === "string") return _arrayLikeToArray(o, minLen);
270    var n = Object.prototype.toString.call(o).slice(8, -1);
271    if (n === "Object" && o.constructor) n = o.constructor.name;
272    if (n === "Map" || n === "Set") return Array.from(o);
273    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
274  }
275
276  function _arrayLikeToArray(arr, len) {
277    if (len == null || len > arr.length) len = arr.length;
278
279    for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
280
281    return arr2;
282  }
283
284  function _nonIterableSpread() {
285    throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
286  }
287
288  function _nonIterableRest() {
289    throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
290  }
291
292  function _createForOfIteratorHelper(o, allowArrayLike) {
293    var it;
294
295    if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
296      if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
297        if (it) o = it;
298        var i = 0;
299
300        var F = function () {};
301
302        return {
303          s: F,
304          n: function () {
305            if (i >= o.length) return {
306              done: true
307            };
308            return {
309              done: false,
310              value: o[i++]
311            };
312          },
313          e: function (e) {
314            throw e;
315          },
316          f: F
317        };
318      }
319
320      throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
321    }
322
323    var normalCompletion = true,
324        didErr = false,
325        err;
326    return {
327      s: function () {
328        it = o[Symbol.iterator]();
329      },
330      n: function () {
331        var step = it.next();
332        normalCompletion = step.done;
333        return step;
334      },
335      e: function (e) {
336        didErr = true;
337        err = e;
338      },
339      f: function () {
340        try {
341          if (!normalCompletion && it.return != null) it.return();
342        } finally {
343          if (didErr) throw err;
344        }
345      }
346    };
347  }
348
349  var requestAnimFrame = function () {
350    if (typeof window === 'undefined') {
351      return function (callback) {
352        return callback();
353      };
354    }
355
356    return window.requestAnimationFrame;
357  }();
358
359  function throttled(fn, thisArg, updateFn) {
360    var updateArgs = updateFn || function (args) {
361      return Array.prototype.slice.call(args);
362    };
363
364    var ticking = false;
365    var args = [];
366    return function () {
367      for (var _len = arguments.length, rest = new Array(_len), _key = 0; _key < _len; _key++) {
368        rest[_key] = arguments[_key];
369      }
370
371      args = updateArgs(rest);
372
373      if (!ticking) {
374        ticking = true;
375        requestAnimFrame.call(window, function () {
376          ticking = false;
377          fn.apply(thisArg, args);
378        });
379      }
380    };
381  }
382
383  function debounce(fn, delay) {
384    var timeout;
385    return function () {
386      if (delay) {
387        clearTimeout(timeout);
388        timeout = setTimeout(fn, delay);
389      } else {
390        fn();
391      }
392
393      return delay;
394    };
395  }
396
397  var _toLeftRightCenter = function _toLeftRightCenter(align) {
398    return align === 'start' ? 'left' : align === 'end' ? 'right' : 'center';
399  };
400
401  var _alignStartEnd = function _alignStartEnd(align, start, end) {
402    return align === 'start' ? start : align === 'end' ? end : (start + end) / 2;
403  };
404
405  var _textX = function _textX(align, left, right, rtl) {
406    var check = rtl ? 'left' : 'right';
407    return align === check ? right : align === 'center' ? (left + right) / 2 : left;
408  };
409
410  function noop() {}
411
412  var uid = function () {
413    var id = 0;
414    return function () {
415      return id++;
416    };
417  }();
418
419  function isNullOrUndef(value) {
420    return value === null || typeof value === 'undefined';
421  }
422
423  function isArray(value) {
424    if (Array.isArray && Array.isArray(value)) {
425      return true;
426    }
427
428    var type = Object.prototype.toString.call(value);
429
430    if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
431      return true;
432    }
433
434    return false;
435  }
436
437  function isObject(value) {
438    return value !== null && Object.prototype.toString.call(value) === '[object Object]';
439  }
440
441  var isNumberFinite = function isNumberFinite(value) {
442    return (typeof value === 'number' || value instanceof Number) && isFinite(+value);
443  };
444
445  function finiteOrDefault(value, defaultValue) {
446    return isNumberFinite(value) ? value : defaultValue;
447  }
448
449  function valueOrDefault(value, defaultValue) {
450    return typeof value === 'undefined' ? defaultValue : value;
451  }
452
453  var toPercentage = function toPercentage(value, dimension) {
454    return typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 : value / dimension;
455  };
456
457  var toDimension = function toDimension(value, dimension) {
458    return typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 * dimension : +value;
459  };
460
461  function callback(fn, args, thisArg) {
462    if (fn && typeof fn.call === 'function') {
463      return fn.apply(thisArg, args);
464    }
465  }
466
467  function each(loopable, fn, thisArg, reverse) {
468    var i, len, keys;
469
470    if (isArray(loopable)) {
471      len = loopable.length;
472
473      if (reverse) {
474        for (i = len - 1; i >= 0; i--) {
475          fn.call(thisArg, loopable[i], i);
476        }
477      } else {
478        for (i = 0; i < len; i++) {
479          fn.call(thisArg, loopable[i], i);
480        }
481      }
482    } else if (isObject(loopable)) {
483      keys = Object.keys(loopable);
484      len = keys.length;
485
486      for (i = 0; i < len; i++) {
487        fn.call(thisArg, loopable[keys[i]], keys[i]);
488      }
489    }
490  }
491
492  function _elementsEqual(a0, a1) {
493    var i, ilen, v0, v1;
494
495    if (!a0 || !a1 || a0.length !== a1.length) {
496      return false;
497    }
498
499    for (i = 0, ilen = a0.length; i < ilen; ++i) {
500      v0 = a0[i];
501      v1 = a1[i];
502
503      if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) {
504        return false;
505      }
506    }
507
508    return true;
509  }
510
511  function clone$1(source) {
512    if (isArray(source)) {
513      return source.map(clone$1);
514    }
515
516    if (isObject(source)) {
517      var target = Object.create(null);
518      var keys = Object.keys(source);
519      var klen = keys.length;
520      var k = 0;
521
522      for (; k < klen; ++k) {
523        target[keys[k]] = clone$1(source[keys[k]]);
524      }
525
526      return target;
527    }
528
529    return source;
530  }
531
532  function isValidKey(key) {
533    return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;
534  }
535
536  function _merger(key, target, source, options) {
537    if (!isValidKey(key)) {
538      return;
539    }
540
541    var tval = target[key];
542    var sval = source[key];
543
544    if (isObject(tval) && isObject(sval)) {
545      merge(tval, sval, options);
546    } else {
547      target[key] = clone$1(sval);
548    }
549  }
550
551  function merge(target, source, options) {
552    var sources = isArray(source) ? source : [source];
553    var ilen = sources.length;
554
555    if (!isObject(target)) {
556      return target;
557    }
558
559    options = options || {};
560    var merger = options.merger || _merger;
561
562    for (var i = 0; i < ilen; ++i) {
563      source = sources[i];
564
565      if (!isObject(source)) {
566        continue;
567      }
568
569      var keys = Object.keys(source);
570
571      for (var k = 0, klen = keys.length; k < klen; ++k) {
572        merger(keys[k], target, source, options);
573      }
574    }
575
576    return target;
577  }
578
579  function mergeIf(target, source) {
580    return merge(target, source, {
581      merger: _mergerIf
582    });
583  }
584
585  function _mergerIf(key, target, source) {
586    if (!isValidKey(key)) {
587      return;
588    }
589
590    var tval = target[key];
591    var sval = source[key];
592
593    if (isObject(tval) && isObject(sval)) {
594      mergeIf(tval, sval);
595    } else if (!Object.prototype.hasOwnProperty.call(target, key)) {
596      target[key] = clone$1(sval);
597    }
598  }
599
600  var emptyString = '';
601  var dot = '.';
602
603  function indexOfDotOrLength(key, start) {
604    var idx = key.indexOf(dot, start);
605    return idx === -1 ? key.length : idx;
606  }
607
608  function resolveObjectKey(obj, key) {
609    if (key === emptyString) {
610      return obj;
611    }
612
613    var pos = 0;
614    var idx = indexOfDotOrLength(key, pos);
615
616    while (obj && idx > pos) {
617      obj = obj[key.substr(pos, idx - pos)];
618      pos = idx + 1;
619      idx = indexOfDotOrLength(key, pos);
620    }
621
622    return obj;
623  }
624
625  function _capitalize(str) {
626    return str.charAt(0).toUpperCase() + str.slice(1);
627  }
628
629  var defined = function defined(value) {
630    return typeof value !== 'undefined';
631  };
632
633  var isFunction = function isFunction(value) {
634    return typeof value === 'function';
635  };
636
637  var setsEqual = function setsEqual(a, b) {
638    if (a.size !== b.size) {
639      return false;
640    }
641
642    var _iterator = _createForOfIteratorHelper(a),
643        _step;
644
645    try {
646      for (_iterator.s(); !(_step = _iterator.n()).done;) {
647        var item = _step.value;
648
649        if (!b.has(item)) {
650          return false;
651        }
652      }
653    } catch (err) {
654      _iterator.e(err);
655    } finally {
656      _iterator.f();
657    }
658
659    return true;
660  };
661
662  var PI = Math.PI;
663  var TAU = 2 * PI;
664  var PITAU = TAU + PI;
665  var INFINITY = Number.POSITIVE_INFINITY;
666  var RAD_PER_DEG = PI / 180;
667  var HALF_PI = PI / 2;
668  var QUARTER_PI = PI / 4;
669  var TWO_THIRDS_PI = PI * 2 / 3;
670  var log10 = Math.log10;
671  var sign = Math.sign;
672
673  function niceNum(range) {
674    var roundedRange = Math.round(range);
675    range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range;
676    var niceRange = Math.pow(10, Math.floor(log10(range)));
677    var fraction = range / niceRange;
678    var niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
679    return niceFraction * niceRange;
680  }
681
682  function _factorize(value) {
683    var result = [];
684    var sqrt = Math.sqrt(value);
685    var i;
686
687    for (i = 1; i < sqrt; i++) {
688      if (value % i === 0) {
689        result.push(i);
690        result.push(value / i);
691      }
692    }
693
694    if (sqrt === (sqrt | 0)) {
695      result.push(sqrt);
696    }
697
698    result.sort(function (a, b) {
699      return a - b;
700    }).pop();
701    return result;
702  }
703
704  function isNumber(n) {
705    return !isNaN(parseFloat(n)) && isFinite(n);
706  }
707
708  function almostEquals(x, y, epsilon) {
709    return Math.abs(x - y) < epsilon;
710  }
711
712  function almostWhole(x, epsilon) {
713    var rounded = Math.round(x);
714    return rounded - epsilon <= x && rounded + epsilon >= x;
715  }
716
717  function _setMinAndMaxByKey(array, target, property) {
718    var i, ilen, value;
719
720    for (i = 0, ilen = array.length; i < ilen; i++) {
721      value = array[i][property];
722
723      if (!isNaN(value)) {
724        target.min = Math.min(target.min, value);
725        target.max = Math.max(target.max, value);
726      }
727    }
728  }
729
730  function toRadians(degrees) {
731    return degrees * (PI / 180);
732  }
733
734  function toDegrees(radians) {
735    return radians * (180 / PI);
736  }
737
738  function _decimalPlaces(x) {
739    if (!isNumberFinite(x)) {
740      return;
741    }
742
743    var e = 1;
744    var p = 0;
745
746    while (Math.round(x * e) / e !== x) {
747      e *= 10;
748      p++;
749    }
750
751    return p;
752  }
753
754  function getAngleFromPoint(centrePoint, anglePoint) {
755    var distanceFromXCenter = anglePoint.x - centrePoint.x;
756    var distanceFromYCenter = anglePoint.y - centrePoint.y;
757    var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
758    var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
759
760    if (angle < -0.5 * PI) {
761      angle += TAU;
762    }
763
764    return {
765      angle: angle,
766      distance: radialDistanceFromCenter
767    };
768  }
769
770  function distanceBetweenPoints(pt1, pt2) {
771    return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
772  }
773
774  function _angleDiff(a, b) {
775    return (a - b + PITAU) % TAU - PI;
776  }
777
778  function _normalizeAngle(a) {
779    return (a % TAU + TAU) % TAU;
780  }
781
782  function _angleBetween(angle, start, end, sameAngleIsFullCircle) {
783    var a = _normalizeAngle(angle);
784
785    var s = _normalizeAngle(start);
786
787    var e = _normalizeAngle(end);
788
789    var angleToStart = _normalizeAngle(s - a);
790
791    var angleToEnd = _normalizeAngle(e - a);
792
793    var startToAngle = _normalizeAngle(a - s);
794
795    var endToAngle = _normalizeAngle(a - e);
796
797    return a === s || a === e || sameAngleIsFullCircle && s === e || angleToStart > angleToEnd && startToAngle < endToAngle;
798  }
799
800  function _limitValue(value, min, max) {
801    return Math.max(min, Math.min(max, value));
802  }
803
804  function _int16Range(value) {
805    return _limitValue(value, -32768, 32767);
806  }
807
808  var atEdge = function atEdge(t) {
809    return t === 0 || t === 1;
810  };
811
812  var elasticIn = function elasticIn(t, s, p) {
813    return -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p));
814  };
815
816  var elasticOut = function elasticOut(t, s, p) {
817    return Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1;
818  };
819
820  var effects = {
821    linear: function linear(t) {
822      return t;
823    },
824    easeInQuad: function easeInQuad(t) {
825      return t * t;
826    },
827    easeOutQuad: function easeOutQuad(t) {
828      return -t * (t - 2);
829    },
830    easeInOutQuad: function easeInOutQuad(t) {
831      return (t /= 0.5) < 1 ? 0.5 * t * t : -0.5 * (--t * (t - 2) - 1);
832    },
833    easeInCubic: function easeInCubic(t) {
834      return t * t * t;
835    },
836    easeOutCubic: function easeOutCubic(t) {
837      return (t -= 1) * t * t + 1;
838    },
839    easeInOutCubic: function easeInOutCubic(t) {
840      return (t /= 0.5) < 1 ? 0.5 * t * t * t : 0.5 * ((t -= 2) * t * t + 2);
841    },
842    easeInQuart: function easeInQuart(t) {
843      return t * t * t * t;
844    },
845    easeOutQuart: function easeOutQuart(t) {
846      return -((t -= 1) * t * t * t - 1);
847    },
848    easeInOutQuart: function easeInOutQuart(t) {
849      return (t /= 0.5) < 1 ? 0.5 * t * t * t * t : -0.5 * ((t -= 2) * t * t * t - 2);
850    },
851    easeInQuint: function easeInQuint(t) {
852      return t * t * t * t * t;
853    },
854    easeOutQuint: function easeOutQuint(t) {
855      return (t -= 1) * t * t * t * t + 1;
856    },
857    easeInOutQuint: function easeInOutQuint(t) {
858      return (t /= 0.5) < 1 ? 0.5 * t * t * t * t * t : 0.5 * ((t -= 2) * t * t * t * t + 2);
859    },
860    easeInSine: function easeInSine(t) {
861      return -Math.cos(t * HALF_PI) + 1;
862    },
863    easeOutSine: function easeOutSine(t) {
864      return Math.sin(t * HALF_PI);
865    },
866    easeInOutSine: function easeInOutSine(t) {
867      return -0.5 * (Math.cos(PI * t) - 1);
868    },
869    easeInExpo: function easeInExpo(t) {
870      return t === 0 ? 0 : Math.pow(2, 10 * (t - 1));
871    },
872    easeOutExpo: function easeOutExpo(t) {
873      return t === 1 ? 1 : -Math.pow(2, -10 * t) + 1;
874    },
875    easeInOutExpo: function easeInOutExpo(t) {
876      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);
877    },
878    easeInCirc: function easeInCirc(t) {
879      return t >= 1 ? t : -(Math.sqrt(1 - t * t) - 1);
880    },
881    easeOutCirc: function easeOutCirc(t) {
882      return Math.sqrt(1 - (t -= 1) * t);
883    },
884    easeInOutCirc: function easeInOutCirc(t) {
885      return (t /= 0.5) < 1 ? -0.5 * (Math.sqrt(1 - t * t) - 1) : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
886    },
887    easeInElastic: function easeInElastic(t) {
888      return atEdge(t) ? t : elasticIn(t, 0.075, 0.3);
889    },
890    easeOutElastic: function easeOutElastic(t) {
891      return atEdge(t) ? t : elasticOut(t, 0.075, 0.3);
892    },
893    easeInOutElastic: function easeInOutElastic(t) {
894      var s = 0.1125;
895      var p = 0.45;
896      return atEdge(t) ? t : t < 0.5 ? 0.5 * elasticIn(t * 2, s, p) : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p);
897    },
898    easeInBack: function easeInBack(t) {
899      var s = 1.70158;
900      return t * t * ((s + 1) * t - s);
901    },
902    easeOutBack: function easeOutBack(t) {
903      var s = 1.70158;
904      return (t -= 1) * t * ((s + 1) * t + s) + 1;
905    },
906    easeInOutBack: function easeInOutBack(t) {
907      var s = 1.70158;
908
909      if ((t /= 0.5) < 1) {
910        return 0.5 * (t * t * (((s *= 1.525) + 1) * t - s));
911      }
912
913      return 0.5 * ((t -= 2) * t * (((s *= 1.525) + 1) * t + s) + 2);
914    },
915    easeInBounce: function easeInBounce(t) {
916      return 1 - effects.easeOutBounce(1 - t);
917    },
918    easeOutBounce: function easeOutBounce(t) {
919      var m = 7.5625;
920      var d = 2.75;
921
922      if (t < 1 / d) {
923        return m * t * t;
924      }
925
926      if (t < 2 / d) {
927        return m * (t -= 1.5 / d) * t + 0.75;
928      }
929
930      if (t < 2.5 / d) {
931        return m * (t -= 2.25 / d) * t + 0.9375;
932      }
933
934      return m * (t -= 2.625 / d) * t + 0.984375;
935    },
936    easeInOutBounce: function easeInOutBounce(t) {
937      return t < 0.5 ? effects.easeInBounce(t * 2) * 0.5 : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
938    }
939  };
940  /*!
941   * @kurkle/color v0.1.9
942   * https://github.com/kurkle/color#readme
943   * (c) 2020 Jukka Kurkela
944   * Released under the MIT License
945   */
946
947  var map$1 = {
948    0: 0,
949    1: 1,
950    2: 2,
951    3: 3,
952    4: 4,
953    5: 5,
954    6: 6,
955    7: 7,
956    8: 8,
957    9: 9,
958    A: 10,
959    B: 11,
960    C: 12,
961    D: 13,
962    E: 14,
963    F: 15,
964    a: 10,
965    b: 11,
966    c: 12,
967    d: 13,
968    e: 14,
969    f: 15
970  };
971  var hex = '0123456789ABCDEF';
972
973  var h1 = function h1(b) {
974    return hex[b & 0xF];
975  };
976
977  var h2 = function h2(b) {
978    return hex[(b & 0xF0) >> 4] + hex[b & 0xF];
979  };
980
981  var eq = function eq(b) {
982    return (b & 0xF0) >> 4 === (b & 0xF);
983  };
984
985  function isShort(v) {
986    return eq(v.r) && eq(v.g) && eq(v.b) && eq(v.a);
987  }
988
989  function hexParse(str) {
990    var len = str.length;
991    var ret;
992
993    if (str[0] === '#') {
994      if (len === 4 || len === 5) {
995        ret = {
996          r: 255 & map$1[str[1]] * 17,
997          g: 255 & map$1[str[2]] * 17,
998          b: 255 & map$1[str[3]] * 17,
999          a: len === 5 ? map$1[str[4]] * 17 : 255
1000        };
1001      } else if (len === 7 || len === 9) {
1002        ret = {
1003          r: map$1[str[1]] << 4 | map$1[str[2]],
1004          g: map$1[str[3]] << 4 | map$1[str[4]],
1005          b: map$1[str[5]] << 4 | map$1[str[6]],
1006          a: len === 9 ? map$1[str[7]] << 4 | map$1[str[8]] : 255
1007        };
1008      }
1009    }
1010
1011    return ret;
1012  }
1013
1014  function _hexString(v) {
1015    var f = isShort(v) ? h1 : h2;
1016    return v ? '#' + f(v.r) + f(v.g) + f(v.b) + (v.a < 255 ? f(v.a) : '') : v;
1017  }
1018
1019  function round(v) {
1020    return v + 0.5 | 0;
1021  }
1022
1023  var lim = function lim(v, l, h) {
1024    return Math.max(Math.min(v, h), l);
1025  };
1026
1027  function p2b(v) {
1028    return lim(round(v * 2.55), 0, 255);
1029  }
1030
1031  function n2b(v) {
1032    return lim(round(v * 255), 0, 255);
1033  }
1034
1035  function b2n(v) {
1036    return lim(round(v / 2.55) / 100, 0, 1);
1037  }
1038
1039  function n2p(v) {
1040    return lim(round(v * 100), 0, 100);
1041  }
1042
1043  var RGB_RE = /^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;
1044
1045  function rgbParse(str) {
1046    var m = RGB_RE.exec(str);
1047    var a = 255;
1048    var r, g, b;
1049
1050    if (!m) {
1051      return;
1052    }
1053
1054    if (m[7] !== r) {
1055      var v = +m[7];
1056      a = 255 & (m[8] ? p2b(v) : v * 255);
1057    }
1058
1059    r = +m[1];
1060    g = +m[3];
1061    b = +m[5];
1062    r = 255 & (m[2] ? p2b(r) : r);
1063    g = 255 & (m[4] ? p2b(g) : g);
1064    b = 255 & (m[6] ? p2b(b) : b);
1065    return {
1066      r: r,
1067      g: g,
1068      b: b,
1069      a: a
1070    };
1071  }
1072
1073  function _rgbString(v) {
1074    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, ")"));
1075  }
1076
1077  var HUE_RE = /^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;
1078
1079  function hsl2rgbn(h, s, l) {
1080    var a = s * Math.min(l, 1 - l);
1081
1082    var f = function f(n) {
1083      var k = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (n + h / 30) % 12;
1084      return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
1085    };
1086
1087    return [f(0), f(8), f(4)];
1088  }
1089
1090  function hsv2rgbn(h, s, v) {
1091    var f = function f(n) {
1092      var k = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (n + h / 60) % 6;
1093      return v - v * s * Math.max(Math.min(k, 4 - k, 1), 0);
1094    };
1095
1096    return [f(5), f(3), f(1)];
1097  }
1098
1099  function hwb2rgbn(h, w, b) {
1100    var rgb = hsl2rgbn(h, 1, 0.5);
1101    var i;
1102
1103    if (w + b > 1) {
1104      i = 1 / (w + b);
1105      w *= i;
1106      b *= i;
1107    }
1108
1109    for (i = 0; i < 3; i++) {
1110      rgb[i] *= 1 - w - b;
1111      rgb[i] += w;
1112    }
1113
1114    return rgb;
1115  }
1116
1117  function rgb2hsl(v) {
1118    var range = 255;
1119    var r = v.r / range;
1120    var g = v.g / range;
1121    var b = v.b / range;
1122    var max = Math.max(r, g, b);
1123    var min = Math.min(r, g, b);
1124    var l = (max + min) / 2;
1125    var h, s, d;
1126
1127    if (max !== min) {
1128      d = max - min;
1129      s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
1130      h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
1131      h = h * 60 + 0.5;
1132    }
1133
1134    return [h | 0, s || 0, l];
1135  }
1136
1137  function calln(f, a, b, c) {
1138    return (Array.isArray(a) ? f(a[0], a[1], a[2]) : f(a, b, c)).map(n2b);
1139  }
1140
1141  function hsl2rgb(h, s, l) {
1142    return calln(hsl2rgbn, h, s, l);
1143  }
1144
1145  function hwb2rgb(h, w, b) {
1146    return calln(hwb2rgbn, h, w, b);
1147  }
1148
1149  function hsv2rgb(h, s, v) {
1150    return calln(hsv2rgbn, h, s, v);
1151  }
1152
1153  function hue(h) {
1154    return (h % 360 + 360) % 360;
1155  }
1156
1157  function hueParse(str) {
1158    var m = HUE_RE.exec(str);
1159    var a = 255;
1160    var v;
1161
1162    if (!m) {
1163      return;
1164    }
1165
1166    if (m[5] !== v) {
1167      a = m[6] ? p2b(+m[5]) : n2b(+m[5]);
1168    }
1169
1170    var h = hue(+m[2]);
1171    var p1 = +m[3] / 100;
1172    var p2 = +m[4] / 100;
1173
1174    if (m[1] === 'hwb') {
1175      v = hwb2rgb(h, p1, p2);
1176    } else if (m[1] === 'hsv') {
1177      v = hsv2rgb(h, p1, p2);
1178    } else {
1179      v = hsl2rgb(h, p1, p2);
1180    }
1181
1182    return {
1183      r: v[0],
1184      g: v[1],
1185      b: v[2],
1186      a: a
1187    };
1188  }
1189
1190  function _rotate(v, deg) {
1191    var h = rgb2hsl(v);
1192    h[0] = hue(h[0] + deg);
1193    h = hsl2rgb(h);
1194    v.r = h[0];
1195    v.g = h[1];
1196    v.b = h[2];
1197  }
1198
1199  function _hslString(v) {
1200    if (!v) {
1201      return;
1202    }
1203
1204    var a = rgb2hsl(v);
1205    var h = a[0];
1206    var s = n2p(a[1]);
1207    var l = n2p(a[2]);
1208    return v.a < 255 ? "hsla(".concat(h, ", ").concat(s, "%, ").concat(l, "%, ").concat(b2n(v.a), ")") : "hsl(".concat(h, ", ").concat(s, "%, ").concat(l, "%)");
1209  }
1210
1211  var map$1$1 = {
1212    x: 'dark',
1213    Z: 'light',
1214    Y: 're',
1215    X: 'blu',
1216    W: 'gr',
1217    V: 'medium',
1218    U: 'slate',
1219    A: 'ee',
1220    T: 'ol',
1221    S: 'or',
1222    B: 'ra',
1223    C: 'lateg',
1224    D: 'ights',
1225    R: 'in',
1226    Q: 'turquois',
1227    E: 'hi',
1228    P: 'ro',
1229    O: 'al',
1230    N: 'le',
1231    M: 'de',
1232    L: 'yello',
1233    F: 'en',
1234    K: 'ch',
1235    G: 'arks',
1236    H: 'ea',
1237    I: 'ightg',
1238    J: 'wh'
1239  };
1240  var names = {
1241    OiceXe: 'f0f8ff',
1242    antiquewEte: 'faebd7',
1243    aqua: 'ffff',
1244    aquamarRe: '7fffd4',
1245    azuY: 'f0ffff',
1246    beige: 'f5f5dc',
1247    bisque: 'ffe4c4',
1248    black: '0',
1249    blanKedOmond: 'ffebcd',
1250    Xe: 'ff',
1251    XeviTet: '8a2be2',
1252    bPwn: 'a52a2a',
1253    burlywood: 'deb887',
1254    caMtXe: '5f9ea0',
1255    KartYuse: '7fff00',
1256    KocTate: 'd2691e',
1257    cSO: 'ff7f50',
1258    cSnflowerXe: '6495ed',
1259    cSnsilk: 'fff8dc',
1260    crimson: 'dc143c',
1261    cyan: 'ffff',
1262    xXe: '8b',
1263    xcyan: '8b8b',
1264    xgTMnPd: 'b8860b',
1265    xWay: 'a9a9a9',
1266    xgYF: '6400',
1267    xgYy: 'a9a9a9',
1268    xkhaki: 'bdb76b',
1269    xmagFta: '8b008b',
1270    xTivegYF: '556b2f',
1271    xSange: 'ff8c00',
1272    xScEd: '9932cc',
1273    xYd: '8b0000',
1274    xsOmon: 'e9967a',
1275    xsHgYF: '8fbc8f',
1276    xUXe: '483d8b',
1277    xUWay: '2f4f4f',
1278    xUgYy: '2f4f4f',
1279    xQe: 'ced1',
1280    xviTet: '9400d3',
1281    dAppRk: 'ff1493',
1282    dApskyXe: 'bfff',
1283    dimWay: '696969',
1284    dimgYy: '696969',
1285    dodgerXe: '1e90ff',
1286    fiYbrick: 'b22222',
1287    flSOwEte: 'fffaf0',
1288    foYstWAn: '228b22',
1289    fuKsia: 'ff00ff',
1290    gaRsbSo: 'dcdcdc',
1291    ghostwEte: 'f8f8ff',
1292    gTd: 'ffd700',
1293    gTMnPd: 'daa520',
1294    Way: '808080',
1295    gYF: '8000',
1296    gYFLw: 'adff2f',
1297    gYy: '808080',
1298    honeyMw: 'f0fff0',
1299    hotpRk: 'ff69b4',
1300    RdianYd: 'cd5c5c',
1301    Rdigo: '4b0082',
1302    ivSy: 'fffff0',
1303    khaki: 'f0e68c',
1304    lavFMr: 'e6e6fa',
1305    lavFMrXsh: 'fff0f5',
1306    lawngYF: '7cfc00',
1307    NmoncEffon: 'fffacd',
1308    ZXe: 'add8e6',
1309    ZcSO: 'f08080',
1310    Zcyan: 'e0ffff',
1311    ZgTMnPdLw: 'fafad2',
1312    ZWay: 'd3d3d3',
1313    ZgYF: '90ee90',
1314    ZgYy: 'd3d3d3',
1315    ZpRk: 'ffb6c1',
1316    ZsOmon: 'ffa07a',
1317    ZsHgYF: '20b2aa',
1318    ZskyXe: '87cefa',
1319    ZUWay: '778899',
1320    ZUgYy: '778899',
1321    ZstAlXe: 'b0c4de',
1322    ZLw: 'ffffe0',
1323    lime: 'ff00',
1324    limegYF: '32cd32',
1325    lRF: 'faf0e6',
1326    magFta: 'ff00ff',
1327    maPon: '800000',
1328    VaquamarRe: '66cdaa',
1329    VXe: 'cd',
1330    VScEd: 'ba55d3',
1331    VpurpN: '9370db',
1332    VsHgYF: '3cb371',
1333    VUXe: '7b68ee',
1334    VsprRggYF: 'fa9a',
1335    VQe: '48d1cc',
1336    VviTetYd: 'c71585',
1337    midnightXe: '191970',
1338    mRtcYam: 'f5fffa',
1339    mistyPse: 'ffe4e1',
1340    moccasR: 'ffe4b5',
1341    navajowEte: 'ffdead',
1342    navy: '80',
1343    Tdlace: 'fdf5e6',
1344    Tive: '808000',
1345    TivedBb: '6b8e23',
1346    Sange: 'ffa500',
1347    SangeYd: 'ff4500',
1348    ScEd: 'da70d6',
1349    pOegTMnPd: 'eee8aa',
1350    pOegYF: '98fb98',
1351    pOeQe: 'afeeee',
1352    pOeviTetYd: 'db7093',
1353    papayawEp: 'ffefd5',
1354    pHKpuff: 'ffdab9',
1355    peru: 'cd853f',
1356    pRk: 'ffc0cb',
1357    plum: 'dda0dd',
1358    powMrXe: 'b0e0e6',
1359    purpN: '800080',
1360    YbeccapurpN: '663399',
1361    Yd: 'ff0000',
1362    Psybrown: 'bc8f8f',
1363    PyOXe: '4169e1',
1364    saddNbPwn: '8b4513',
1365    sOmon: 'fa8072',
1366    sandybPwn: 'f4a460',
1367    sHgYF: '2e8b57',
1368    sHshell: 'fff5ee',
1369    siFna: 'a0522d',
1370    silver: 'c0c0c0',
1371    skyXe: '87ceeb',
1372    UXe: '6a5acd',
1373    UWay: '708090',
1374    UgYy: '708090',
1375    snow: 'fffafa',
1376    sprRggYF: 'ff7f',
1377    stAlXe: '4682b4',
1378    tan: 'd2b48c',
1379    teO: '8080',
1380    tEstN: 'd8bfd8',
1381    tomato: 'ff6347',
1382    Qe: '40e0d0',
1383    viTet: 'ee82ee',
1384    JHt: 'f5deb3',
1385    wEte: 'ffffff',
1386    wEtesmoke: 'f5f5f5',
1387    Lw: 'ffff00',
1388    LwgYF: '9acd32'
1389  };
1390
1391  function unpack() {
1392    var unpacked = {};
1393    var keys = Object.keys(names);
1394    var tkeys = Object.keys(map$1$1);
1395    var i, j, k, ok, nk;
1396
1397    for (i = 0; i < keys.length; i++) {
1398      ok = nk = keys[i];
1399
1400      for (j = 0; j < tkeys.length; j++) {
1401        k = tkeys[j];
1402        nk = nk.replace(k, map$1$1[k]);
1403      }
1404
1405      k = parseInt(names[ok], 16);
1406      unpacked[nk] = [k >> 16 & 0xFF, k >> 8 & 0xFF, k & 0xFF];
1407    }
1408
1409    return unpacked;
1410  }
1411
1412  var names$1;
1413
1414  function nameParse(str) {
1415    if (!names$1) {
1416      names$1 = unpack();
1417      names$1.transparent = [0, 0, 0, 0];
1418    }
1419
1420    var a = names$1[str.toLowerCase()];
1421    return a && {
1422      r: a[0],
1423      g: a[1],
1424      b: a[2],
1425      a: a.length === 4 ? a[3] : 255
1426    };
1427  }
1428
1429  function modHSL(v, i, ratio) {
1430    if (v) {
1431      var tmp = rgb2hsl(v);
1432      tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1));
1433      tmp = hsl2rgb(tmp);
1434      v.r = tmp[0];
1435      v.g = tmp[1];
1436      v.b = tmp[2];
1437    }
1438  }
1439
1440  function clone(v, proto) {
1441    return v ? Object.assign(proto || {}, v) : v;
1442  }
1443
1444  function fromObject(input) {
1445    var v = {
1446      r: 0,
1447      g: 0,
1448      b: 0,
1449      a: 255
1450    };
1451
1452    if (Array.isArray(input)) {
1453      if (input.length >= 3) {
1454        v = {
1455          r: input[0],
1456          g: input[1],
1457          b: input[2],
1458          a: 255
1459        };
1460
1461        if (input.length > 3) {
1462          v.a = n2b(input[3]);
1463        }
1464      }
1465    } else {
1466      v = clone(input, {
1467        r: 0,
1468        g: 0,
1469        b: 0,
1470        a: 1
1471      });
1472      v.a = n2b(v.a);
1473    }
1474
1475    return v;
1476  }
1477
1478  function functionParse(str) {
1479    if (str.charAt(0) === 'r') {
1480      return rgbParse(str);
1481    }
1482
1483    return hueParse(str);
1484  }
1485
1486  var Color = /*#__PURE__*/function () {
1487    function Color(input) {
1488      _classCallCheck(this, Color);
1489
1490      if (input instanceof Color) {
1491        return input;
1492      }
1493
1494      var type = _typeof(input);
1495
1496      var v;
1497
1498      if (type === 'object') {
1499        v = fromObject(input);
1500      } else if (type === 'string') {
1501        v = hexParse(input) || nameParse(input) || functionParse(input);
1502      }
1503
1504      this._rgb = v;
1505      this._valid = !!v;
1506    }
1507
1508    _createClass(Color, [{
1509      key: "valid",
1510      get: function get() {
1511        return this._valid;
1512      }
1513    }, {
1514      key: "rgb",
1515      get: function get() {
1516        var v = clone(this._rgb);
1517
1518        if (v) {
1519          v.a = b2n(v.a);
1520        }
1521
1522        return v;
1523      },
1524      set: function set(obj) {
1525        this._rgb = fromObject(obj);
1526      }
1527    }, {
1528      key: "rgbString",
1529      value: function rgbString() {
1530        return this._valid ? _rgbString(this._rgb) : this._rgb;
1531      }
1532    }, {
1533      key: "hexString",
1534      value: function hexString() {
1535        return this._valid ? _hexString(this._rgb) : this._rgb;
1536      }
1537    }, {
1538      key: "hslString",
1539      value: function hslString() {
1540        return this._valid ? _hslString(this._rgb) : this._rgb;
1541      }
1542    }, {
1543      key: "mix",
1544      value: function mix(color, weight) {
1545        var me = this;
1546
1547        if (color) {
1548          var c1 = me.rgb;
1549          var c2 = color.rgb;
1550          var w2;
1551          var p = weight === w2 ? 0.5 : weight;
1552          var w = 2 * p - 1;
1553          var a = c1.a - c2.a;
1554          var w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
1555          w2 = 1 - w1;
1556          c1.r = 0xFF & w1 * c1.r + w2 * c2.r + 0.5;
1557          c1.g = 0xFF & w1 * c1.g + w2 * c2.g + 0.5;
1558          c1.b = 0xFF & w1 * c1.b + w2 * c2.b + 0.5;
1559          c1.a = p * c1.a + (1 - p) * c2.a;
1560          me.rgb = c1;
1561        }
1562
1563        return me;
1564      }
1565    }, {
1566      key: "clone",
1567      value: function clone() {
1568        return new Color(this.rgb);
1569      }
1570    }, {
1571      key: "alpha",
1572      value: function alpha(a) {
1573        this._rgb.a = n2b(a);
1574        return this;
1575      }
1576    }, {
1577      key: "clearer",
1578      value: function clearer(ratio) {
1579        var rgb = this._rgb;
1580        rgb.a *= 1 - ratio;
1581        return this;
1582      }
1583    }, {
1584      key: "greyscale",
1585      value: function greyscale() {
1586        var rgb = this._rgb;
1587        var val = round(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11);
1588        rgb.r = rgb.g = rgb.b = val;
1589        return this;
1590      }
1591    }, {
1592      key: "opaquer",
1593      value: function opaquer(ratio) {
1594        var rgb = this._rgb;
1595        rgb.a *= 1 + ratio;
1596        return this;
1597      }
1598    }, {
1599      key: "negate",
1600      value: function negate() {
1601        var v = this._rgb;
1602        v.r = 255 - v.r;
1603        v.g = 255 - v.g;
1604        v.b = 255 - v.b;
1605        return this;
1606      }
1607    }, {
1608      key: "lighten",
1609      value: function lighten(ratio) {
1610        modHSL(this._rgb, 2, ratio);
1611        return this;
1612      }
1613    }, {
1614      key: "darken",
1615      value: function darken(ratio) {
1616        modHSL(this._rgb, 2, -ratio);
1617        return this;
1618      }
1619    }, {
1620      key: "saturate",
1621      value: function saturate(ratio) {
1622        modHSL(this._rgb, 1, ratio);
1623        return this;
1624      }
1625    }, {
1626      key: "desaturate",
1627      value: function desaturate(ratio) {
1628        modHSL(this._rgb, 1, -ratio);
1629        return this;
1630      }
1631    }, {
1632      key: "rotate",
1633      value: function rotate(deg) {
1634        _rotate(this._rgb, deg);
1635
1636        return this;
1637      }
1638    }]);
1639
1640    return Color;
1641  }();
1642
1643  function index_esm(input) {
1644    return new Color(input);
1645  }
1646
1647  var isPatternOrGradient = function isPatternOrGradient(value) {
1648    return value instanceof CanvasGradient || value instanceof CanvasPattern;
1649  };
1650
1651  function color(value) {
1652    return isPatternOrGradient(value) ? value : index_esm(value);
1653  }
1654
1655  function getHoverColor(value) {
1656    return isPatternOrGradient(value) ? value : index_esm(value).saturate(0.5).darken(0.1).hexString();
1657  }
1658
1659  var overrides = Object.create(null);
1660  var descriptors = Object.create(null);
1661
1662  function getScope$1(node, key) {
1663    if (!key) {
1664      return node;
1665    }
1666
1667    var keys = key.split('.');
1668
1669    for (var i = 0, n = keys.length; i < n; ++i) {
1670      var k = keys[i];
1671      node = node[k] || (node[k] = Object.create(null));
1672    }
1673
1674    return node;
1675  }
1676
1677  function _set(root, scope, values) {
1678    if (typeof scope === 'string') {
1679      return merge(getScope$1(root, scope), values);
1680    }
1681
1682    return merge(getScope$1(root, ''), scope);
1683  }
1684
1685  var Defaults = /*#__PURE__*/function () {
1686    function Defaults(_descriptors) {
1687      _classCallCheck(this, Defaults);
1688
1689      this.animation = undefined;
1690      this.backgroundColor = 'rgba(0,0,0,0.1)';
1691      this.borderColor = 'rgba(0,0,0,0.1)';
1692      this.color = '#666';
1693      this.datasets = {};
1694
1695      this.devicePixelRatio = function (context) {
1696        return context.chart.platform.getDevicePixelRatio();
1697      };
1698
1699      this.elements = {};
1700      this.events = ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'];
1701      this.font = {
1702        family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
1703        size: 12,
1704        style: 'normal',
1705        lineHeight: 1.2,
1706        weight: null
1707      };
1708      this.hover = {};
1709
1710      this.hoverBackgroundColor = function (ctx, options) {
1711        return getHoverColor(options.backgroundColor);
1712      };
1713
1714      this.hoverBorderColor = function (ctx, options) {
1715        return getHoverColor(options.borderColor);
1716      };
1717
1718      this.hoverColor = function (ctx, options) {
1719        return getHoverColor(options.color);
1720      };
1721
1722      this.indexAxis = 'x';
1723      this.interaction = {
1724        mode: 'nearest',
1725        intersect: true
1726      };
1727      this.maintainAspectRatio = true;
1728      this.onHover = null;
1729      this.onClick = null;
1730      this.parsing = true;
1731      this.plugins = {};
1732      this.responsive = true;
1733      this.scale = undefined;
1734      this.scales = {};
1735      this.showLine = true;
1736      this.describe(_descriptors);
1737    }
1738
1739    _createClass(Defaults, [{
1740      key: "set",
1741      value: function set(scope, values) {
1742        return _set(this, scope, values);
1743      }
1744    }, {
1745      key: "get",
1746      value: function get(scope) {
1747        return getScope$1(this, scope);
1748      }
1749    }, {
1750      key: "describe",
1751      value: function describe(scope, values) {
1752        return _set(descriptors, scope, values);
1753      }
1754    }, {
1755      key: "override",
1756      value: function override(scope, values) {
1757        return _set(overrides, scope, values);
1758      }
1759    }, {
1760      key: "route",
1761      value: function route(scope, name, targetScope, targetName) {
1762        var _Object$definePropert;
1763
1764        var scopeObject = getScope$1(this, scope);
1765        var targetScopeObject = getScope$1(this, targetScope);
1766        var privateName = '_' + name;
1767        Object.defineProperties(scopeObject, (_Object$definePropert = {}, _defineProperty(_Object$definePropert, privateName, {
1768          value: scopeObject[name],
1769          writable: true
1770        }), _defineProperty(_Object$definePropert, name, {
1771          enumerable: true,
1772          get: function get() {
1773            var local = this[privateName];
1774            var target = targetScopeObject[targetName];
1775
1776            if (isObject(local)) {
1777              return Object.assign({}, target, local);
1778            }
1779
1780            return valueOrDefault(local, target);
1781          },
1782          set: function set(value) {
1783            this[privateName] = value;
1784          }
1785        }), _Object$definePropert));
1786      }
1787    }]);
1788
1789    return Defaults;
1790  }();
1791
1792  var defaults = new Defaults({
1793    _scriptable: function _scriptable(name) {
1794      return !name.startsWith('on');
1795    },
1796    _indexable: function _indexable(name) {
1797      return name !== 'events';
1798    },
1799    hover: {
1800      _fallback: 'interaction'
1801    },
1802    interaction: {
1803      _scriptable: false,
1804      _indexable: false
1805    }
1806  });
1807
1808  function toFontString(font) {
1809    if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.fam
vendor: 10,397 bytes, lines 1809-2170
1809ily)) {
1810      return null;
1811    }
1812
1813    return (font.style ? font.style + ' ' : '') + (font.weight ? font.weight + ' ' : '') + font.size + 'px ' + font.family;
1814  }
1815
1816  function _measureText(ctx, data, gc, longest, string) {
1817    var textWidth = data[string];
1818
1819    if (!textWidth) {
1820      textWidth = data[string] = ctx.measureText(string).width;
1821      gc.push(string);
1822    }
1823
1824    if (textWidth > longest) {
1825      longest = textWidth;
1826    }
1827
1828    return longest;
1829  }
1830
1831  function _longestText(ctx, font, arrayOfThings, cache) {
1832    cache = cache || {};
1833    var data = cache.data = cache.data || {};
1834    var gc = cache.garbageCollect = cache.garbageCollect || [];
1835
1836    if (cache.font !== font) {
1837      data = cache.data = {};
1838      gc = cache.garbageCollect = [];
1839      cache.font = font;
1840    }
1841
1842    ctx.save();
1843    ctx.font = font;
1844    var longest = 0;
1845    var ilen = arrayOfThings.length;
1846    var i, j, jlen, thing, nestedThing;
1847
1848    for (i = 0; i < ilen; i++) {
1849      thing = arrayOfThings[i];
1850
1851      if (thing !== undefined && thing !== null && isArray(thing) !== true) {
1852        longest = _measureText(ctx, data, gc, longest, thing);
1853      } else if (isArray(thing)) {
1854        for (j = 0, jlen = thing.length; j < jlen; j++) {
1855          nestedThing = thing[j];
1856
1857          if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) {
1858            longest = _measureText(ctx, data, gc, longest, nestedThing);
1859          }
1860        }
1861      }
1862    }
1863
1864    ctx.restore();
1865    var gcLen = gc.length / 2;
1866
1867    if (gcLen > arrayOfThings.length) {
1868      for (i = 0; i < gcLen; i++) {
1869        delete data[gc[i]];
1870      }
1871
1872      gc.splice(0, gcLen);
1873    }
1874
1875    return longest;
1876  }
1877
1878  function _alignPixel(chart, pixel, width) {
1879    var devicePixelRatio = chart.currentDevicePixelRatio;
1880    var halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0;
1881    return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
1882  }
1883
1884  function clearCanvas(canvas, ctx) {
1885    ctx = ctx || canvas.getContext('2d');
1886    ctx.save();
1887    ctx.resetTransform();
1888    ctx.clearRect(0, 0, canvas.width, canvas.height);
1889    ctx.restore();
1890  }
1891
1892  function drawPoint(ctx, options, x, y) {
1893    var type, xOffset, yOffset, size, cornerRadius;
1894    var style = options.pointStyle;
1895    var rotation = options.rotation;
1896    var radius = options.radius;
1897    var rad = (rotation || 0) * RAD_PER_DEG;
1898
1899    if (style && _typeof(style) === 'object') {
1900      type = style.toString();
1901
1902      if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
1903        ctx.save();
1904        ctx.translate(x, y);
1905        ctx.rotate(rad);
1906        ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
1907        ctx.restore();
1908        return;
1909      }
1910    }
1911
1912    if (isNaN(radius) || radius <= 0) {
1913      return;
1914    }
1915
1916    ctx.beginPath();
1917
1918    switch (style) {
1919      default:
1920        ctx.arc(x, y, radius, 0, TAU);
1921        ctx.closePath();
1922        break;
1923
1924      case 'triangle':
1925        ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
1926        rad += TWO_THIRDS_PI;
1927        ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
1928        rad += TWO_THIRDS_PI;
1929        ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
1930        ctx.closePath();
1931        break;
1932
1933      case 'rectRounded':
1934        cornerRadius = radius * 0.516;
1935        size = radius - cornerRadius;
1936        xOffset = Math.cos(rad + QUARTER_PI) * size;
1937        yOffset = Math.sin(rad + QUARTER_PI) * size;
1938        ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
1939        ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
1940        ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
1941        ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
1942        ctx.closePath();
1943        break;
1944
1945      case 'rect':
1946        if (!rotation) {
1947          size = Math.SQRT1_2 * radius;
1948          ctx.rect(x - size, y - size, 2 * size, 2 * size);
1949          break;
1950        }
1951
1952        rad += QUARTER_PI;
1953
1954      case 'rectRot':
1955        xOffset = Math.cos(rad) * radius;
1956        yOffset = Math.sin(rad) * radius;
1957        ctx.moveTo(x - xOffset, y - yOffset);
1958        ctx.lineTo(x + yOffset, y - xOffset);
1959        ctx.lineTo(x + xOffset, y + yOffset);
1960        ctx.lineTo(x - yOffset, y + xOffset);
1961        ctx.closePath();
1962        break;
1963
1964      case 'crossRot':
1965        rad += QUARTER_PI;
1966
1967      case 'cross':
1968        xOffset = Math.cos(rad) * radius;
1969        yOffset = Math.sin(rad) * radius;
1970        ctx.moveTo(x - xOffset, y - yOffset);
1971        ctx.lineTo(x + xOffset, y + yOffset);
1972        ctx.moveTo(x + yOffset, y - xOffset);
1973        ctx.lineTo(x - yOffset, y + xOffset);
1974        break;
1975
1976      case 'star':
1977        xOffset = Math.cos(rad) * radius;
1978        yOffset = Math.sin(rad) * radius;
1979        ctx.moveTo(x - xOffset, y - yOffset);
1980        ctx.lineTo(x + xOffset, y + yOffset);
1981        ctx.moveTo(x + yOffset, y - xOffset);
1982        ctx.lineTo(x - yOffset, y + xOffset);
1983        rad += QUARTER_PI;
1984        xOffset = Math.cos(rad) * radius;
1985        yOffset = Math.sin(rad) * radius;
1986        ctx.moveTo(x - xOffset, y - yOffset);
1987        ctx.lineTo(x + xOffset, y + yOffset);
1988        ctx.moveTo(x + yOffset, y - xOffset);
1989        ctx.lineTo(x - yOffset, y + xOffset);
1990        break;
1991
1992      case 'line':
1993        xOffset = Math.cos(rad) * radius;
1994        yOffset = Math.sin(rad) * radius;
1995        ctx.moveTo(x - xOffset, y - yOffset);
1996        ctx.lineTo(x + xOffset, y + yOffset);
1997        break;
1998
1999      case 'dash':
2000        ctx.moveTo(x, y);
2001        ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
2002        break;
2003    }
2004
2005    ctx.fill();
2006
2007    if (options.borderWidth > 0) {
2008      ctx.stroke();
2009    }
2010  }
2011
2012  function _isPointInArea(point, area, margin) {
2013    margin = margin || 0.5;
2014    return point && point.x > area.left - margin && point.x < area.right + margin && point.y > area.top - margin && point.y < area.bottom + margin;
2015  }
2016
2017  function clipArea(ctx, area) {
2018    ctx.save();
2019    ctx.beginPath();
2020    ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
2021    ctx.clip();
2022  }
2023
2024  function unclipArea(ctx) {
2025    ctx.restore();
2026  }
2027
2028  function _steppedLineTo(ctx, previous, target, flip, mode) {
2029    if (!previous) {
2030      return ctx.lineTo(target.x, target.y);
2031    }
2032
2033    if (mode === 'middle') {
2034      var midpoint = (previous.x + target.x) / 2.0;
2035      ctx.lineTo(midpoint, previous.y);
2036      ctx.lineTo(midpoint, target.y);
2037    } else if (mode === 'after' !== !!flip) {
2038      ctx.lineTo(previous.x, target.y);
2039    } else {
2040      ctx.lineTo(target.x, previous.y);
2041    }
2042
2043    ctx.lineTo(target.x, target.y);
2044  }
2045
2046  function _bezierCurveTo(ctx, previous, target, flip) {
2047    if (!previous) {
2048      return ctx.lineTo(target.x, target.y);
2049    }
2050
2051    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);
2052  }
2053
2054  function renderText(ctx, text, x, y, font) {
2055    var opts = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
2056    var lines = isArray(text) ? text : [text];
2057    var stroke = opts.strokeWidth > 0 && opts.strokeColor !== '';
2058    var i, line;
2059    ctx.save();
2060    ctx.font = font.string;
2061    setRenderOpts(ctx, opts);
2062
2063    for (i = 0; i < lines.length; ++i) {
2064      line = lines[i];
2065
2066      if (stroke) {
2067        if (opts.strokeColor) {
2068          ctx.strokeStyle = opts.strokeColor;
2069        }
2070
2071        if (!isNullOrUndef(opts.strokeWidth)) {
2072          ctx.lineWidth = opts.strokeWidth;
2073        }
2074
2075        ctx.strokeText(line, x, y, opts.maxWidth);
2076      }
2077
2078      ctx.fillText(line, x, y, opts.maxWidth);
2079      decorateText(ctx, x, y, line, opts);
2080      y += font.lineHeight;
2081    }
2082
2083    ctx.restore();
2084  }
2085
2086  function setRenderOpts(ctx, opts) {
2087    if (opts.translation) {
2088      ctx.translate(opts.translation[0], opts.translation[1]);
2089    }
2090
2091    if (!isNullOrUndef(opts.rotation)) {
2092      ctx.rotate(opts.rotation);
2093    }
2094
2095    if (opts.color) {
2096      ctx.fillStyle = opts.color;
2097    }
2098
2099    if (opts.textAlign) {
2100      ctx.textAlign = opts.textAlign;
2101    }
2102
2103    if (opts.textBaseline) {
2104      ctx.textBaseline = opts.textBaseline;
2105    }
2106  }
2107
2108  function decorateText(ctx, x, y, line, opts) {
2109    if (opts.strikethrough || opts.underline) {
2110      var metrics = ctx.measureText(line);
2111      var left = x - metrics.actualBoundingBoxLeft;
2112      var right = x + metrics.actualBoundingBoxRight;
2113      var top = y - metrics.actualBoundingBoxAscent;
2114      var bottom = y + metrics.actualBoundingBoxDescent;
2115      var yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom;
2116      ctx.strokeStyle = ctx.fillStyle;
2117      ctx.beginPath();
2118      ctx.lineWidth = opts.decorationWidth || 2;
2119      ctx.moveTo(left, yDecoration);
2120      ctx.lineTo(right, yDecoration);
2121      ctx.stroke();
2122    }
2123  }
2124
2125  function addRoundedRectPath(ctx, rect) {
2126    var x = rect.x,
2127        y = rect.y,
2128        w = rect.w,
2129        h = rect.h,
2130        radius = rect.radius;
2131    ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, -HALF_PI, PI, true);
2132    ctx.lineTo(x, y + h - radius.bottomLeft);
2133    ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true);
2134    ctx.lineTo(x + w - radius.bottomRight, y + h);
2135    ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true);
2136    ctx.lineTo(x + w, y + radius.topRight);
2137    ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true);
2138    ctx.lineTo(x + radius.topLeft, y);
2139  }
2140
2141  var LINE_HEIGHT = new RegExp(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
2142  var FONT_STYLE = new RegExp(/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/);
2143
2144  function toLineHeight(value, size) {
2145    var matches = ('' + value).match(LINE_HEIGHT);
2146
2147    if (!matches || matches[1] === 'normal') {
2148      return size * 1.2;
2149    }
2150
2151    value = +matches[2];
2152
2153    switch (matches[3]) {
2154      case 'px':
2155        return value;
2156
2157      case '%':
2158        value /= 100;
2159        break;
2160    }
2161
2162    return size * value;
2163  }
2164
2165  var numberOrZero$1 = function numberOrZero(v) {
2166    return +v || 0;
2167  };
2168
2169  function _readValueToProps(value, props) {
2170    var ret = {};
2171    var objProps = isObject(props);
2172    var keys = objProps ? Object.keys(props) : props;
2173    var read = isObject(value) ? objProps ? function (prop) {
2174      return valueOrDefault(value[prop], value[props[prop]]);
2175    } : function (prop) {
2176      return value[prop];
2177    } : function () {
2178      return value;
2179    };
2180
2181    var _iterator2 = _createForOfIteratorHelper(keys),
2182        _step2;
2183
2184    try {
2185      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2186        var prop = _step2.value;
2187        ret[prop] = numberOrZero$1(read(prop));
2188      }
2189    } catch (err) {
2190      _iterator2.e(err);
2191    } finally {
2192      _iterator2.f();
2193    }
2194
2195    return ret;
2196  }
2197
2198  function toTRBL(value) {
2199    return _readValueToProps(value, {
2200      top: 'y',
2201      right: 'x',
2202      bottom: 'y',
2203      left: 'x'
2204    });
2205  }
2206
2207  function toTRBLCorners(value) {
2208    return _readValueToProps(value, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']);
2209  }
2210
2211  function toPadding(value) {
2212    var obj = toTRBL(value);
2213    obj.width = obj.left + obj.right;
2214    obj.height = obj.top + obj.bottom;
2215    return obj;
2216  }
2217
2218  function toFont(options, fallback) {
2219    options = options || {};
2220    fallback = fallback || defaults.font;
2221    var size = valueOrDefault(options.size, fallback.size);
2222
2223    if (typeof size === 'string') {
2224      size = parseInt(size, 10);
2225    }
2226
2227    var style = valueOrDefault(options.style, fallback.style);
2228
2229    if (style && !('' + style).match(FONT_STYLE)) {
2230      console.warn('Invalid font style specified: "' + style + '"');
2231      style = '';
2232    }
2233
2234    var font = {
2235      family: valueOrDefault(options.family, fallback.family),
2236      lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size),
2237      size: size,
2238      style: style,
2239      weight: valueOrDefault(options.weight, fallback.weight),
2240      string: ''
2241    };
2242    font.string = toFontString(font);
2243    return font;
2244  }
2245
2246  function resolve(inputs, context, index, info) {
2247    var cacheable = true;
2248    var i, ilen, value;
2249
2250    for (i = 0, ilen = inputs.length; i < ilen; ++i) {
2251      value = inputs[i];
2252
2253      if (value === undefined) {
2254        continue;
2255      }
2256
2257      if (context !== undefined && typeof value === 'function') {
2258        value = value(context);
2259        cacheable = false;
2260      }
2261
2262      if (index !== undefined && isArray(value)) {
2263        value = value[index % value.length];
2264        cacheable = false;
2265      }
2266
2267      if (value !== undefined) {
2268        if (info && !cacheable) {
2269          info.cacheable = false;
2270        }
2271
2272        return value;
2273      }
2274    }
2275  }
2276
2277  function _addGrace(minmax, grace) {
2278    var min = minmax.min,
2279        max = minmax.max;
2280    return {
2281      min: min - Math.abs(toDimension(grace, min)),
2282      max: max + toDimension(grace, max)
2283    };
2284  }
2285
2286  function _lookup(table, value, cmp) {
2287    cmp = cmp || function (index) {
2288      return table[index] < value;
2289    };
2290
2291    var hi = table.length - 1;
2292    var lo = 0;
2293    var mid;
2294
2295    while (hi - lo > 1) {
2296      mid = lo + hi >> 1;
2297
2298      if (cmp(mid)) {
2299        lo = mid;
2300      } else {
2301        hi = mid;
2302      }
2303    }
2304
2305    return {
2306      lo: lo,
2307      hi: hi
2308    };
2309  }
2310
2311  var _lookupByKey = function _lookupByKey(table, key, value) {
2312    return _lookup(table, value, function (index) {
2313      return table[index][key] < value;
2314    });
2315  };
2316
2317  var _rlookupByKey = function _rlookupByKey(table, key, value) {
2318    return _lookup(table, value, function (index) {
2319      return table[index][key] >= value;
2320    });
2321  };
2322
2323  function _filterBetween(values, min, max) {
2324    var start = 0;
2325    var end = values.length;
2326
2327    while (start < end && values[start] < min) {
2328      start++;
2329    }
2330
2331    while (end > start && values[end - 1] > max) {
2332      end--;
2333    }
2334
2335    return start > 0 || end < values.length ? values.slice(start, end) : values;
2336  }
2337
2338  var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
2339
2340  function listenArrayEvents(array, listener) {
2341    if (array._chartjs) {
2342      array._chartjs.listeners.push(listener);
2343
2344      return;
2345    }
2346
2347    Object.defineProperty(array, '_chartjs', {
2348      configurable: true,
2349      enumerable: false,
2350      value: {
2351        listeners: [listener]
2352      }
2353    });
2354    arrayEvents.forEach(function (key) {
2355      var method = '_onData' + _capitalize(key);
2356
2357      var base = array[key];
2358      Object.defineProperty(array, key, {
2359        configurable: true,
2360        enumerable: false,
2361        value: function value() {
2362          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
2363            args[_key2] = arguments[_key2];
2364          }
2365
2366          var res = base.apply(this, args);
2367
2368          array._chartjs.listeners.forEach(function (object) {
2369            if (typeof object[method] === 'function') {
2370              object[method].apply(object, args);
2371            }
2372          });
2373
2374          return res;
2375        }
2376      });
2377    });
2378  }
2379
2380  function unlistenArrayEvents(array, listener) {
2381    var stub = array._chartjs;
2382
2383    if (!stub) {
2384      return;
2385    }
2386
2387    var listeners = stub.listeners;
2388    var index = listeners.indexOf(listener);
2389
2390    if (index !== -1) {
2391      listeners.splice(index, 1);
2392    }
2393
2394    if (listeners.length > 0) {
2395      return;
2396    }
2397
2398    arrayEvents.forEach(function (key) {
2399      delete array[key];
2400    });
2401    delete array._chartjs;
2402  }
2403
2404  function _arrayUnique(items) {
2405    var set = new Set();
2406    var i, ilen;
2407
2408    for (i = 0, ilen = items.length; i < ilen; ++i) {
2409      set.add(items[i]);
2410    }
2411
2412    if (set.size === ilen) {
2413      return items;
2414    }
2415
2416    return Array.from(set);
2417  }
2418
2419  function _createResolver(scopes) {
2420    var _cache;
2421
2422    var prefixes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [''];
2423    var rootScopes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : scopes;
2424    var fallback = arguments.length > 3 ? arguments[3] : undefined;
2425    var getTarget = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : function () {
2426      return scopes[0];
2427    };
2428
2429    if (!defined(fallback)) {
2430      fallback = _resolve('_fallback', scopes);
2431    }
2432
2433    var cache = (_cache = {}, _defineProperty(_cache, Symbol.toStringTag, 'Object'), _defineProperty(_cache, "_cacheable", true), _defineProperty(_cache, "_scopes", scopes), _defineProperty(_cache, "_rootScopes", rootScopes), _defineProperty(_cache, "_fallback", fallback), _defineProperty(_cache, "_getTarget", getTarget), _defineProperty(_cache, "override", function override(scope) {
2434      return _createResolver([scope].concat(_toConsumableArray(scopes)), prefixes, rootScopes, fallback);
2435    }), _cache);
2436    return new Proxy(cache, {
2437      deleteProperty: function deleteProperty(target, prop) {
2438        delete target[prop];
2439        delete target._keys;
2440        delete scopes[0][prop];
2441        return true;
2442      },
2443      get: function get(target, prop) {
2444        return _cached(target, prop, function () {
2445          return _resolveWithPrefixes(prop, prefixes, scopes, target);
2446        });
2447      },
2448      getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, prop) {
2449        return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop);
2450      },
2451      getPrototypeOf: function getPrototypeOf() {
2452        return Reflect.getPrototypeOf(scopes[0]);
2453      },
2454      has: function has(target, prop) {
2455        return getKeysFromAllScopes(target).includes(prop);
2456      },
2457      ownKeys: function ownKeys(target) {
2458        return getKeysFromAllScopes(target);
2459      },
2460      set: function set(target, prop, value) {
2461        var storage = target._storage || (target._storage = getTarget());
2462        storage[prop] = value;
2463        delete target[prop];
2464        delete target._keys;
2465        return true;
2466      }
2467    });
2468  }
2469
2470  function _attachContext(proxy, context, subProxy, descriptorDefaults) {
2471    var cache = {
2472      _cacheable: false,
2473      _proxy: proxy,
2474      _context: context,
2475      _subProxy: subProxy,
2476      _stack: new Set(),
2477      _descriptors: _descriptors(proxy, descriptorDefaults),
2478      setContext: function setContext(ctx) {
2479        return _attachContext(proxy, ctx, subProxy, descriptorDefaults);
2480      },
2481      override: function override(scope) {
2482        return _attachContext(proxy.override(scope), context, subProxy, descriptorDefaults);
2483      }
2484    };
2485    return new Proxy(cache, {
2486      deleteProperty: function deleteProperty(target, prop) {
2487        delete target[prop];
2488        delete proxy[prop];
2489        return true;
2490      },
2491      get: function get(target, prop, receiver) {
2492        return _cached(target, prop, function () {
2493          return _resolveWithContext(target, prop, receiver);
2494        });
2495      },
2496      getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, prop) {
2497        return target._descriptors.allKeys ? Reflect.has(proxy, prop
2497) ? {
2498          enumerable: true,
2499          configurable: true
2500        } : undefined : Reflect.getOwnPropertyDescriptor(proxy, prop);
2501      },
2502      getPrototypeOf: function getPrototypeOf() {
2503        return Reflect.getPrototypeOf(proxy);
2504      },
2505      has: function has(target, prop) {
2506        return Reflect.has(proxy, prop);
2507      },
2508      ownKeys: function ownKeys() {
2509        return Reflect.ownKeys(proxy);
2510      },
2511      set: function set(target, prop, value) {
2512        proxy[prop] = value;
2513        delete target[prop];
2514        return true;
2515      }
2516    });
2517  }
2518
2519  function _descriptors(proxy) {
2520    var defaults = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
2521      scriptable: true,
2522      indexable: true
2523    };
2524
2525    var _proxy$_scriptable = proxy._scriptable,
2526        _scriptable = _proxy$_scriptable === void 0 ? defaults.scriptable : _proxy$_scriptable,
2527        _proxy$_indexable = proxy._indexable,
2528        _indexable = _proxy$_indexable === void 0 ? defaults.indexable : _proxy$_indexable,
2529        _proxy$_allKeys = proxy._allKeys,
2530        _allKeys = _proxy$_allKeys === void 0 ? defaults.allKeys : _proxy$_allKeys;
2531
2532    return {
2533      allKeys: _allKeys,
2534      scriptable: _scriptable,
2535      indexable: _indexable,
2536      isScriptable: isFunction(_scriptable) ? _scriptable : function () {
2537        return _scriptable;
2538      },
2539      isIndexable: isFunction(_indexable) ? _indexable : function () {
2540        return _indexable;
2541      }
2542    };
2543  }
2544
2545  var readKey = function readKey(prefix, name) {
2546    return prefix ? prefix + _capitalize(name) : name;
2547  };
2548
2549  var needsSubResolver = function needsSubResolver(prop, value) {
2550    return isObject(value) && prop !== 'adapters';
2551  };
2552
2553  function _cached(target, prop, resolve) {
2554    var value = target[prop];
2555
2556    if (defined(value)) {
2557      return value;
2558    }
2559
2560    value = resolve();
2561
2562    if (defined(value)) {
2563      target[prop] = value;
2564    }
2565
2566    return value;
2567  }
2568
2569  function _resolveWithContext(target, prop, receiver) {
2570    var _proxy = target._proxy,
2571        _context = target._context,
2572        _subProxy = target._subProxy,
2573        descriptors = target._descriptors;
2574    var value = _proxy[prop];
2575
2576    if (isFunction(value) && descriptors.isScriptable(prop)) {
2577      value = _resolveScriptable(prop, value, target, receiver);
2578    }
2579
2580    if (isArray(value) && value.length) {
2581      value = _resolveArray(prop, value, target, descriptors.isIndexable);
2582    }
2583
2584    if (needsSubResolver(prop, value)) {
2585      value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors);
2586    }
2587
2588    return value;
2589  }
2590
2591  function _resolveScriptable(prop, value, target, receiver) {
2592    var _proxy = target._proxy,
2593        _context = target._context,
2594        _subProxy = target._subProxy,
2595        _stack = target._stack;
2596
2597    if (_stack.has(prop)) {
2598      throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop);
2599    }
2600
2601    _stack.add(prop);
2602
2603    value = value(_context, _subProxy || receiver);
2604
2605    _stack.delete(prop);
2606
2607    if (isObject(value)) {
2608      value = createSubResolver(_proxy._scopes, _proxy, prop, value);
2609    }
2610
2611    return value;
2612  }
2613
2614  function _resolveArray(prop, value, target, isIndexable) {
2615    var _proxy = target._proxy,
2616        _context = target._context,
2617        _subProxy = target._subProxy,
2618        descriptors = target._descriptors;
2619
2620    if (defined(_context.index) && isIndexable(prop)) {
2621      value = value[_context.index % value.length];
2622    } else if (isObject(value[0])) {
2623      var arr = value;
2624
2625      var scopes = _proxy._scopes.filter(function (s) {
2626        return s !== arr;
2627      });
2628
2629      value = [];
2630
2631      var _iterator3 = _createForOfIteratorHelper(arr),
2632          _step3;
2633
2634      try {
2635        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
2636          var item = _step3.value;
2637          var resolver = createSubResolver(scopes, _proxy, prop, item);
2638          value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors));
2639        }
2640      } catch (err) {
2641        _iterator3.e(err);
2642      } finally {
2643        _iterator3.f();
2644      }
2645    }
2646
2647    return value;
2648  }
2649
2650  function resolveFallback(fallback, prop, value) {
2651    return isFunction(fallback) ? fallback(prop, value) : fallback;
2652  }
2653
2654  var getScope = function getScope(key, parent) {
2655    return key === true ? parent : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined;
2656  };
2657
2658  function addScopes(set, parentScopes, key, parentFallback) {
2659    var _iterator4 = _createForOfIteratorHelper(parentScopes),
2660        _step4;
2661
2662    try {
2663      for (_iterator4.s();
2663 !(_step4 = _iterator4.n()).done;) {
2664        var parent = _step4.value;
2665        var scope = getScope(key, parent);
2666
2667        if (scope) {
2668          set.add(scope);
2669          var fallback = resolveFallback(scope._fallback, key, scope);
2670
2671          if (defined(fallback) && fallback !== key && fallback !== parentFallback) {
2672            return fallback;
2673          }
2674        } else if (scope === false && defined(parentFallback) && key !== parentFallback) {
2675          return null;
2676        }
2677      }
2678    } catch (err) {
2679      _iterator4.e(err);
2680    } finally {
2681      _iterator4.f();
2682    }
2683
2684    return false;
2685  }
2686
2687  function createSubResolver(parentScopes, resolver, prop, value) {
2688    var rootScopes = resolver._rootScopes;
2689    var fallback = resolveFallback(resolver._fallback, prop, value);
2690    var allScopes = [].concat(_toConsumableArray(parentScopes), _toConsumableArray(rootScopes));
2691    var set = new Set();
2692    set.add(value);
2693    var key = addScopesFromKey(set, allScopes, prop, fallback || prop);
2694
2695    if (key === null) {
2696      return false;
2697    }
2698
2699    if (defined(fallback) && fallback !== prop) {
2700      key = addScopesFromKey(set, allScopes, fallback, key);
2701
2702      if (key === null) {
2703        return false;
2704      }
2705    }
2706
2707    return _createResolver(Array.from(set), [''], rootScopes, fallback, function () {
2708      return subGetTarget(resolver, prop, value);
2709    });
2710  }
2711
2712  function addScopesFromKey(set, allScopes, key, fallback) {
2713    while (key) {
2714      key = addScopes(set, allScopes, key, fallback);
2715    }
2716
2717    return key;
2718  }
2719
2720  function subGetTarget(resolver, prop, value) {
2721    var parent = resolver._getTarget();
2722
2723    if (!(prop in parent)) {
2724      parent[prop] = {};
2725    }
2726
2727    var target = parent[prop];
2728
2729    if (isArray(target) && isObject(value)) {
2730      return value;
2731    }
2732
2733    return target;
2734  }
2735
2736  function _resolveWithPrefixes(prop, prefixes, scopes, proxy) {
2737    var value;
2738
2739    var _iterator5 = _createForOfIteratorHelper(prefixes),
2740        _step5;
2741
2742    try {
2743      for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
2744        var prefix = _step5.value;
2745        value = _resolve(readKey(prefix, prop), scopes);
2746
2747        if (defined(value)) {
2748          return needsSubResolver(prop, value) ? createSubResolver(scopes, proxy, prop, value) : value;
2749        }
2750      }
2751    } catch (err) {
2752      _iterator5.e(err);
2753    } finally {
2754      _iterator5.f();
2755    }
2756  }
2757
2758  function _resolve(key, scopes) {
2759    var _iterator6 = _createForOfIteratorHelper(scopes),
2760        _step6;
2761
2762    try {
2763      for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
2764        var scope = _step6.value;
2765
2766        if (!scope) {
2767          continue;
2768        }
2769
2770        var value = scope[key];
2771
2772        if (defined(value)) {
2773          return value;
2774        }
2775      }
2776    } catch (err) {
2777      _iterator6.e(err);
2778    } finally {
2779      _iterator6.f();
2780    }
2781  }
2782
2783  function getKeysFromAllScopes(target) {
2784    var keys = target._keys;
2785
2786    if (!keys) {
2787      keys = target._keys = resolveKeysFromAllScopes(target._scopes);
2788    }
2789
2790    return keys;
2791  }
2792
2793  function resolveKeysFromAllScopes(scopes) {
2794    var set = new Set();
2795
2796    var _iterator7 = _createForOfIteratorHelper(scopes),
2797        _step7;
2798
2799    try {
2800      for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
2801        var scope = _step7.value;
2802
2803        var _iterator8 = _createForOfIteratorHelper(Object.keys(scope).filter(function (k) {
2804          return !k.startsWith('_');
2805        })),
2806            _step8;
2807
2808        try {
2809          for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
2810            var key = _step8.value;
2811            set.add(key);
2812          }
2813        } catch (err) {
2814          _iterator8.e(err);
2815        } finally {
2816          _iterator8.f();
2817        }
2818      }
2819    } catch (err) {
2820      _iterator7.e(err);
2821    } finally {
2822      _iterator7.f();
2823    }
2824
2825    return Array.from(set);
2826  }
2827
2828  var EPSILON = Number.EPSILON || 1e-14;
2829
2830  var getPoint = function getPoint(points, i) {
2831    return i < points.length && !points[i].skip && points[i];
2832  };
2833
2834  var getValueAxis = function getValueAxis(indexAxis) {
2835    return indexAxis === 'x' ? 'y' : 'x';
2836  };
2837
2838  function splineCurve(firstPoint, middlePoint, afterPoint, t) {
2839    var previous = firstPoint.skip ? middlePoint : firstPoint;
2840    var current = middlePoint;
2841    var next = afterPoint.skip ? middlePoint : afterPoint;
2842    var d01 = distanceBetweenPoints(current, previous);
2843    var d12 = distanceBetweenPoints(next, current);
2844    var s01 = d01 / (d01 + d12);
2845    var s12 = d12 / (d01 + d12);
2846    s01 = isNaN(s01) ? 0 : s01;
2847    s12 = isNaN(s12) ? 0 : s12;
2848    var fa = t * s01;
2849    var fb = t * s12;
2850    return {
2851      previous: {
2852        x: current.x - fa * (next.x - previous.x),
2853        y: current.y - fa * (next.y - previous.y)
2854      },
2855      next: {
2856        x: current.x + fb * (next.x - previous.x),
2857        y: current.y + fb * (next.y - previous.y)
2858      }
2859    };
2860  }
2861
2862  function monotoneAdjust(points, deltaK, mK) {
2863    var pointsLen = points.length;
2864    var alphaK, betaK, tauK, squaredMagnitude, pointCurrent;
2865    var pointAfter = getPoint(points, 0);
2866
2867    for (var i = 0; i < pointsLen - 1; ++i) {
2868      pointCurrent = pointAfter;
2869      pointAfter = getPoint(points, i + 1);
2870
2871      if (!pointCurrent || !pointAfter) {
2872        continue;
2873      }
2874
2875      if (almostEquals(deltaK[i], 0, EPSILON)) {
2876        mK[i] = mK[i + 1] = 0;
2877        continue;
2878      }
2879
2880      alphaK = mK[i] / deltaK[i];
2881      betaK = mK[i + 1] / deltaK[i];
2882      squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
2883
2884      if (squaredMagnitude <= 9) {
2885        continue;
2886      }
2887
2888      tauK = 3 / Math.sqrt(squaredMagnitude);
2889      mK[i] = alphaK * tauK * deltaK[i];
2890      mK[i + 1] = betaK * tauK * deltaK[i];
2891    }
2892  }
2893
2894  function monotoneCompute(points, mK) {
2895    var indexAxis = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'x';
2896    var valueAxis = getValueAxis(indexAxis);
2897    var pointsLen = points.length;
2898    var delta, pointBefore, pointCurrent;
2899    var pointAfter = getPoint(points, 0);
2900
2901    for (var i = 0; i < pointsLen; ++i) {
2902      pointBefore = pointCurrent;
2903      pointCurrent = pointAfter;
2904      pointAfter = getPoint(points, i + 1);
2905
2906      if (!pointCurrent) {
2907        continue;
2908      }
2909
2910      var iPixel = pointCurrent[indexAxis];
2911      var vPixel = pointCurrent[valueAxis];
2912
2913      if (pointBefore) {
2914        delta = (iPixel - pointBefore[indexAxis]) / 3;
2915        pointCurrent["cp1".concat(indexAxis)] = iPixel - delta;
2916        pointCurrent["cp1".concat(valueAxis)] = vPixel - delta * mK[i];
2917      }
2918
2919      if (pointAfter) {
2920        delta = (pointAfter[indexAxis] - iPixel) / 3;
2921        pointCurrent["cp2".concat(indexAxis)] = iPixel + delta;
2922        pointCurrent["cp2".concat(valueAxis)] = vPixel + delta * mK[i];
2923      }
2924    }
2925  }
2926
2927  function splineCurveMonotone(points) {
2928    var indexAxis = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'x';
2929    var valueAxis = getValueAxis(indexAxis);
2930    var pointsLen = points.length;
2931    var deltaK = Array(pointsLen).fill(0);
2932    var mK = Array(pointsLen);
2933    var i, pointBefore, pointCurrent;
2934    var pointAfter = getPoint(points, 0);
2935
2936    for (i = 0; i < pointsLen; ++i) {
2937      pointBefore = pointCurrent;
2938      pointCurrent = pointAfter;
2939      pointAfter = getPoint(points, i + 1);
2940
2941      if (!pointCurrent) {
2942        continue;
2943      }
2944
2945      if (pointAfter) {
2946        var slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis];
2947        deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0;
2948      }
2949
2950      mK[i] = !pointBefore ? deltaK[i] : !pointAfter ? deltaK[i - 1] : sign(deltaK[i - 1]) !== sign(deltaK[i]) ? 0 : (deltaK[i - 1] + deltaK[i]) / 2;
2951    }
2952
2953    monotoneAdjust(points, deltaK, mK);
2954    monotoneCompute(points, mK, indexAxis);
2955  }
2956
2957  function capControlPoint(pt, min, max) {
2958    return Math.max(Math.min(pt, max), min);
2959  }
2960
2961  function capBezierPoints(points, area) {
2962    var i, ilen, point, inArea, inAreaPrev;
2963
2964    var inAreaNext = _isPointInArea(points[0], area);
2965
2966    for (i = 0, ilen = points.length; i < ilen; ++i) {
2967      inAreaPrev = inArea;
2968      inArea = inAreaNext;
2969      inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area);
2970
2971      if (!inArea) {
2972        continue;
2973      }
2974
2975      point = points[i];
2976
2977      if (inAreaPrev) {
2978        point.cp1x = capControlPoint(point.cp1x, area.left, area.right);
2979        point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom);
2980      }
2981
2982      if (inAreaNext) {
2983        point.cp2x = capControlPoint(point.cp2x, area.left, area.right);
2984        point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom);
2985      }
2986    }
2987  }
2988
2989  function _updateBezierControlPoints(points, options, area, loop, indexAxis) {
2990    var i, ilen, point, controlPoints;
2991
2992    if (options.spanGaps) {
2993      points = points.filter(function (pt) {
2994        return !pt.skip;
2995      });
2996    }
2997
2998    if (options.cubicInterpolationMode === 'monotone') {
2999      splineCurveMonotone(points, indexAxis);
3000    } else {
3001      var prev = loop ? points[points.length - 1] : points[0];
3002
3003      for (i = 0, ilen = points.length; i < ilen; ++i) {
3004        point = points[i];
3005        controlPoints = splineCurve(prev, point, points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen], options.tension);
3006        point.cp1x = controlPoints.previous.x;
3007        point.cp1y = controlPoints.previous.y;
3008        point.cp2x = controlPoints.next.x;
3009        point.cp2y = controlPoints.next.y;
3010        prev = point;
3011      }
3012    }
3013
3014    if (options.capBezierPoints) {
3015      capBezierPoints(points, area);
3016    }
3017  }
3018
3019  function _getParentNode(domNode) {
3020    var parent = domNode.parentNode;
3021
3022    if (parent && parent.toString() === '[object ShadowRoot]') {
3023      parent = parent.host;
3024    }
3025
3026    return parent;
3027  }
3028
3029  function parseMaxStyle(styleValue, node, parentProperty) {
3030    var valueInPixels;
3031
3032    if (typeof styleValue === 'string') {
3033      valueInPixels = parseInt(styleValue, 10);
3034
3035      if (styleValue.indexOf('%') !== -1) {
3036        valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
3037      }
3038    } else {
3039      valueInPixels = styleValue;
3040    }
3041
3042    return valueInPixels;
3043  }
3044
3045  var getComputedStyle = function getComputedStyle(element) {
3046    return window.getComputedStyle(element, null);
3047  };
3048
3049  function getStyle(el, property) {
3050    return getComputedStyle(el).getPropertyValue(property);
3051  }
3052
3053  var positions = ['top', 'right', 'bottom', 'left'];
3054
3055  function getPositionedStyle(styles, style, suffix) {
3056    var result = {};
3057    suffix = suffix ? '-' + suffix : '';
3058
3059    for (var i = 0; i < 4; i++) {
3060      var pos = positions[i];
3061      result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0;
3062    }
3063
3064    result.width = result.left + result.right;
3065    result.height = result.top + result.bottom;
3066    return result;
3067  }
3068
3069  var useOffsetPos = function useOffsetPos(x, y, target) {
3070    return (x > 0 || y > 0) && (!target || !target.shadowRoot);
3071  };
3072
3073  function getCanvasPosition(evt, canvas) {
3074    var e = evt.native || evt;
3075    var touches = e.touches;
3076    var source = touches && touches.length ? touches[0] : e;
3077    var offsetX = source.offsetX,
3078        offsetY = source.offsetY;
3079    var box = false;
3080    var x, y;
3081
3082    if (useOffsetPos(offsetX, offsetY, e.target)) {
3083      x = offsetX;
3084      y = offsetY;
3085    } else {
3086      var rect = canvas.getBoundingClientRect();
3087      x = source.clientX - rect.left;
3088      y = source.clientY - rect.top;
3089      box = true;
3090    }
3091
3092    return {
3093      x: x,
3094      y: y,
3095      box: box
3096    };
3097  }
3098
3099  function getRelativePosition$1(evt, chart) {
3100    var canvas = chart.canvas,
3101        currentDevicePixelRatio = chart.currentDevicePixelRatio;
3102    var style = getComputedStyle(canvas);
3103    var borderBox = style.boxSizing === 'border-box';
3104    var paddings = getPositionedStyle(style, 'padding');
3105    var borders = getPositionedStyle(style, 'border', 'width');
3106
3107    var _getCanvasPosition = getCanvasPosition(evt, canvas),
3108        x = _getCanvasPosition.x,
3109        y = _getCanvasPosition.y,
3110        box = _getCanvasPosition.box;
3111
3112    var xOffset = paddings.left + (box && borders.left);
3113    var yOffset = paddings.top + (box && borders.top);
3114    var width = chart.width,
3115        height = chart.height;
3116
3117    if (borderBox) {
3118      width -= paddings.width + borders.width;
3119      height -= paddings.height + borders.height;
3120    }
3121
3122    return {
3123      x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio),
3124      y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio)
3125    };
3126  }
3127
3128  function getContainerSize(canvas, width, height) {
3129    var maxWidth, maxHeight;
3130
3131    if (width === undefined || height === undefined) {
3132      var container = _getParentNode(canvas);
3133
3134      if (!container) {
3135        width = canvas.clientWidth;
3136        height = canvas.clientHeight;
3137      } else {
3138        var rect = container.getBoundingClientRect();
3139        var containerStyle = getComputedStyle(container);
3140        var containerBorder = getPositionedStyle(containerStyle, 'border', 'width');
3141        var containerPadding = getPositionedStyle(containerStyle, 'padding');
3142        width = rect.width - containerPadding.width - containerBorder.width;
3143        height = rect.height - containerPadding.height - containerBorder.height;
3144        maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth');
3145        maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight');
3146      }
3147    }
3148
3149    return {
3150      width: width,
3151      height: height,
3152      maxWidth: maxWidth || INFINITY,
3153      maxHeight: maxHeight || INFINITY
3154    };
3155  }
3156
3157  var round1 = function round1(v) {
3158    return Math.round(v * 10) / 10;
3159  };
3160
3161  function getMaximumSize(canvas, bbWidth, bbHeight, aspectRatio) {
3162    var style = getComputedStyle(canvas);
3163    var margins = getPositionedStyle(style, 'margin');
3164    var maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY;
3165    var maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY;
3166    var containerSize = getContainerSize(canvas, bbWidth, bbHeight);
3167    var width = containerSize.width,
3168        height = containerSize.height;
3169
3170    if (style.boxSizing === 'content-box') {
3171      var borders = getPositionedStyle(style, 'border', 'width');
3172      var paddings = getPositionedStyle(style, 'padding');
3173      width -= paddings.width + borders.width;
3174      height -= paddings.height + borders.height;
3175    }
3176
3177    width = Math.max(0, width - margins.width);
3178    height = Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height - margins.height);
3179    width = round1(Math.min(width, maxWidth, containerSize.maxWidth));
3180    height = round1(Math.min(height, maxHeight, containerSize.maxHeight));
3181
3182    if (width && !height) {
3183      height = round1(width / 2);
3184    }
3185
3186    return {
3187      width: width,
3188      height: height
3189    };
3190  }
3191
3192  function retinaScale(chart, forceRatio, forceStyle) {
3193    var pixelRatio = forceRatio || 1;
3194    var deviceHeight = Math.floor(chart.height * pixelRatio);
3195    var deviceWidth = Math.floor(chart.width * pixelRatio);
3196    chart.height = deviceHeight / pixelRatio;
3197    chart.width = deviceWidth / pixelRatio;
3198    var canvas = chart.canvas;
3199
3200    if (canvas.style && (forceStyle || !canvas.style.height && !canvas.style.width)) {
3201      canvas.style.height = "".concat(chart.height, "px");
3202      canvas.style.width = "".concat(chart.width, "px");
3203    }
3204
3205    if (chart.currentDevicePixelRatio !== pixelRatio || canvas.height !== deviceHeight || canvas.width !== deviceWidth) {
3206      chart.currentDevicePixelRatio = pixelRatio;
3207      canvas.height = deviceHeight;
3208      canvas.width = deviceWidth;
3209      chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
3210      return true;
3211    }
3212
3213    return false;
3214  }
3215
3216  var supportsEventListenerOptions = function () {
3217    var passiveSupported = false;
3218
3219    try {
3220      var options = {
3221        get passive() {
3222          passiveSupported = true;
3223          return false;
3224        }
3225
3226      };
3227      window.addEventListener('test', null, options);
3228      window.removeEventListener('test', null, options);
3229    } catch (e) {}
3230
3231    return passiveSupported;
3232  }();
3233
3234  function readUsedSize(element, property) {
3235    var value = getStyle(element, property);
3236    var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
3237    return matches ? +matches[1] : undefined;
3238  }
3239
3240  function _pointInLine(p1, p2, t, mode) {
3241    return {
3242      x: p1.x + t * (p2.x - p1.x),
3243      y: p1.y + t * (p2.y - p1.y)
3244    };
3245  }
3246
3247  function _steppedInterpolation(p1, p2, t, mode) {
3248    return {
3249      x: p1.x + t * (p2.x - p1.x),
3250      y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y : mode === 'after' ? t < 1 ? p1.y : p2.y : t > 0 ? p2.y : p1.y
3251    };
3252  }
3253
3254  function _bezierInterpolation(p1, p2, t, mode) {
3255    var cp1 = {
3256      x: p1.cp2x,
3257      y: p1.cp2y
3258    };
3259    var cp2 = {
3260      x: p2.cp1x,
3261      y: p2.cp1y
3262    };
3263
3264    var a = _pointInLine(p1, cp1, t);
3265
3266    var b = _pointInLine(cp1, cp2, t);
3267
3268    var c = _pointInLine(cp2, p2, t);
3269
3270    var d = _pointInLine(a, b, t);
3271
3272    var e = _pointInLine(b, c, t);
3273
3274    return _pointInLine(d, e, t);
3275  }
3276
3277  var intlCache = new Map();
3278
3279  function getNumberFormat(locale, options) {
3280    options = options || {};
3281    var cacheKey = locale + JSON.stringify(options);
3282    var formatter = intlCache.get(cacheKey);
3283
3284    if (!formatter) {
3285      formatter = new Intl.NumberFormat(locale, options);
3286      intlCache.set(cacheKey, formatter);
3287    }
3288
3289    return formatter;
3290  }
3291
3292  function formatNumber(num, locale, options) {
3293    return getNumberFormat(locale, options).format(num);
3294  }
3295
3296  var getRightToLeftAdapter = function getRightToLeftAdapter(rectX, width) {
3297    return {
3298      x: function x(_x) {
3299        return rectX + rectX + width - _x;
3300      },
3301      setWidth: function setWidth(w) {
3302        width = w;
3303      },
3304      textAlign: function textAlign(align) {
3305        if (align === 'center') {
3306          return align;
3307        }
3308
3309        return align === 'right' ? 'left' : 'right';
3310      },
3311      xPlus: function xPlus(x, value) {
3312        return x - value;
3313      },
3314      leftForLtr: function leftForLtr(x, itemWidth) {
3315        return x - itemWidth;
3316      }
3317    };
3318  };
3319
3320  var getLeftToRightAdapter = function getLeftToRightAdapter() {
3321    return {
3322      x: function x(_x2) {
3323        return _x2;
3324      },
3325      setWidth: function setWidth(w) {},
3326      textAlign: function textAlign(align) {
3327        return align;
3328      },
3329      xPlus: function xPlus(x, value) {
3330        return x + value;
3331      },
3332      leftForLtr: function leftForLtr(x, _itemWidth) {
3333        return x;
3334      }
3335    };
3336  };
3337
3338  function getRtlAdapter(rtl, rectX, width) {
3339    return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter();
3340  }
3341
3342  function overrideTextDirection(ctx, direction) {
3343    var style, original;
3344
3345    if (direction === 'ltr' || direction === 'rtl') {
3346      style = ctx.canvas.style;
3347      original = [style.getPropertyValue('direction'), style.getPropertyPriority('direction')];
3348      style.setProperty('direction', direction, 'important');
3349      ctx.prevTextDirection = original;
3350    }
3351  }
3352
3353  function restoreTextDirection(ctx, original) {
3354    if (original !== undefined) {
3355      delete ctx.prevTextDirection;
3356      ctx.canvas.style.setProperty('direction', original[0], original[1]);
3357    }
3358  }
3359
3360  function propertyFn(property) {
3361    if (property === 'angle') {
3362      return {
3363        between: _angleBetween,
3364        compare: _angleDiff,
3365        normalize: _normalizeAngle
3366      };
3367    }
3368
3369    return {
3370      between: function between(n, s, e) {
3371        return n >= Math.min(s, e) && n <= Math.max(e, s);
3372      },
3373      compare: function compare(a, b) {
3374        return a - b;
3375      },
3376      normalize: function normalize(x) {
3377        return x;
3378      }
3379    };
3380  }
3381
3382  function normalizeSegment(_ref) {
3383    var start = _ref.start,
3384        end = _ref.end,
3385        count = _ref.count,
3386        loop = _ref.loop,
3387        style = _ref.style;
3388    return {
3389      start: start % count,
3390      end: end % count,
3391      loop: loop && (end - start + 1) % count === 0,
3392      style: style
3393    };
3394  }
3395
3396  function getSegment(segment, points, bounds) {
3397    var property = bounds.property,
3398        startBound = bounds.start,
3399        endBound = bounds.end;
3400
3401    var _propertyFn = propertyFn(property),
3402        between = _propertyFn.between,
3403        normalize = _propertyFn.normalize;
3404
3405    var count = points.length;
3406    var start = segment.start,
3407        end = segment.end,
3408        loop = segment.loop;
3409    var i, ilen;
3410
3411    if (loop) {
3412      start += count;
3413      end += count;
3414
3415      for (i = 0, ilen = count; i < ilen; ++i) {
3416        if (!between(normalize(points[start % count][property]), startBound, endBound)) {
3417          break;
3418        }
3419
3420        start--;
3421        end--;
3422      }
3423
3424      start %= count;
3425      end %= count;
3426    }
3427
3428    if (end < start) {
3429      end += count;
3430    }
3431
3432    return {
3433      start: start,
3434      end: end,
3435      loop: loop,
3436      style: segment.style
3437    };
3438  }
3439
3440  function _boundSegment(segment, points, bounds) {
3441    if (!bounds) {
3442      return [segment];
3443    }
3444
3445    var property = bounds.property,
3446        startBound = bounds.start,
3447        endBound = bounds.end;
3448    var count = points.length;
3449
3450    var _propertyFn2 = propertyFn(property),
3451        compare = _propertyFn2.compare,
3452        between = _propertyFn2.between,
3453        normalize = _propertyFn2.normalize;
3454
3455    var _getSegment = getSegment(segment, points, bounds),
3456        start = _getSegment.start,
3457        end = _getSegment.end,
3458        loop = _getSegment.loop,
3459        style = _getSegment.style;
3460
3461    var result = [];
3462    var inside = false;
3463    var subStart = null;
3464    var value, point, prevValue;
3465
3466    var startIsBefore = function startIsBefore() {
3467      return between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0;
3468    };
3469
3470    var endIsBefore = function endIsBefore() {
3471      return compare(endBound, value) === 0 || between(endBound, prevValue, value);
3472    };
3473
3474    var shouldStart = function shouldStart() {
3475      return inside || startIsBefore();
3476    };
3477
3478    var shouldStop = function shouldStop() {
3479      return !inside || endIsBefore();
3480    };
3481
3482    for (var i = start, prev = start; i <= end; ++i) {
3483      point = points[i % count];
3484
3485      if (point.skip) {
3486        continue;
3487      }
3488
3489      value = normalize(point[property]);
3490
3491      if (value === prevValue) {
3492        continue;
3493      }
3494
3495      inside = between(value, startBound, endBound);
3496
3497      if (subStart === null && shouldStart()) {
3498        subStart = compare(value, startBound) === 0 ? i : prev;
3499      }
3500
3501      if (subStart !== null && shouldStop()) {
3502        result.push(normalizeSegment({
3503          start: subStart,
3504          end: i,
3505          loop: loop,
3506          count: count,
3507          style: style
3508        }));
3509        subStart = null;
3510      }
3511
3512      prev = i;
3513      prevValue = value;
3514    }
3515
3516    if (subStart !== null) {
3517      result.push(normalizeSegment({
3518        start: subStart,
3519        end: end,
3520        loop: loop,
3521        count: count,
3522        style: style
3523      }));
3524    }
3525
3526    return result;
3527  }
3528
3529  function _boundSegments(line, bounds) {
3530    var result = [];
3531    var segments = line.segments;
3532
3533    for (var i = 0; i < segments.length; i++) {
3534      var sub = _boundSegment(segments[i], line.points, bounds);
3535
3536      if (sub.length) {
3537        result.push.apply(result, _toConsumableArray(sub));
3538      }
3539    }
3540
3541    return result;
3542  }
3543
3544  function findStartAndEnd(points, count, loop, spanGaps) {
3545    var start = 0;
3546    var end = count - 1;
3547
3548    if (loop && !spanGaps) {
3549      while (start < count && !points[start].skip) {
3550        start++;
3551      }
3552    }
3553
3554    while (start < count && points[start].skip) {
3555      start++;
3556    }
3557
3558    start %= count;
3559
3560    if (loop) {
3561      end += start;
3562    }
3563
3564    while (end > start && points[end % count].skip) {
3565      end--;
3566    }
3567
3568    end %= count;
3569    return {
3570      start: start,
3571      end: end
3572    };
3573  }
3574
3575  function solidSegments(points, start, max, loop) {
3576    var count = points.length;
3577    var result = [];
3578    var last = start;
3579    var prev = points[start];
3580    var end;
3581
3582    for (end = start + 1; end <= max; ++end) {
3583      var cur = points[end % count];
3584
3585      if (cur.skip || cur.stop) {
3586        if (!prev.skip) {
3587          loop = false;
3588          result.push({
3589            start: start % count,
3590            end: (end - 1) % count,
3591            loop: loop
3592          });
3593          start = last = cur.stop ? end : null;
3594        }
3595      } else {
3596        last = end;
3597
3598        if (prev.skip) {
3599          start = end;
3600        }
3601      }
3602
3603      prev = cur;
3604    }
3605
3606    if (last !== null) {
3607      result.push({
3608        start: start % count,
3609        end: last % count,
3610        loop: loop
3611      });
3612    }
3613
3614    return result;
3615  }
3616
3617  function _computeSegments(line, segmentOptions) {
3618    var points = line.points;
3619    var spanGaps = line.options.spanGaps;
3620    var count = points.length;
3621
3622    if (!count) {
3623      return [];
3624    }
3625
3626    var loop = !!line._loop;
3627
3628    var _findStartAndEnd = findStartAndEnd(points, count, loop, spanGaps),
3629        start = _findStartAndEnd.start,
3630        end = _findStartAndEnd.end;
3631
3632    if (spanGaps === true) {
3633      return splitByStyles([{
3634        start: start,
3635        end: end,
3636        loop: loop
3637      }], points, segmentOptions);
3638    }
3639
3640    var max = end < start ? end + count : end;
3641    var completeLoop = !!line._fullLoop && start === 0 && end === count - 1;
3642    return splitByStyles(solidSegments(points, start, max, completeLoop), points, segmentOptions);
3643  }
3644
3645  function splitByStyles(segments, points, segmentOptions) {
3646    if (!segmentOptions || !segmentOptions.setContext || !points) {
3647      return segments;
3648    }
3649
3650    return doSplitByStyles(segments, points, segmentOptions);
3651  }
3652
3653  function doSplitByStyles(segments, points, segmentOptions) {
3654    var count = points.length;
3655    var result = [];
3656    var start = segments[0].start;
3657    var i = start;
3658
3659    var _iterator9 = _createForOfIteratorHelper(segments),
3660        _step9;
3661
3662    try {
3663      for (_iterator9.s();
3663 !(_step9 = _iterator9.n()).done;) {
3664        var segment = _step9.value;
3665        var prevStyle = void 0,
3666            style = void 0;
3667        var prev = points[start % count];
3668
3669        for (i = start + 1; i <= segment.end; i++) {
3670          var pt = points[i % count];
3671          style = readStyle(segmentOptions.setContext({
3672            type: 'segment',
3673            p0: prev,
3674            p1: pt
3675          }));
3676
3677          if (styleChanged(style, prevStyle)) {
3678            result.push({
3679              start: start,
3680              end: i - 1,
3681              loop: segment.loop,
3682              style: prevStyle
3683            });
3684            prevStyle = style;
3685            start = i - 1;
3686          }
3687
3688          prev = pt;
3689          prevStyle = style;
3690        }
3691
3692        if (start < i - 1) {
3693          result.push({
3694            start: start,
3695            end: i - 1,
3696            loop: segment.loop,
3697            style: style
3698          });
3699          start = i - 1;
3700        }
3701      }
3702    } catch (err) {
3703      _iterator9.e(err);
3704    } finally {
3705      _iterator9.f();
3706    }
3707
3708    return result;
3709  }
3710
3711  function readStyle(options) {
3712    return {
3713      backgroundColor: options.backgroundColor,
3714      borderCapStyle: options.borderCapStyle,
3715      borderDash: options.borderDash,
3716      borderDashOffset: options.borderDashOffset,
3717      borderJoinStyle: options.borderJoinStyle,
3718      borderWidth: options.borderWidth,
3719      borderColor: options.borderColor
3720    };
3721  }
3722
3723  function styleChanged(style, prevStyle) {
3724    return prevStyle && JSON.stringify(style) !== JSON.stringify(prevStyle);
3725  }
3726
3727  var Animator = /*#__PURE__*/function () {
3728    function Animator() {
3729      _classCallCheck(this, Animator);
3730
3731      this._request = null;
3732      this._charts = new Map();
3733      this._running = false;
3734      this._lastDate = undefined;
3735    }
3736
3737    _createClass(Animator, [{
3738      key: "_notify",
3739      value: function _notify(chart, anims, date, type) {
3740        var callbacks = anims.listeners[type];
3741        var numSteps = anims.duration;
3742        callbacks.forEach(function (fn) {
3743          return fn({
3744            chart: chart,
3745            initial: anims.initial,
3746            numSteps: numSteps,
3747            currentStep: Math.min(date - anims.start, numSteps)
3748          });
3749        });
3750      }
3751    }, {
3752      key: "_refresh",
3753      value: function _refresh() {
3754        var me = this;
3755
3756        if (me._request) {
3757          return;
3758        }
3759
3760        me._running = true;
3761        me._request = requestAnimFrame.call(window, function () {
3762          me._update();
3763
3764          me._request = null;
3765
3766          if (me._running) {
3767            me._refresh();
3768          }
3769        });
3770      }
3771    }, {
3772      key: "_update",
3773      value: function _update() {
3774        var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Date.now();
3775        var me = this;
3776        var remaining = 0;
3777
3778        me._charts.forEach(function (anims, chart) {
3779          if (!anims.running || !anims.items.length) {
3780            return;
3781          }
3782
3783          var items = anims.items;
3784          var i = items.length - 1;
3785          var draw = false;
3786          var item;
3787
3788          for (; i >= 0; --i) {
3789            item = items[i];
3790
3791            if (item._active) {
3792              if (item._total > anims.duration) {
3793                anims.duration = item._total;
3794              }
3795
3796              item.tick(date);
3797              draw = true;
3798            } else {
3799              items[i] = items[items.length - 1];
3800              items.pop();
3801            }
3802          }
3803
3804          if (draw) {
3805            chart.draw();
3806
3807            me._notify(chart, anims, date, 'progress');
3808          }
3809
3810          if (!items.length) {
3811            anims.running = false;
3812
3813            me._notify(chart, anims, date, 'complete');
3814
3815            anims.initial = false;
3816          }
3817
3818          remaining += items.length;
3819        });
3820
3821        me._lastDate = date;
3822
3823        if (remaining === 0) {
3824          me._running = false;
3825        }
3826      }
3827    }, {
3828      key: "_getAnims",
3829      value: function _getAnims(chart) {
3830        var charts = this._charts;
3831        var anims = charts.get(chart);
3832
3833        if (!anims) {
3834          anims = {
3835            running: false,
3836            initial: true,
3837            items: [],
3838            listeners: {
3839              complete: [],
3840              progress: []
3841            }
3842          };
3843          charts.set(chart, anims);
3844        }
3845
3846        return anims;
3847      }
3848    }, {
3849      key: "listen",
3850      value: function listen(chart, event, cb) {
3851        this._getAnims(chart).listeners[event].push(cb);
3852      }
3853    }, {
3854      key: "add",
3855      value: function add(chart, items) {
3856        var _this$_getAnims$items;
3857
3858        if (!items || !items.length) {
3859          return;
3860        }
3861
3862        (_this$_getAnims$items = this._getAnims(chart).items).push.apply(_this$_getAnims$items, _toConsumableArray(items));
3863      }
3864    }, {
3865      key: "has",
3866      value: function has(chart) {
3867        return this._getAnims(chart).items.length > 0;
3868      }
3869    }, {
3870      key: "start",
3871      value: function start(chart) {
3872        var anims = this._charts.get(chart);
3873
3874        if (!anims) {
3875          return;
3876        }
3877
3878        anims.running = true;
3879        anims.start = Date.now();
3880        anims.duration = anims.items.reduce(function (acc, cur) {
3881          return Math.max(acc, cur._duration);
3882        }, 0);
3883
3884        this._refresh();
3885      }
3886    }, {
3887      key: "running",
3888      value: function running(chart) {
3889        if (!this._running) {
3890          return false;
3891        }
3892
3893        var anims = this._charts.get(chart);
3894
3895        if (!anims || !anims.running || !anims.items.length) {
3896          return false;
3897        }
3898
3899        return true;
3900      }
3901    }, {
3902      key: "stop",
3903      value: function stop(chart) {
3904        var anims = this._charts.get(chart);
3905
3906        if (!anims || !anims.items.length) {
3907          return;
3908        }
3909
3910        var items = anims.items;
3911        var i = items.length - 1;
3912
3913        for (; i >= 0; --i) {
3914          items[i].cancel();
3915        }
3916
3917        anims.items = [];
3918
3919        this._notify(chart, anims, Date.now(), 'complete');
3920      }
3921    }, {
3922      key: "remove",
3923      value: function remove(chart) {
3924        return this._charts.delete(chart);
3925      }
3926    }]);
3927
3928    return Animator;
3929  }();
3930
3931  var animator = new Animator();
3932  var transparent = 'transparent';
3933  var interpolators = {
3934    boolean: function boolean(from, to, factor) {
3935      return factor > 0.5 ? to : from;
3936    },
3937    color: function color$1(from, to, factor) {
3938      var c0 = color(from || transparent);
3939
3940      var c1 = c0.valid && color(to || transparent);
3941
3942      return c1 && c1.valid ? c1.mix(c0, factor).hexString() : to;
3943    },
3944    number: function number(from, to, factor) {
3945      return from + (to - from) * factor;
3946    }
3947  };
3948
3949  var Animation = /*#__PURE__*/function () {
3950    function Animation(cfg, target, prop, to) {
3951      _classCallCheck(this, Animation);
3952
3953      var currentValue = target[prop];
3954      to = resolve([cfg.to, to, currentValue, cfg.from]);
3955      var from = resolve([cfg.from, currentValue, to]);
3956      this._active = true;
3957      this._fn = cfg.fn || interpolators[cfg.type || _typeof(from)];
3958      this._easing = effects[cfg.easing] || effects.linear;
3959      this._start = Math.floor(Date.now() + (cfg.delay || 0));
3960      this._duration = this._total = Math.floor(cfg.duration);
3961      this._loop = !!cfg.loop;
3962      this._target = target;
3963      this._prop = prop;
3964      this._from = from;
3965      this._to = to;
3966      this._promises = undefined;
3967    }
3968
3969    _createClass(Animation, [{
3970      key: "active",
3971      value: function active() {
3972        return this._active;
3973      }
3974    }, {
3975      key: "update",
3976      value: function update(cfg, to, date) {
3977        var me = this;
3978
3979        if (me._active) {
3980          me._notify(false);
3981
3982          var currentValue = me._target[me._prop];
3983          var elapsed = date - me._start;
3984          var remain = me._duration - elapsed;
3985          me._start = date;
3986          me._duration = Math.floor(Math.max(remain, cfg.duration));
3987          me._total += elapsed;
3988          me._loop = !!cfg.loop;
3989          me._to = resolve([cfg.to, to, currentValue, cfg.from]);
3990          me._from = resolve([cfg.from, currentValue, to]);
3991        }
3992      }
3993    }, {
3994      key: "cancel",
3995      value: function cancel() {
3996        var me = this;
3997
3998        if (me._active) {
3999          me.tick(Date.now());
4000          me._active = false;
4001
4002          me._notify(false);
4003        }
4004      }
4005    }, {
4006      key: "tick",
4007      value: function tick(date) {
4008        var me = this;
4009        var elapsed = date - me._start;
4010        var duration = me._duration;
4011        var prop = me._prop;
4012        var from = me._from;
4013        var loop = me._loop;
4014        var to = me._to;
4015        var factor;
4016        me._active = from !== to && (loop || elapsed < duration);
4017
4018        if (!me._active) {
4019          me._target[prop] = to;
4020
4021          me._notify(true);
4022
4023          return;
4024        }
4025
4026        if (elapsed < 0) {
4027          me._target[prop] = from;
4028          return;
4029        }
4030
4031        factor = elapsed / duration % 2;
4032        factor = loop && factor > 1 ? 2 - factor : factor;
4033        factor = me._easing(Math.min(1, Math.max(0, factor)));
4034        me._target[prop] = me._fn(from, to, factor);
4035      }
4036    }, {
4037      key: "wait",
4038      value: function wait() {
4039        var promises = this._promises || (this._promises = []);
4040        return new Promise(function (res, rej) {
4041          promises.push({
4042            res: res,
4043            rej: rej
4044          });
4045        });
4046      }
4047    }, {
4048      key: "_notify",
4049      value: function _notify(resolved) {
4050        var method = resolved ? 'res' : 'rej';
4051        var promises = this._promises || [];
4052
4053        for (var i = 0; i < promises.length; i++) {
4054          promises[i][method]();
4055        }
4056      }
4057    }]);
4058
4059    return Animation;
4060  }();
4061
4062  var numbers = ['x', 'y', 'borderWidth', 'radius', 'tension'];
4063  var colors = ['color', 'borderColor', 'backgroundColor'];
4064  defaults.set('animation', {
4065    delay: undefined,
4066    duration: 1000,
4067    easing: 'easeOutQuart',
4068    fn: undefined,
4069    from: undefined,
4070    loop: undefined,
4071    to: undefined,
4072    type: undefined
4073  });
4074  var animationOptions = Object.keys(defaults.animation);
4075  defaults.describe('animation', {
4076    _fallback: false,
4077    _indexable: false,
4078    _scriptable: function _scriptable(name) {
4079      return name !== 'onProgress' && name !== 'onComplete' && name !== 'fn';
4080    }
4081  });
4082  defaults.set('animations', {
4083    colors: {
4084      type: 'color',
4085      properties: colors
4086    },
4087    numbers: {
4088      type: 'number',
4089      properties: numbers
4090    }
4091  });
4092  defaults.describe('animations', {
4093    _fallback: 'animation'
4094  });
4095  defaults.set('transitions', {
4096    active: {
4097      animation: {
4098        duration: 400
4099      }
4100    },
4101    resize: {
4102      animation: {
4103        duration: 0
4104      }
4105    },
4106    show: {
4107      animations: {
4108        colors: {
4109          from: 'transparent'
4110        },
4111        visible: {
4112          type: 'boolean',
4113          duration: 0
4114        }
4115      }
4116    },
4117    hide: {
4118      animations: {
4119        colors: {
4120          to: 'transparent'
4121        },
4122        visible: {
4123          type: 'boolean',
4124          easing: 'linear',
4125          fn: function fn(v) {
4126            return v | 0;
4127          }
4128        }
4129      }
4130    }
4131  });
4132
4133  var Animations = /*#__PURE__*/function () {
4134    function Animations(chart, config) {
4135      _classCallCheck(this, Animations);
4136
4137      this._chart = chart;
4138      this._properties = new Map();
4139      this.configure(config);
4140    }
4141
4142    _createClass(Animations, [{
4143      key: "configure",
4144      value: function configure(config) {
4145        if (!isObject(config)) {
4146          return;
4147        }
4148
4149        var animatedProps = this._properties;
4150        Object.getOwnPropertyNames(config).forEach(function (key) {
4151          var cfg = config[key];
4152
4153          if (!isObject(cfg)) {
4154            return;
4155          }
4156
4157          var resolved = {};
4158
4159          var _iterator = _createForOfIteratorHelper(animationOptions),
4160              _step;
4161
4162          try {
4163            for (_iterator.s(); !(_step = _iterator.n()).done;) {
4164              var option = _step.value;
4165              resolved[option] = cfg[option];
4166            }
4167          } catch (err) {
4168            _iterator.e(err);
4169          } finally {
4170            _iterator.f();
4171          }
4172
4173          (isArray(cfg.properties) && cfg.properties || [key]).forEach(function (prop) {
4174            if (prop === key || !animatedProps.has(prop)) {
4175              animatedProps.set(prop, resolved);
4176            }
4177          });
4178        });
4179      }
4180    }, {
4181      key: "_animateOptions",
4182      value: function _animateOptions(target, values) {
4183        var newOptions = values.options;
4184        var options = resolveTargetOptions(target, newOptions);
4185
4186        if (!options) {
4187          return [];
4188        }
4189
4190        var animations = this._createAnimations(options, newOptions);
4191
4192        if (newOptions.$shared) {
4193          awaitAll(target.options.$animations, newOptions).then(function () {
4194            target.options = newOptions;
4195          }, function () {});
4196        }
4197
4198        return animations;
4199      }
4200    }, {
4201      key: "_createAnimations",
4202      value: function _createAnimations(target, values) {
4203        var animatedProps = this._properties;
4204        var animations = [];
4205        var running = target.$animations || (target.$animations = {});
4206        var props = Object.keys(values);
4207        var date = Date.now();
4208        var i;
4209
4210        for (i = props.length - 1; i >= 0; --i) {
4211          var prop = props[i];
4212
4213          if (prop.charAt(0) === '$') {
4214            continue;
4215          }
4216
4217          if (prop === 'options') {
4218            animations.push.apply(animations, _toConsumableArray(this._animateOptions(target, values)));
4219            continue;
4220          }
4221
4222          var value = values[prop];
4223          var animation = running[prop];
4224          var cfg = animatedProps.get(prop);
4225
4226          if (animation) {
4227            if (cfg && animation.active()) {
4228              animation.update(cfg, value, date);
4229              continue;
4230            } else {
4231              animation.cancel();
4232            }
4233          }
4234
4235          if (!cfg || !cfg.duration) {
4236            target[prop] = value;
4237            continue;
4238          }
4239
4240          running[prop] = animation = new Animation(cfg, target, prop, value);
4241          animations.push(animation);
4242        }
4243
4244        return animations;
4245      }
4246    }, {
4247      key: "update",
4248      value: function update(target, values) {
4249        if (this._properties.size === 0) {
4250          Object.assign(target, values);
4251          return;
4252        }
4253
4254        var animations = this._createAnimations(target, values);
4255
4256        if (animations.length) {
4257          animator.add(this._chart, animations);
4258          return true;
4259        }
4260      }
4261    }]);
4262
4263    return Animations;
4264  }();
4265
4266  function awaitAll(animations, properties) {
4267    var running = [];
4268    var keys = Object.keys(properties);
4269
4270    for (var i = 0; i < keys.length; i++) {
4271      var anim = animations[keys[i]];
4272
4273      if (anim && anim.active()) {
4274        running.push(anim.wait());
4275      }
4276    }
4277
4278    return Promise.all(running);
4279  }
4280
4281  function resolveTargetOptions(target, newOptions) {
4282    if (!newOptions) {
4283      return;
4284    }
4285
4286    var options = target.options;
4287
4288    if (!options) {
4289      target.options = newOptions;
4290      return;
4291    }
4292
4293    if (options.$shared) {
4294      target.options = options = Object.assign({}, options, {
4295        $shared: false,
4296        $animations: {}
4297      });
4298    }
4299
4300    return options;
4301  }
4302
4303  function scaleClip(scale, allowedOverflow) {
4304    var opts = scale && scale.options || {};
4305    var reverse = opts.reverse;
4306    var min = opts.min === undefined ? allowedOverflow : 0;
4307    var max = opts.max === undefined ? allowedOverflow : 0;
4308    return {
4309      start: reverse ? max : min,
4310      end: reverse ? min : max
4311    };
4312  }
4313
4314  function defaultClip(xScale, yScale, allowedOverflow) {
4315    if (allowedOverflow === false) {
4316      return false;
4317    }
4318
4319    var x = scaleClip(xScale, allowedOverflow);
4320    var y = scaleClip(yScale, allowedOverflow);
4321    return {
4322      top: y.end,
4323      right: x.end,
4324      bottom: y.start,
4325      left: x.start
4326    };
4327  }
4328
4329  function toClip(value) {
4330    var t, r, b, l;
4331
4332    if (isObject(value)) {
4333      t = value.top;
4334      r = value.right;
4335      b = value.bottom;
4336      l = value.left;
4337    } else {
4338      t = r = b = l = value;
4339    }
4340
4341    return {
4342      top: t,
4343      right: r,
4344      bottom: b,
4345      left: l,
4346      disabled: value === false
4347    };
4348  }
4349
4350  function getSortedDatasetIndices(chart, filterVisible) {
4351    var keys = [];
4352
4353    var metasets = chart._getSortedDatasetMetas(filterVisible);
4354
4355    var i, ilen;
4356
4357    for (i = 0, ilen = metasets.length; i < ilen; ++i) {
4358      keys.push(metasets[i].index);
4359    }
4360
4361    return keys;
4362  }
4363
4364  function _applyStack(stack, value, dsIndex, options) {
4365    var keys = stack.keys;
4366    var singleMode = options.mode === 'single';
4367    var i, ilen, datasetIndex, otherValue;
4368
4369    if (value === null) {
4370      return;
4371    }
4372
4373    for (i = 0, ilen = keys.length; i < ilen; ++i) {
4374      datasetIndex = +keys[i];
4375
4376      if (datasetIndex === dsIndex) {
4377        if (options.all) {
4378          continue;
4379        }
4380
4381        break;
4382      }
4383
4384      otherValue = stack.values[datasetIndex];
4385
4386      if (isNumberFinite(otherValue) && (singleMode || value === 0 || sign(value) === sign(otherValue))) {
4387        value += otherValue;
4388      }
4389    }
4390
4391    return value;
4392  }
4393
4394  function convertObjectDataToArray(data) {
4395    var keys = Object.keys(data);
4396    var adata = new Array(keys.length);
4397    var i, ilen, key;
4398
4399    for (i = 0, ilen = keys.length; i < ilen; ++i) {
4400      key = keys[i];
4401      adata[i] = {
4402        x: key,
4403        y: data[key]
4404      };
4405    }
4406
4407    return adata;
4408  }
4409
4410  function isStacked(scale, meta) {
4411    var stacked = scale && scale.options.stacked;
4412    return stacked || stacked === undefined && meta.stack !== undefined;
4413  }
4414
4415  function getStackKey(indexScale, valueScale, meta) {
4416    return "".concat(indexScale.id, ".").concat(valueScale.id, ".").concat(meta.stack || meta.type);
4417  }
4418
4419  function getUserBounds(scale) {
4420    var _scale$getUserBounds = scale.getUserBounds(),
4421        min = _scale$getUserBounds.min,
4422        max = _scale$getUserBounds.max,
4423        minDefined = _scale$getUserBounds.minDefined,
4424        maxDefined = _scale$getUserBounds.maxDefined;
4425
4426    return {
4427      min: minDefined ? min : Number.NEGATIVE_INFINITY,
4428      max: maxDefined ? max : Number.POSITIVE_INFINITY
4429    };
4430  }
4431
4432  function getOrCreateStack(stacks, stackKey, indexValue) {
4433    var subStack = stacks[stackKey] || (stacks[stackKey] = {});
4434    return subStack[indexValue] || (subStack[indexValue] = {});
4435  }
4436
4437  function getLastIndexInStack(stack, vScale, positive) {
4438    var _iterator2 = _createForOfIteratorHelper(vScale.getMatchingVisibleMetas('bar').reverse()),
4439        _step2;
4440
4441    try {
4442      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
4443        var meta = _step2.value;
4444        var value = stack[meta.index];
4445
4446        if (positive && value > 0 || !positive && value < 0) {
4447          return meta.index;
4448        }
4449      }
4450    } catch (err) {
4451      _iterator2.e(err);
4452    } finally {
4453      _iterator2.f();
4454    }
4455
4456    return null;
4457  }
4458
4459  function updateStacks(controller, parsed) {
4460    var chart = controller.chart,
4461        meta = controller._cachedMeta;
4462    var stacks = chart._stacks || (chart._stacks = {});
4463    var iScale = meta.iScale,
4464        vScale = meta.vScale,
4465        datasetIndex = meta.index;
4466    var iAxis = iScale.axis;
4467    var vAxis = vScale.axis;
4468    var key = getStackKey(iScale, vScale, meta);
4469    var ilen = parsed.length;
4470    var stack;
4471
4472    for (var i = 0; i < ilen; ++i) {
4473      var item = parsed[i];
4474      var index = item[iAxis],
4475          value = item[vAxis];
4476      var itemStacks = item._stacks || (item._stacks = {});
4477      stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);
4478      stack[datasetIndex] = value;
4479      stack._top = getLastIndexInStack(stack, vScale, true);
4480      stack._bottom = getLastIndexInStack(stack, vScale, false);
4481    }
4482  }
4483
4484  function getFirstScaleId(chart, axis) {
4485    var scales = chart.scales;
4486    return Object.keys(scales).filter(function (key) {
4487      return scales[key].axis === axis;
4488    }).shift();
4489  }
4490
4491  function createDatasetContext(parent, index) {
4492    return Object.assign(Object.create(parent), {
4493      active: false,
4494      dataset: undefined,
4495      datasetIndex: index,
4496      index: index,
4497      mode: 'default',
4498      type: 'dataset'
4499    });
4500  }
4501
4502  function createDataContext(parent, index, element) {
4503    return Object.assign(Object.create(parent), {
4504      active: false,
4505      dataIndex: index,
4506      parsed: undefined,
4507      raw: undefined,
4508      element: element,
4509      index: index,
4510      mode: 'default',
4511      type: 'data'
4512    });
4513  }
4514
4515  function clearStacks(meta, items) {
4516    var axis = meta.vScale && meta.vScale.axis;
4517
4518    if (!axis) {
4519      return;
4520    }
4521
4522    items = items || meta._parsed;
4523
4524    var _iterator3 = _createForOfIteratorHelper(items),
4525        _step3;
4526
4527    try {
4528      for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
4529        var parsed = _step3.value;
4530        var stacks = parsed._stacks;
4531
4532        if (!stacks || stacks[axis] === undefined || stacks[axis][meta.index] === undefined) {
4533          return;
4534        }
4535
4536        delete stacks[axis][meta.index];
4537      }
4538    } catch (err) {
4539      _iterator3.e(err);
4540    } finally {
4541      _iterator3.f();
4542    }
4543  }
4544
4545  var isDirectUpdateMode = function isDirectUpdateMode(mode) {
4546    return mode === 'reset' || mode === 'none';
4547  };
4548
4549  var cloneIfNotShared = function cloneIfNotShared(cached, shared) {
4550    return shared ? cached : Object.assign({}, cached);
4551  };
4552
4553  var DatasetController = /*#__PURE__*/function () {
4554    function DatasetController(chart, datasetIndex) {
4555      _classCallCheck(this, DatasetController);
4556
4557      this.chart = chart;
4558      this._ctx = chart.ctx;
4559      this.index = datasetIndex;
4560      this._cachedDataOpts = {};
4561      this._cachedMeta = this.getMeta();
4562      this._type = this._cachedMeta.type;
4563      this.options = undefined;
4564      this._parsing = false;
4565      this._data = undefined;
4566      this._objectData = undefined;
4567      this._sharedOptions = undefined;
4568      this._drawStart = undefined;
4569      this._drawCount = undefined;
4570      this.enableOptionSharing = false;
4571      this.$context = undefined;
4572      this._syncList = [];
4573      this.initialize();
4574    }
4575
4576    _createClass(DatasetController, [{
4577      key: "initialize",
4578      value: function initialize() {
4579        var me = this;
4580        var meta = me._cachedMeta;
4581        me.configure();
4582        me.linkScales();
4583        meta._stacked = isStacked(meta.vScale, meta);
4584        me.addElements();
4585      }
4586    }, {
4587      key: "updateIndex",
4588      value: function updateIndex(datasetIndex) {
4589        if (this.index !== datasetIndex) {
4590          clearStacks(this._cachedMeta);
4591        }
4592
4593        this.index = datasetIndex;
4594      }
4595    }, {
4596      key: "linkScales",
4597      value: function linkScales() {
4598        var me = this;
4599        var chart = me.chart;
4600        var meta = me._cachedMeta;
4601        var dataset = me.getDataset();
4602
4603        var chooseId = function chooseId(axis, x, y, r) {
4604          return axis === 'x' ? x : axis === 'r' ? r : y;
4605        };
4606
4607        var xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));
4608        var yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));
4609        var rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));
4610        var indexAxis = meta.indexAxis;
4611        var iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);
4612        var vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);
4613        meta.xScale = me.getScaleForId(xid);
4614        meta.yScale = me.getScaleForId(yid);
4615        meta.rScale = me.getScaleForId(rid);
4616        meta.iScale = me.getScaleForId(iid);
4617        meta.vScale = me.getScaleForId(vid);
4618      }
4619    }, {
4620      key: "getDataset",
4621      value: function getDataset() {
4622        return this.chart.data.datasets[this.index];
4623      }
4624    }, {
4625      key: "getMeta",
4626      value: function getMeta() {
4627        return this.chart.getDatasetMeta(this.index);
4628      }
4629    }, {
4630      key: "getScaleForId",
4631      value: function getScaleForId(scaleID) {
4632        return this.chart.scales[scaleID];
4633      }
4634    }, {
4635      key: "_getOtherScale",
4636      value: function _getOtherScale(scale) {
4637        var meta = this._cachedMeta;
4638        return scale === meta.iScale ? meta.vScale : meta.iScale;
4639      }
4640    }, {
4641      key: "reset",
4642      value: function reset() {
4643        this._update('reset');
4644      }
4645    }, {
4646      key: "_destroy",
4647      value: function _destroy() {
4648        var meta = this._cachedMeta;
4649
4650        if (this._data) {
4651          unlistenArrayEvents(this._data, this);
4652        }
4653
4654        if (meta._stacked) {
4655          clearStacks(meta);
4656        }
4657      }
4658    }, {
4659      key: "_dataCheck",
4660      value: function _dataCheck() {
4661        var me = this;
4662        var dataset = me.getDataset();
4663        var data = dataset.data || (dataset.data = []);
4664        var _data = me._data;
4665
4666        if (isObject(data)) {
4667          me._data = convertObjectDataToArray(data);
4668        } else if (_data !== data) {
4669          if (_data) {
4670            unlistenArrayEvents(_data, me);
4671            var meta = me._cachedMeta;
4672            clearStacks(meta);
4673            meta._parsed = [];
4674          }
4675
4676          if (data && Object.isExtensible(data)) {
4677            listenArrayEvents(data, me);
4678          }
4679
4680          me._syncList = [];
4681          me._data = data;
4682        }
4683      }
4684    }, {
4685      key: "addElements",
4686      value: function addElements() {
4687        var me = this;
4688        var meta = me._cachedMeta;
4689
4690        me._dataCheck();
4691
4692        if (me.datasetElementType) {
4693          meta.dataset = new me.datasetElementType();
4694        }
4695      }
4696    }, {
4697      key: "buildOrUpdateElements",
4698      value: function buildOrUpdateElements(resetNewElements) {
4699        var me = this;
4700        var meta = me._cachedMeta;
4701        var dataset = me.getDataset();
4702        var stackChanged = false;
4703
4704        me._dataCheck();
4705
4706        var oldStacked = meta._stacked;
4707        meta._stacked = isStacked(meta.vScale, meta);
4708
4709        if (meta.stack !== dataset.stack) {
4710          stackChanged = true;
4711          clearStacks(meta);
4712          meta.stack = dataset.stack;
4713        }
4714
4715        me._resyncElements(resetNewElements);
4716
4717        if (stackChanged || oldStacked !== meta._stacked) {
4718          updateStacks(me, meta._parsed);
4719        }
4720      }
4721    }, {
4722      key: "configure",
4723      value: function configure() {
4724        var me = this;
4725        var config = me.chart.config;
4726        var scopeKeys = config.datasetScopeKeys(me._type);
4727        var scopes = config.getOptionScopes(me.getDataset(), scopeKeys, true);
4728        me.options = config.createResolver(scopes, me.getContext());
4729        me._parsing = me.options.parsing;
4730      }
4731    }, {
4732      key: "parse",
4733      value: function parse(start, count) {
4734        var me = this;
4735        var meta = me._cachedMeta,
4736            data = me._data;
4737        var iScale = meta.iScale,
4738            _stacked = meta._stacked;
4739        var iAxis = iScale.axis;
4740        var sorted = start === 0 && count === data.length ? true : meta._sorted;
4741        var prev = start > 0 && meta._parsed[start - 1];
4742        var i, cur, parsed;
4743
4744        if (me._parsing === false) {
4745          meta._parsed = data;
4746          meta._sorted = true;
4747          parsed = data;
4748        } else {
4749          if (isArray(data[start])) {
4750            parsed = me.parseArrayData(meta, data, start, count);
4751          } else if (isObject(data[start])) {
4752            parsed = me.parseObjectData(meta, data, start, count);
4753          } else {
4754            parsed = me.parsePrimitiveData(meta, data, start, count);
4755          }
4756
4757          var isNotInOrderComparedToPrev = function isNotInOrderComparedToPrev() {
4758            return cur[iAxis] === null || prev && cur[iAxis] < prev[iAxis];
4759          };
4760
4761          for (i = 0; i < count; ++i) {
4762            meta._parsed[i + start] = cur = parsed[i];
4763
4764            if (sorted) {
4765              if (isNotInOrderComparedToPrev()) {
4766                sorted = false;
4767              }
4768
4769              prev = cur;
4770            }
4771          }
4772
4773          meta._sorted = sorted;
4774        }
4775
4776        if (_stacked) {
4777          updateStacks(me, parsed);
4778        }
4779      }
4780    }, {
4781      key: "parsePrimitiveData",
4782      value: function parsePrimitiveData(meta, data, start, count) {
4783        var iScale = meta.iScale,
4784            vScale = meta.vScale;
4785        var iAxis = iScale.axis;
4786        var vAxis = vScale.axis;
4787        var labels = iScale.getLabels();
4788        var singleScale = iScale === vScale;
4789        var parsed = new Array(count);
4790        var i, ilen, index;
4791
4792        for (i = 0, ilen = count; i < ilen; ++i) {
4793          var _parsed$i;
4794
4795          index = i + start;
4796          parsed[i] = (_parsed$i = {}, _defineProperty(_parsed$i, iAxis, singleScale || iScale.parse(labels[index], index)), _defineProperty(_parsed$i, vAxis, vScale.parse(data[index], index)), _parsed$i);
4797        }
4798
4799        return parsed;
4800      }
4801    }, {
4802      key: "parseArrayData",
4803      value: function parseArrayData(meta, data, start, count) {
4804        var xScale = meta.xScale,
4805            yScale = meta.yScale;
4806        var parsed = new Array(count);
4807        var i, ilen, index, item;
4808
4809        for (i = 0, ilen = count; i < ilen; ++i) {
4810          index = i + start;
4811          item = data[index];
4812          parsed[i] = {
4813            x: xScale.parse(item[0], index),
4814            y: yScale.parse(item[1], index)
4815          };
4816        }
4817
4818        return parsed;
4819      }
4820    }, {
4821      key: "parseObjectData",
4822      value: function parseObjectData(meta, data, start, count) {
4823        var xScale = meta.xScale,
4824            yScale = meta.yScale;
4825        var _this$_parsing = this._parsing,
4826            _this$_parsing$xAxisK = _this$_parsing.xAxisKey,
4827            xAxisKey = _this$_parsing$xAxisK === void 0 ? 'x' : _this$_parsing$xAxisK,
4828            _this$_parsing$yAxisK = _this$_parsing.yAxisKey,
4829            yAxisKey = _this$_parsing$yAxisK === void 0 ? 'y' : _this$_parsing$yAxisK;
4830        var parsed = new Array(count);
4831        var i, ilen, index, item;
4832
4833        for (i = 0, ilen = count; i < ilen; ++i) {
4834          index = i + start;
4835          item = data[index];
4836          parsed[i] = {
4837            x: xScale.parse(resolveObjectKey(item, xAxisKey), index),
4838            y: yScale.parse(resolveObjectKey(item, yAxisKey), index)
4839          };
4840        }
4841
4842        return parsed;
4843      }
4844    }, {
4845      key: "getParsed",
4846      value: function getParsed(index) {
4847        return this._cachedMeta._parsed[index];
4848      }
4849    }, {
4850      key: "getDataElement",
4851      value: function getDataElement(index) {
4852        return this._cachedMeta.data[index];
4853      }
4854    }, {
4855      key: "applyStack",
4856      value: function applyStack(scale, parsed, mode) {
4857        var chart = this.chart;
4858        var meta = this._cachedMeta;
4859        var value = parsed[scale.axis];
4860        var stack = {
4861          keys: getSortedDatasetIndices(chart, true),
4862          values: parsed._stacks[scale.axis]
4863        };
4864        return _applyStack(stack, value, meta.index, {
4865          mode: mode
4866        });
4867      }
4868    }, {
4869      key: "updateRangeFromParsed",
4870      value: function updateRangeFromParsed(range, scale, parsed, stack) {
4871        var parsedValue = parsed[scale.axis];
4872        var value = parsedValue === null ? NaN : parsedValue;
4873        var values = stack && parsed._stacks[scale.axis];
4874
4875        if (stack && values) {
4876          stack.values = values;
4877          range.min = Math.min(range.min, value);
4878          range.max = Math.max(range.max, value);
4879          value = _applyStack(stack, parsedValue, this._cachedMeta.index, {
4880            all: true
4881          });
4882        }
4883
4884        range.min = Math.min(range.min, value);
4885        range.max = Math.max(range.max, value);
4886      }
4887    }, {
4888      key: "getMinMax",
4889      value: function getMinMax(scale, canStack) {
4890        var me = this;
4891        var meta = me._cachedMeta;
4892        var _parsed = meta._parsed;
4893        var sorted = meta._sorted && scale === meta.iScale;
4894        var ilen = _parsed.length;
4895
4896        var otherScale = me._getOtherScale(scale);
4897
4898        var stack = canStack && meta._stacked && {
4899          keys: getSortedDatasetIndices(me.chart, true),
4900          values: null
4901        };
4902        var range = {
4903          min: Number.POSITIVE_INFINITY,
4904          max: Number.NEGATIVE_INFINITY
4905        };
4906
4907        var _getUserBounds = getUserBounds(otherScale),
4908            otherMin = _getUserBounds.min,
4909            otherMax = _getUserBounds.max;
4910
4911        var i, value, parsed, otherValue;
4912
4913        function _skip() {
4914          parsed = _parsed[i];
4915          value = parsed[scale.axis];
4916          otherValue = parsed[otherScale.axis];
4917          return !isNumberFinite(value) || otherMin > otherValue || otherMax < otherValue;
4918        }
4919
4920        for (i = 0; i < ilen; ++i) {
4921          if (_skip()) {
4922            continue;
4923          }
4924
4925          me.updateRangeFromParsed(range, scale, parsed, stack);
4926
4927          if (sorted) {
4928            break;
4929          }
4930        }
4931
4932        if (sorted) {
4933          for (i = ilen - 1; i >= 0; --i) {
4934            if (_skip()) {
4935              continue;
4936            }
4937
4938            me.updateRangeFromParsed(range, scale, parsed, stack);
4939            break;
4940          }
4941        }
4942
4943        return range;
4944      }
4945    }, {
4946      key: "getAllParsedValues",
4947      value: function getAllParsedValues(scale) {
4948        var parsed = this._cachedMeta._parsed;
4949        var values = [];
4950        var i, ilen, value;
4951
4952        for (i = 0, ilen = parsed.length; i < ilen; ++i) {
4953          value = parsed[i][scale.axis];
4954
4955          if (isNumberFinite(value)) {
4956            values.push(value);
4957          }
4958        }
4959
4960        return values;
4961      }
4962    }, {
4963      key: "getMaxOverflow",
4964      value: function getMaxOverflow() {
4965        return false;
4966      }
4967    }, {
4968      key: "getLabelAndValue",
4969      value: function getLabelAndValue(index) {
4970        var me = this;
4971        var meta = me._cachedMeta;
4972        var iScale = meta.iScale;
4973        var vScale = meta.vScale;
4974        var parsed = me.getParsed(index);
4975        return {
4976          label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',
4977          value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''
4978        };
4979      }
4980    }, {
4981      key: "_update",
4982      value: function _update(mode) {
4983        var me = this;
4984        var meta = me._cachedMeta;
4985        me.configure();
4986        me._cachedDataOpts = {};
4987        me.update(mode || 'default');
4988        meta._clip = toClip(valueOrDefault(me.options.clip, defaultClip(meta.xScale, meta.yScale, me.getMaxOverflow())));
4989      }
4990    }, {
4991      key: "update",
4992      value: function update(mode) {}
4993    }, {
4994      key: "draw",
4995      value: function draw() {
4996        var me = this;
4997        var ctx = me._ctx;
4998        var chart = me.chart;
4999        var meta = me._cachedMeta;
5000        var elements = meta.data || [];
5001        var area = chart.chartArea;
5002        var active = [];
5003        var start = me._drawStart || 0;
5004        var count = me._drawCount || elements.length - start;
5005        var i;
5006
5007        if (meta.dataset) {
5008          meta.dataset.draw(ctx, area, start, count);
5009        }
5010
5011        for (i = start; i < start + count; ++i) {
5012          var element = elements[i];
5013
5014          if (element.active) {
5015            active.push(element);
5016          } else {
5017            element.draw(ctx, area);
5018          }
5019        }
5020
5021        for (i = 0; i < active.length; ++i) {
5022          active[i].draw(ctx, area);
5023        }
5024      }
5025    }, {
5026      key: "getStyle",
5027      value: function getStyle(index, active) {
5028        var mode = active ? 'active' : 'default';
5029        return index === undefined && this._cachedMeta.dataset ? this.resolveDatasetElementOptions(mode) : this.resolveDataElementOptions(index || 0, mode);
5030      }
5031    }, {
5032      key: "getContext",
5033      value: function getContext(index, active, mode) {
5034        var me = this;
5035        var dataset = me.getDataset();
5036        var context;
5037
5038        if (index >= 0 && index < me._cachedMeta.data.length) {
5039          var element = me._cachedMeta.data[index];
5040          context = element.$context || (element.$context = createDataContext(me.getContext(), index, element));
5041          context.parsed = me.getParsed(index);
5042          context.raw = dataset.data[index];
5043          context.index = context.dataIndex = index;
5044        } else {
5045          context = me.$context || (me.$context = createDatasetContext(me.chart.getContext(), me.index));
5046          context.dataset = dataset;
5047          context.index = context.datasetIndex = me.index;
5048        }
5049
5050        context.active = !!active;
5051        context.mode = mode;
5052        return context;
5053      }
5054    }, {
5055      key: "resolveDatasetElementOptions",
5056      value: function resolveDatasetElementOptions(mode) {
5057        return this._resolveElementOptions(this.datasetElementType.id, mode);
5058      }
5059    }, {
5060      key: "resolveDataElementOptions",
5061      value: function resolveDataElementOptions(index, mode) {
5062        return this._resolveElementOptions(this.dataElementType.id, mode, index);
5063      }
5064    }, {
5065      key: "_resolveElementOptions",
5066      value: function _resolveElementOptions(elementType) {
5067        var mode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
5068        var index = arguments.length > 2 ? arguments[2] : undefined;
5069        var me = this;
5070        var active = mode === 'active';
5071        var cache = me._cachedDataOpts;
5072        var cacheKey = elementType + '-' + mode;
5073        var cached = cache[cacheKey];
5074        var sharing = me.enableOptionSharing && defined(index);
5075
5076        if (cached) {
5077          return cloneIfNotShared(cached, sharing);
5078        }
5079
5080        var config = me.chart.config;
5081        var scopeKeys = config.datasetElementScopeKeys(me._type, elementType);
5082        var prefixes = active ? ["".concat(elementType, "Hover"), 'hover', elementType, ''] : [elementType, ''];
5083        var scopes = config.getOptionScopes(me.getDataset(), scopeKeys);
5084        var names = Object.keys(defaults.elements[elementType]);
5085
5086        var context = function context() {
5087          return me.getContext(index, active);
5088        };
5089
5090        var values = config.resolveNamedOptions(scopes, names, context, prefixes);
5091
5092        if (values.$shared) {
5093          values.$shared = sharing;
5094          cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));
5095        }
5096
5097        return values;
5098      }
5099    }, {
5100      key: "_resolveAnimations",
5101      value: function _resolveAnimations(index, transition, active) {
5102        var me = this;
5103        var chart = me.chart;
5104        var cache = me._cachedDataOpts;
5105        var cacheKey = "animation-".concat(transition);
5106        var cached = cache[cacheKey];
5107
5108        if (cached) {
5109          return cached;
5110        }
5111
5112        var options;
5113
5114        if (chart.options.animation !== false) {
5115          var config = me.chart.config;
5116          var scopeKeys = config.datasetAnimationScopeKeys(me._type, transition);
5117          var scopes = config.getOptionScopes(me.getDataset(), scopeKeys);
5118          options = config.createResolver(scopes, me.getContext(index, active, transition));
5119        }
5120
5121        var animations = new Animations(chart, options && options.animations);
5122
5123        if (options && options._cacheable) {
5124          cache[cacheKey] = Object.freeze(animations);
5125        }
5126
5127        return animations;
5128      }
5129    }, {
5130      key: "getSharedOptions",
5131      value: function getSharedOptions(options) {
5132        if (!options.$shared) {
5133          return;
5134        }
5135
5136        return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));
5137      }
5138    }, {
5139      key: "includeOptions",
5140      value: function includeOptions(mode, sharedOptions) {
5141        return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;
5142      }
5143    }, {
5144      key: "updateElement",
5145      value: function updateElement(element, index, properties, mode) {
5146        if (isDirectUpdateMode(mode)) {
5147          Object.assign(element, properties);
5148        } else {
5149          this._resolveAnimations(index, mode).update(element, properties);
5150        }
5151      }
5152    }, {
5153      key: "updateSharedOptions",
5154      value: function updateSharedOptions(sharedOptions, mode, newOptions) {
5155        if (sharedOptions && !isDirectUpdateMode(mode)) {
5156          this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);
5157        }
5158      }
5159    }, {
5160      key: "_setStyle",
5161      value: function _setStyle(element, index, mode, active) {
5162        element.active = active;
5163        var options = this.getStyle(index, active);
5164
5165        this._resolveAnimations(index, mode, active).update(element, {
5166          options: !active && this.getSharedOptions(options) || options
5167        });
5168      }
5169    }, {
5170      key: "removeHoverStyle",
5171      value: function removeHoverStyle(element, datasetIndex, index) {
5172        this._setStyle(element, index, 'active', false);
5173      }
5174    }, {
5175      key: "setHoverStyle",
5176      value: function setHoverStyle(element, datasetIndex, index) {
5177        this._setStyle(element, index, 'active', true);
5178      }
5179    }, {
5180      key: "_removeDatasetHoverStyle",
5181      value: function _removeDatasetHoverStyle() {
5182        var element = this._cachedMeta.dataset;
5183
5184        if (element) {
5185          this._setStyle(element, undefined, 'active', false);
5186        }
5187      }
5188    }, {
5189      key: "_setDatasetHoverStyle",
5190      value: function _setDatasetHoverStyle() {
5191        var element = this._cachedMeta.dataset;
5192
5193        if (element) {
5194          this._setStyle(element, undefined, 'active', true);
5195        }
5196      }
5197    }, {
5198      key: "_resyncElements",
5199      value: function _resyncElements(resetNewElements) {
5200        var me = this;
5201        var data = me._data;
5202        var elements = me._cachedMeta.data;
5203
5204        var _iterator4 = _createForOfIteratorHelper(me._syncList),
5205            _step4;
5206
5207        try {
5208          for (_iterator4.s();
5208 !(_step4 = _iterator4.n()).done;) {
5209            var _step4$value = _slicedToArray(_step4.value, 3),
5210                method = _step4$value[0],
5211                arg1 = _step4$value[1],
5212                arg2 = _step4$value[2];
5213
5214            me[method](arg1, arg2);
5215          }
5216        } catch (err) {
5217          _iterator4.e(err);
5218        } finally {
5219          _iterator4.f();
5220        }
5221
5222        me._syncList = [];
5223        var numMeta = elements.length;
5224        var numData = data.length;
5225        var count = Math.min(numData, numMeta);
5226
5227        if (count) {
5228          me.parse(0, count);
5229        }
5230
5231        if (numData > numMeta) {
5232          me._insertElements(numMeta, numData - numMeta, resetNewElements);
5233        } else if (numData < numMeta) {
5234          me._removeElements(numData, numMeta - numData);
5235        }
5236      }
5237    }, {
5238      key: "_insertElements",
5239      value: function _insertElements(start, count) {
5240        var resetNewElements = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
5241        var me = this;
5242        var meta = me._cachedMeta;
5243        var data = meta.data;
5244        var end = start + count;
5245        var i;
5246
5247        var move = function move(arr) {
5248          arr.length += count;
5249
5250          for (i = arr.length - 1; i >= end; i--) {
5251            arr[i] = arr[i - count];
5252          }
5253        };
5254
5255        move(data);
5256
5257        for (i = start; i < end; ++i) {
5258          data[i] = new me.dataElementType();
5259        }
5260
5261        if (me._parsing) {
5262          move(meta._parsed);
5263        }
5264
5265        me.parse(start, count);
5266
5267        if (resetNewElements) {
5268          me.updateElements(data, start, count, 'reset');
5269        }
5270      }
5271    }, {
5272      key: "updateElements",
5273      value: function updateElements(element, start, count, mode) {}
5274    }, {
5275      key: "_removeElements",
5276      value: function _removeElements(start, count) {
5277        var me = this;
5278        var meta = me._cachedMeta;
5279
5280        if (me._parsing) {
5281          var removed = meta._parsed.splice(start, count);
5282
5283          if (meta._stacked) {
5284            clearStacks(meta, removed);
5285          }
5286        }
5287
5288        meta.data.splice(start, count);
5289      }
5290    }, {
5291      key: "_onDataPush",
5292      value: function _onDataPush() {
5293        var count = arguments.length;
5294
5295        this._syncList.push(['_insertElements', this.getDataset().data.length - count, count]);
5296      }
5297    }, {
5298      key: "_onDataPop",
5299      value: function _onDataPop() {
5300        this._syncList.push(['_removeElements', this._cachedMeta.data.length - 1, 1]);
5301      }
5302    }, {
5303      key: "_onDataShift",
5304      value: function _onDataShift() {
5305        this._syncList.push(['_removeElements', 0, 1]);
5306      }
5307    }, {
5308      key: "_onDataSplice",
5309      value: function _onDataSplice(start, count) {
5310        this._syncList.push(['_removeElements', start, count]);
5311
5312        this._syncList.push(['_insertElements', start, arguments.length - 2]);
5313      }
5314    }, {
5315      key: "_onDataUnshift",
5316      value: function _onDataUnshift() {
5317        this._syncList.push(['_insertElements', 0, arguments.length]);
5318      }
5319    }]);
5320
5321    return DatasetController;
5322  }();
5323
5324  DatasetController.defaults = {};
5325  DatasetController.prototype.datasetElementType = null;
5326  DatasetController.prototype.dataElementType = null;
5327
5328  function getAllScaleValues(scale) {
5329    if (!scale._cache.$bar) {
5330      var metas = scale.getMatchingVisibleMetas('bar');
5331      var values = [];
5332
5333      for (var i = 0, ilen = metas.length; i < ilen; i++) {
5334        values = values.concat(metas[i].controller.getAllParsedValues(scale));
5335      }
5336
5337      scale._cache.$bar = _arrayUnique(values.sort(function (a, b) {
5338        return a - b;
5339      }));
5340    }
5341
5342    return scale._cache.$bar;
5343  }
5344
5345  function computeMinSampleSize(scale) {
5346    var values = getAllScaleValues(scale);
5347    var min = scale._length;
5348    var i, ilen, curr, prev;
5349
5350    var updateMinAndPrev = function updateMinAndPrev() {
5351      if (curr === 32767 || curr === -32768) {
5352        return;
5353      }
5354
5355      if (defined(prev)) {
5356        min = Math.min(min, Math.abs(curr - prev) || min);
5357      }
5358
5359      prev = curr;
5360    };
5361
5362    for (i = 0, ilen = values.length; i < ilen; ++i) {
5363      curr = scale.getPixelForValue(values[i]);
5364      updateMinAndPrev();
5365    }
5366
5367    prev = undefined;
5368
5369    for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {
5370      curr = scale.getPixelForTick(i);
5371      updateMinAndPrev();
5372    }
5373
5374    return min;
5375  }
5376
5377  function computeFitCategoryTraits(index, ruler, options, stackCount) {
5378    var thickness = options.barThickness;
5379    var size, ratio;
5380
5381    if (isNullOrUndef(thickness)) {
5382      size = ruler.min * options.categoryPercentage;
5383      ratio = options.barPercentage;
5384    } else {
5385      size = thickness * stackCount;
5386      ratio = 1;
5387    }
5388
5389    return {
5390      chunk: size / stackCount,
5391      ratio: ratio,
5392      start: ruler.pixels[index] - size / 2
5393    };
5394  }
5395
5396  function computeFlexCategoryTraits(index, ruler, options, stackCount) {
5397    var pixels = ruler.pixels;
5398    var curr = pixels[index];
5399    var prev = index > 0 ? pixels[index - 1] : null;
5400    var next = index < pixels.length - 1 ? pixels[index + 1] : null;
5401    var percent = options.categoryPercentage;
5402
5403    if (prev === null) {
5404      prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
5405    }
5406
5407    if (next === null) {
5408      next = curr + curr - prev;
5409    }
5410
5411    var start = curr - (curr - Math.min(prev, next)) / 2 * percent;
5412    var size = Math.abs(next - prev) / 2 * percent;
5413    return {
5414      chunk: size / stackCount,
5415      ratio: options.barPercentage,
5416      start: start
5417    };
5418  }
5419
5420  function parseFloatBar(entry, item, vScale, i) {
5421    var startValue = vScale.parse(entry[0], i);
5422    var endValue = vScale.parse(entry[1], i);
5423    var min = Math.min(startValue, endValue);
5424    var max = Math.max(startValue, endValue);
5425    var barStart = min;
5426    var barEnd = max;
5427
5428    if (Math.abs(min) > Math.abs(max)) {
5429      barStart = max;
5430      barEnd = min;
5431    }
5432
5433    item[vScale.axis] = barEnd;
5434    item._custom = {
5435      barStart: barStart,
5436      barEnd: barEnd,
5437      start: startValue,
5438      end: endValue,
5439      min: min,
5440      max: max
5441    };
5442  }
5443
5444  function parseValue(entry, item, vScale, i) {
5445    if (isArray(entry)) {
5446      parseFloatBar(entry, item, vScale, i);
5447    } else {
5448      item[vScale.axis] = vScale.parse(entry, i);
5449    }
5450
5451    return item;
5452  }
5453
5454  function parseArrayOrPrimitive(meta, data, start, count) {
5455    var iScale = meta.iScale;
5456    var vScale = meta.vScale;
5457    var labels = iScale.getLabels();
5458    var singleScale = iScale === vScale;
5459    var parsed = [];
5460    var i, ilen, item, entry;
5461
5462    for (i = start, ilen = start + count; i < ilen; ++i) {
5463      entry = data[i];
5464      item = {};
5465      item[iScale.axis] = singleScale || iScale.parse(labels[i], i);
5466      parsed.push(parseValue(entry, item, vScale, i));
5467    }
5468
5469    return parsed;
5470  }
5471
5472  function isFloatBar(custom) {
5473    return custom && custom.barStart !== undefined && custom.barEnd !== undefined;
5474  }
5475
5476  var BarController = /*#__PURE__*/function (_DatasetController) {
5477    _inherits(BarController, _DatasetController);
5478
5479    var _super = _createSuper(BarController);
5480
5481    function BarController() {
5482      _classCallCheck(this, BarController);
5483
5484      return _super.apply(this, arguments);
5485    }
5486
5487    _createClass(BarController, [{
5488      key: "parsePrimitiveData",
5489      value: function parsePrimitiveData(meta, data, start, count) {
5490        return parseArrayOrPrimitive(meta, data, start, count);
5491      }
5492    }, {
5493      key: "parseArrayData",
5494      value: function parseArrayData(meta, data, start, count) {
5495        return parseArrayOrPrimitive(meta, data, start, count);
5496      }
5497    }, {
5498      key: "parseObjectData",
5499      value: function parseObjectData(meta, data, start, count) {
5500        var iScale = meta.iScale,
5501            vScale = meta.vScale;
5502        var _this$_parsing2 = this._parsing,
5503            _this$_parsing2$xAxis = _this$_parsing2.xAxisKey,
5504            xAxisKey = _this$_parsing2$xAxis === void 0 ? 'x' : _this$_parsing2$xAxis,
5505            _this$_parsing2$yAxis = _this$_parsing2.yAxisKey,
5506            yAxisKey = _this$_parsing2$yAxis === void 0 ? 'y' : _this$_parsing2$yAxis;
5507        var iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;
5508        var vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;
5509        var parsed = [];
5510        var i, ilen, item, obj;
5511
5512        for (i = start, ilen = start + count; i < ilen; ++i) {
5513          obj = data[i];
5514          item = {};
5515          item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);
5516          parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));
5517        }
5518
5519        return parsed;
5520      }
5521    }, {
5522      key: "updateRangeFromParsed",
5523      value: function updateRangeFromParsed(range, scale, parsed, stack) {
5524        _get(_getPrototypeOf(BarController.prototype), "updateRangeFromParsed", this).call(this, range, scale, parsed, stack);
5525
5526        var custom = parsed._custom;
5527
5528        if (custom && scale === this._cachedMeta.vScale) {
5529          range.min = Math.min(range.min, custom.min);
5530          range.max = Math.max(range.max, custom.max);
5531        }
5532      }
5533    }, {
5534      key: "getMaxOverflow",
5535      value: function getMaxOverflow() {
5536        return 0;
5537      }
5538    }, {
5539      key: "getLabelAndValue",
5540      value: function getLabelAndValue(index) {
5541        var me = this;
5542        var meta = me._cachedMeta;
5543        var iScale = meta.iScale,
5544            vScale = meta.vScale;
5545        var parsed = me.getParsed(index);
5546        var custom = parsed._custom;
5547        var value = isFloatBar(custom) ? '[' + custom.start + ', ' + custom.end + ']' : '' + vScale.getLabelForValue(parsed[vScale.axis]);
5548        return {
5549          label: '' + iScale.getLabelForValue(parsed[iScale.axis]),
5550          value: value
5551        };
5552      }
5553    }, {
5554      key: "initialize",
5555      value: function initialize() {
5556        var me = this;
5557        me.enableOptionSharing = true;
5558
5559        _get(_getPrototypeOf(BarController.prototype), "initialize", this).call(this);
5560
5561        var meta = me._cachedMeta;
5562        meta.stack = me.getDataset().stack;
5563      }
5564    }, {
5565      key: "update",
5566      value: function update(mode) {
5567        var me = this;
5568        var meta = me._cachedMeta;
5569        me.updateElements(meta.data, 0, meta.data.length, mode);
5570      }
5571    }, {
5572      key: "updateElements",
5573      value: function updateElements(bars, start, count, mode) {
5574        var me = this;
5575        var reset = mode === 'reset';
5576        var vScale = me._cachedMeta.vScale;
5577        var base = vScale.getBasePixel();
5578        var horizontal = vScale.isHorizontal();
5579
5580        var ruler = me._getRuler();
5581
5582        var firstOpts = me.resolveDataElementOptions(start, mode);
5583        var sharedOptions = me.getSharedOptions(firstOpts);
5584        var includeOptions = me.includeOptions(mode, sharedOptions);
5585        me.updateSharedOptions(sharedOptions, mode, firstOpts);
5586
5587        for (var i = start; i < start + count; i++) {
5588          var parsed = me.getParsed(i);
5589          var vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {
5590            base: base,
5591            head: base
5592          } : me._calculateBarValuePixels(i);
5593
5594          var ipixels = me._calculateBarIndexPixels(i, ruler);
5595
5596          var stack = (parsed._stacks || {})[vScale.axis];
5597          var properties = {
5598            horizontal: horizontal,
5599            base: vpixels.base,
5600            enableBorderRadius: !stack || isFloatBar(parsed._custom) || me.index === stack._top || me.index === stack._bottom,
5601            x: horizontal ? vpixels.head : ipixels.center,
5602            y: horizontal ? ipixels.center : vpixels.head,
5603            height: horizontal ? ipixels.size : Math.abs(vpixels.size),
5604            width: horizontal ? Math.abs(vpixels.size) : ipixels.size
5605          };
5606
5607          if (includeOptions) {
5608            properties.options = sharedOptions || me.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);
5609          }
5610
5611          me.updateElement(bars[i], i, properties, mode);
5612        }
5613      }
5614    }, {
5615      key: "_getStacks",
5616      value: function _getStacks(last, dataIndex) {
5617        var me = this;
5618        var meta = me._cachedMeta;
5619        var iScale = meta.iScale;
5620        var metasets = iScale.getMatchingVisibleMetas(me._type);
5621        var stacked = iScale.options.stacked;
5622        var ilen = metasets.length;
5623        var stacks = [];
5624        var i, item;
5625
5626        for (i = 0; i < ilen; ++i) {
5627          item = metasets[i];
5628
5629          if (!item.controller.options.grouped) {
5630            continue;
5631          }
5632
5633          if (typeof dataIndex !== 'undefined') {
5634            var val = item.controller.getParsed(dataIndex)[item.controller._cachedMeta.vScale.axis];
5635
5636            if (isNullOrUndef(val) || isNaN(val)) {
5637              continue;
5638            }
5639          }
5640
5641          if (stacked === false || stacks.indexOf(item.stack) === -1 || stacked === undefined && item.stack === undefined) {
5642            stacks.push(item.stack);
5643          }
5644
5645          if (item.index === last) {
5646            break;
5647          }
5648        }
5649
5650        if (!stacks.length) {
5651          stacks.push(undefined);
5652        }
5653
5654        return stacks;
5655      }
5656    }, {
5657      key: "_getStackCount",
5658      value: function _getStackCount(index) {
5659        return this._getStacks(undefined, index).length;
5660      }
5661    }, {
5662      key: "_getStackIndex",
5663      value: function _getStackIndex(datasetIndex, name, dataIndex) {
5664        var stacks = this._getStacks(datasetIndex, dataIndex);
5665
5666        var index = name !== undefined ? stacks.indexOf(name) : -1;
5667        return index === -1 ? stacks.length - 1 : index;
5668      }
5669    }, {
5670      key: "_getRuler",
5671      value: function _getRuler() {
5672        var me = this;
5673        var opts = me.options;
5674        var meta = me._cachedMeta;
5675        var iScale = meta.iScale;
5676        var pixels = [];
5677        var i, ilen;
5678
5679        for (i = 0, ilen = meta.data.length; i < ilen; ++i) {
5680          pixels.push(iScale.getPixelForValue(me.getParsed(i)[iScale.axis], i));
5681        }
5682
5683        var barThickness = opts.barThickness;
5684        var min = barThickness || computeMinSampleSize(iScale);
5685        return {
5686          min: min,
5687          pixels: pixels,
5688          start: iScale._startPixel,
5689          end: iScale._endPixel,
5690          stackCount: me._getStackCount(),
5691          scale: iScale,
5692          grouped: opts.grouped,
5693          ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage
5694        };
5695      }
5696    }, {
5697      key: "_calculateBarValuePixels",
5698      value: function _calculateBarValuePixels(index) {
5699        var me = this;
5700        var _me$_cachedMeta = me._cachedMeta,
5701            vScale = _me$_cachedMeta.vScale,
5702            _stacked = _me$_cachedMeta._stacked;
5703        var _me$options = me.options,
5704            baseValue = _me$options.base,
5705            minBarLength = _me$options.minBarLength;
5706        var parsed = me.getParsed(index);
5707        var custom = parsed._custom;
5708        var floating = isFloatBar(custom);
5709        var value = parsed[vScale.axis];
5710        var start = 0;
5711        var length = _stacked ? me.applyStack(vScale, parsed, _stacked) : value;
5712        var head, size;
5713
5714        if (length !== value) {
5715          start = length - value;
5716          length = value;
5717        }
5718
5719        if (floating) {
5720          value = custom.barStart;
5721          length = custom.barEnd - custom.barStart;
5722
5723          if (value !== 0 && sign(value) !== sign(custom.barEnd)) {
5724            start = 0;
5725          }
5726
5727          start += value;
5728        }
5729
5730        var startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;
5731        var base = vScale.getPixelForValue(startValue);
5732
5733        if (this.chart.getDataVisibility(index)) {
5734          head = vScale.getPixelForValue(start + length);
5735        } else {
5736          head = base;
5737        }
5738
5739        size = head - base;
5740
5741        if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
5742          size = size < 0 ? -minBarLength : minBarLength;
5743
5744          if (value === 0) {
5745            base -= size / 2;
5746          }
5747
5748          head = base + size;
5749        }
5750
5751        var actualBase = baseValue || 0;
5752
5753        if (base === vScale.getPixelForValue(actualBase)) {
5754          var halfGrid = vScale.getLineWidthForValue(actualBase) / 2;
5755
5756          if (size > 0) {
5757            base += halfGrid;
5758            size -= halfGrid;
5759          } else if (size < 0) {
5760            base -= halfGrid;
5761            size += halfGrid;
5762          }
5763        }
5764
5765        return {
5766          size: size,
5767          base: base,
5768          head: head,
5769          center: head + size / 2
5770        };
5771      }
5772    }, {
5773      key: "_calculateBarIndexPixels",
5774      value: function _calculateBarIndexPixels(index, ruler) {
5775        var me = this;
5776        var scale = ruler.scale;
5777        var options = me.options;
5778        var skipNull = options.skipNull;
5779        var maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);
5780        var center, size;
5781
5782        if (ruler.grouped) {
5783          var stackCount = skipNull ? me._getStackCount(index) : ruler.stackCount;
5784          var range = options.barThickness === 'flex' ? computeFlexCategoryTraits(index, ruler, options, stackCount) : computeFitCategoryTraits(index, ruler, options, stackCount);
5785
5786          var stackIndex = me._getStackIndex(me.index, me._cachedMeta.stack, skipNull ? index : undefined);
5787
5788          center = range.start + range.chunk * stackIndex + range.chunk / 2;
5789          size = Math.min(maxBarThickness, range.chunk * range.ratio);
5790        } else {
5791          center = scale.getPixelForValue(me.getParsed(index)[scale.axis], index);
5792          size = Math.min(maxBarThickness, ruler.min * ruler.ratio);
5793        }
5794
5795        return {
5796          base: center - size / 2,
5797          head: center + size / 2,
5798          center: center,
5799          size: size
5800        };
5801      }
5802    }, {
5803      key: "draw",
5804      value: function draw() {
5805        var me = this;
5806        var meta = me._cachedMeta;
5807        var vScale = meta.vScale;
5808        var rects = meta.data;
5809        var ilen = rects.length;
5810        var i = 0;
5811
5812        for (; i < ilen; ++i) {
5813          if (me.getParsed(i)[vScale.axis] !== null) {
5814            rects[i].draw(me._ctx);
5815          }
5816        }
5817      }
5818    }]);
5819
5820    return BarController;
5821  }(DatasetController);
5822
5823  BarController.id = 'bar';
5824  BarController.defaults = {
5825    datasetElementType: false,
5826    dataElementType: 'bar',
5827    categoryPercentage: 0.8,
5828    barPercentage: 0.9,
5829    grouped: true,
5830    animations: {
5831      numbers: {
5832        type: 'number',
5833        properties: ['x', 'y', 'base', 'width', 'height']
5834      }
5835    }
5836  };
5837  BarController.overrides = {
5838    interaction: {
5839      mode: 'index'
5840    },
5841    scales: {
5842      _index_: {
5843        type: 'category',
5844        offset: true,
5845        grid: {
5846          offset: true
5847        }
5848      },
5849      _value_: {
5850        type: 'linear',
5851        beginAtZero: true
5852      }
5853    }
5854  };
5855
5856  var BubbleController = /*#__PURE__*/function (_DatasetController2) {
5857    _inherits(BubbleController, _DatasetController2);
5858
5859    var _super2 = _createSuper(BubbleController);
5860
5861    function BubbleController() {
5862      _classCallCheck(this, BubbleController);
5863
5864      return _super2.apply(this, arguments);
5865    }
5866
5867    _createClass(BubbleController, [{
5868      key: "initialize",
5869      value: function initialize() {
5870        this.enableOptionSharing = true;
5871
5872        _get(_getPrototypeOf(BubbleController.prototype), "initialize", this).call(this);
5873      }
5874    }, {
5875      key: "parseObjectData",
5876      value: function parseObjectData(meta, data, start, count) {
5877        var xScale = meta.xScale,
5878            yScale = meta.yScale;
5879        var _this$_parsing3 = this._parsing,
5880            _this$_parsing3$xAxis = _this$_parsing3.xAxisKey,
5881            xAxisKey = _this$_parsing3$xAxis === void 0 ? 'x' : _this$_parsing3$xAxis,
5882            _this$_parsing3$yAxis = _this$_parsing3.yAxisKey,
5883            yAxisKey = _this$_parsing3$yAxis === void 0 ? 'y' : _this$_parsing3$yAxis;
5884        var parsed = [];
5885        var i, ilen, item;
5886
5887        for (i = start, ilen = start + count; i < ilen; ++i) {
5888          item = data[i];
5889          parsed.push({
5890            x: xScale.parse(resolveObjectKey(item, xAxisKey), i),
5891            y: yScale.parse(resolveObjectKey(item, yAxisKey), i),
5892            _custom: item && item.r && +item.r
5893          });
5894        }
5895
5896        return parsed;
5897      }
5898    }, {
5899      key: "getMaxOverflow",
5900      value: function getMaxOverflow() {
5901        var _this$_cachedMeta = this._cachedMeta,
5902            data = _this$_cachedMeta.data,
5903            _parsed = _this$_cachedMeta._parsed;
5904        var max = 0;
5905
5906        for (var i = data.length - 1; i >= 0; --i) {
5907          max = Math.max(max, data[i].size() / 2, _parsed[i]._custom);
5908        }
5909
5910        return max > 0 && max;
5911      }
5912    }, {
5913      key: "getLabelAndValue",
5914      value: function getLabelAndValue(index) {
5915        var me = this;
5916        var meta = me._cachedMeta;
5917        var xScale = meta.xScale,
5918            yScale = meta.yScale;
5919        var parsed = me.getParsed(index);
5920        var x = xScale.getLabelForValue(parsed.x);
5921        var y = yScale.getLabelForValue(parsed.y);
5922        var r = parsed._custom;
5923        return {
5924          label: meta.label,
5925          value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'
5926        };
5927      }
5928    }, {
5929      key: "update",
5930      value: function update(mode) {
5931        var me = this;
5932        var points = me._cachedMeta.data;
5933        me.updateElements(points, 0, points.length, mode);
5934      }
5935    }, {
5936      key: "updateElements",
5937      value: function updateElements(points, start, count, mode) {
5938        var me = this;
5939        var reset = mode === 'reset';
5940        var _me$_cachedMeta2 = me._cachedMeta,
5941            iScale = _me$_cachedMeta2.iScale,
5942            vScale = _me$_cachedMeta2.vScale;
5943        var firstOpts = me.resolveDataElementOptions(start, mode);
5944        var sharedOptions = me.getSharedOptions(firstOpts);
5945        var includeOptions = me.includeOptions(mode, sharedOptions);
5946        var iAxis = iScale.axis;
5947        var vAxis = vScale.axis;
5948
5949        for (var i = start; i < start + count; i++) {
5950          var point = points[i];
5951          var parsed = !reset && me.getParsed(i);
5952          var properties = {};
5953          var iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);
5954          var vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);
5955          properties.skip = isNaN(iPixel) || isNaN(vPixel);
5956
5957          if (includeOptions) {
5958            properties.options = me.resolveDataElementOptions(i, point.active ? 'active' : mode);
5959
5960            if (reset) {
5961              properties.options.radius = 0;
5962            }
5963          }
5964
5965          me.updateElement(point, i, properties, mode);
5966        }
5967
5968        me.updateSharedOptions(sharedOptions, mode, firstOpts);
5969      }
5970    }, {
5971      key: "resolveDataElementOptions",
5972      value: function resolveDataElementOptions(index, mode) {
5973        var parsed = this.getParsed(index);
5974
5975        var values = _get(_getPrototypeOf(BubbleController.prototype), "resolveDataElementOptions", this).call(this, index, mode);
5976
5977        if (values.$shared) {
5978          values = Object.assign({}, values, {
5979            $shared: false
5980          });
5981        }
5982
5983        var radius = values.radius;
5984
5985        if (mode !== 'active') {
5986          values.radius = 0;
5987        }
5988
5989        values.radius += valueOrDefault(parsed && parsed._custom, radius);
5990        return values;
5991      }
5992    }]);
5993
5994    return BubbleController;
5995  }(DatasetController);
5996
5997  BubbleController.id = 'bubble';
5998  BubbleController.defaults = {
5999    datasetElementType: false,
6000    dataElementType: 'point',
6001    animations: {
6002      numbers: {
6003        type: 'number',
6004        properties: ['x', 'y', 'borderWidth', 'radius']
6005      }
6006    }
6007  };
6008  BubbleController.overrides = {
6009    scales: {
6010      x: {
6011        type: 'linear'
6012      },
6013      y: {
6014        type: 'linear'
6015      }
6016    },
6017    plugins: {
6018      tooltip: {
6019        callbacks: {
6020          title: function title() {
6021            return '';
6022          }
6023        }
6024      }
6025    }
6026  };
6027
6028  function getRatioAndOffset(rotation, circumference, cutout) {
6029    var ratioX = 1;
6030    var ratioY = 1;
6031    var offsetX = 0;
6032    var offsetY = 0;
6033
6034    if (circumference < TAU) {
6035      var startAngle = rotation;
6036      var endAngle = startAngle + circumference;
6037      var startX = Math.cos(startAngle);
6038      var startY = Math.sin(startAngle);
6039      var endX = Math.cos(endAngle);
6040      var endY = Math.sin(endAngle);
6041
6042      var calcMax = function calcMax(angle, a, b) {
6043        return _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);
6044      };
6045
6046      var calcMin = function calcMin(angle, a, b) {
6047        return _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);
6048      };
6049
6050      var maxX = calcMax(0, startX, endX);
6051      var maxY = calcMax(HALF_PI, startY, endY);
6052      var minX = calcMin(PI, startX, endX);
6053      var minY = calcMin(PI + HALF_PI, startY, endY);
6054      ratioX = (maxX - minX) / 2;
6055      ratioY = (maxY - minY) / 2;
6056      offsetX = -(maxX + minX) / 2;
6057      offsetY = -(maxY + minY) / 2;
6058    }
6059
6060    return {
6061      ratioX: ratioX,
6062      ratioY: ratioY,
6063      offsetX: offsetX,
6064      offsetY: offsetY
6065    };
6066  }
6067
6068  var DoughnutController = /*#__PURE__*/function (_DatasetController3) {
6069    _inherits(DoughnutController, _DatasetController3);
6070
6071    var _super3 = _createSuper(DoughnutController);
6072
6073    function DoughnutController(chart, datasetIndex) {
6074      var _this;
6075
6076      _classCallCheck(this, DoughnutController);
6077
6078      _this = _super3.call(this, chart, datasetIndex);
6079      _this.enableOptionSharing = true;
6080      _this.innerRadius = undefined;
6081      _this.outerRadius = undefined;
6082      _this.offsetX = undefined;
6083      _this.offsetY = undefined;
6084      return _this;
6085    }
6086
6087    _createClass(DoughnutController, [{
6088      key: "linkScales",
6089      value: function linkScales() {}
6090    }, {
6091      key: "parse",
6092      value: function parse(start, count) {
6093        var data = this.getDataset().data;
6094        var meta = this._cachedMeta;
6095        var i, ilen;
6096
6097        for (i = start, ilen = start + count; i < ilen; ++i) {
6098          meta._parsed[i] = +data[i];
6099        }
6100      }
6101    }, {
6102      key: "_getRotation",
6103      value: function _getRotation() {
6104        return toRadians(this.options.rotation - 90);
6105      }
6106    }, {
6107      key: "_getCircumference",
6108      value: function _getCircumference() {
6109        return toRadians(this.options.circumference);
6110      }
6111    }, {
6112      key: "_getRotationExtents",
6113      value: function _getRotationExtents() {
6114        var min = TAU;
6115        var max = -TAU;
6116        var me = this;
6117
6118        for (var i = 0; i < me.chart.data.datasets.length; ++i) {
6119          if (me.chart.isDatasetVisible(i)) {
6120            var controller = me.chart.getDatasetMeta(i).controller;
6121
6122            var rotation = controller._getRotation();
6123
6124            var circumference = controller._getCircumference();
6125
6126            min = Math.min(min, rotation);
6127            max = Math.max(max, rotation + circumference);
6128          }
6129        }
6130
6131        return {
6132          rotation: min,
6133          circumference: max - min
6134        };
6135      }
6136    }, {
6137      key: "update",
6138      value: function update(mode) {
6139        var me = this;
6140        var chart = me.chart;
6141        var chartArea = chart.chartArea;
6142        var meta = me._cachedMeta;
6143        var arcs = meta.data;
6144        var spacing = me.getMaxBorderWidth() + me.getMaxOffset(arcs) + me.options.spacing;
6145        var maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);
6146        var cutout = Math.min(toPercentage(me.options.cutout, maxSize), 1);
6147
6148        var chartWeight = me._getRingWeight(me.index);
6149
6150        var _me$_getRotationExten = me._getRotationExtents(),
6151            circumference = _me$_getRotationExten.circumference,
6152            rotation = _me$_getRotationExten.rotation;
6153
6154        var _getRatioAndOffset = getRatioAndOffset(rotation, circumference, cutout),
6155            ratioX = _getRatioAndOffset.ratioX,
6156            ratioY = _getRatioAndOffset.ratioY,
6157            offsetX = _getRatioAndOffset.offsetX,
6158            offsetY = _getRatioAndOffset.offsetY;
6159
6160        var maxWidth = (chartArea.width - spacing) / ratioX;
6161        var maxHeight = (chartArea.height - spacing) / ratioY;
6162        var maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
6163        var outerRadius = toDimension(me.options.radius, maxRadius);
6164        var innerRadius = Math.max(outerRadius * cutout, 0);
6165
6166        var radiusLength = (outerRadius - innerRadius) / me._getVisibleDatasetWeightTotal();
6167
6168        me.offsetX = offsetX * outerRadius;
6169        me.offsetY = offsetY * outerRadius;
6170        meta.total = me.calculateTotal();
6171        me.outerRadius = outerRadius - radiusLength * me._getRingWeightOffset(me.index);
6172        me.innerRadius = Math.max(me.outerRadius - radiusLength * chartWeight, 0);
6173        me.updateElements(arcs, 0, arcs.length, mode);
6174      }
6175    }, {
6176      key: "_circumference",
6177      value: function _circumference(i, reset) {
6178        var me = this;
6179        var opts = me.options;
6180        var meta = me._cachedMeta;
6181
6182        var circumference = me._getCircumference();
6183
6184        if (reset && opts.animation.animateRotate || !this.chart.getDataVisibility(i) || meta._parsed[i] === null) {
6185          return 0;
6186        }
6187
6188        return me.calculateCircumference(meta._parsed[i] * circumference / TAU);
6189      }
6190    }, {
6191      key: "updateElements",
6192      value: function updateElements(arcs, start, count, mode) {
6193        var me = this;
6194        var reset = mode === 'reset';
6195        var chart = me.chart;
6196        var chartArea = chart.chartArea;
6197        var opts = chart.options;
6198        var animationOpts = opts.animation;
6199        var centerX = (chartArea.left + chartArea.right) / 2;
6200        var centerY = (chartArea.top + chartArea.bottom) / 2;
6201        var animateScale = reset && animationOpts.animateScale;
6202        var innerRadius = animateScale ? 0 : me.innerRadius;
6203        var outerRadius = animateScale ? 0 : me.outerRadius;
6204        var firstOpts = me.resolveDataElementOptions(start, mode);
6205        var sharedOptions = me.getSharedOptions(firstOpts);
6206        var includeOptions = me.includeOptions(mode, sharedOptions);
6207
6208        var startAngle = me._getRotation();
6209
6210        var i;
6211
6212        for (i = 0; i < start; ++i) {
6213          startAngle += me._circumference(i, reset);
6214        }
6215
6216        for (i = start; i < start + count; ++i) {
6217          var circumference = me._circumference(i, reset);
6218
6219          var arc = arcs[i];
6220          var properties = {
6221            x: centerX + me.offsetX,
6222            y: centerY + me.offsetY,
6223            startAngle: startAngle,
6224            endAngle: startAngle + circumference,
6225            circumference: circumference,
6226            outerRadius: outerRadius,
6227            innerRadius: innerRadius
6228          };
6229
6230          if (includeOptions) {
6231            properties.options = sharedOptions || me.resolveDataElementOptions(i, ar
6231c.active ? 'active' : mode);
6232          }
6233
6234          startAngle += circumference;
6235          me.updateElement(arc, i, properties, mode);
6236        }
6237
6238        me.updateSharedOptions(sharedOptions, mode, firstOpts);
6239      }
6240    }, {
6241      key: "calculateTotal",
6242      value: function calculateTotal() {
6243        var meta = this._cachedMeta;
6244        var metaData = meta.data;
6245        var total = 0;
6246        var i;
6247
6248        for (i = 0; i < metaData.length; i++) {
6249          var value = meta._parsed[i];
6250
6251          if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i)) {
6252            total += Math.abs(value);
6253          }
6254        }
6255
6256        return total;
6257      }
6258    }, {
6259      key: "calculateCircumference",
6260      value: function calculateCircumference(value) {
6261        var total = this._cachedMeta.total;
6262
6263        if (total > 0 && !isNaN(value)) {
6264          return TAU * (Math.abs(value) / total);
6265        }
6266
6267        return 0;
6268      }
6269    }, {
6270      key: "getLabelAndValue",
6271      value: function getLabelAndValue(index) {
6272        var me = this;
6273        var meta = me._cachedMeta;
6274        var chart = me.chart;
6275        var labels = chart.data.labels || [];
6276        var value = formatNumber(meta._parsed[index], chart.options.locale);
6277        return {
6278          label: labels[index] || '',
6279          value: value
6280        };
6281      }
6282    }, {
6283      key: "getMaxBorderWidth",
6284      value: function getMaxBorderWidth(arcs) {
6285        var me = this;
6286        var max = 0;
6287        var chart = me.chart;
6288        var i, ilen, meta, controller, options;
6289
6290        if (!arcs) {
6291          for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
6292            if (chart.isDatasetVisible(i)) {
6293              meta = chart.getDatasetMeta(i);
6294              arcs = meta.data;
6295              controller = meta.controller;
6296
6297              if (controller !== me) {
6298                controller.configure();
6299              }
6300
6301              break;
6302            }
6303          }
6304        }
6305
6306        if (!arcs) {
6307          return 0;
6308        }
6309
6310        for (i = 0, ilen = arcs.length; i < ilen; ++i) {
6311          options = controller.resolveDataElementOptions(i);
6312
6313          if (options.borderAlign !== 'inner') {
6314            max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);
6315          }
6316        }
6317
6318        return max;
6319      }
6320    }, {
6321      key: "getMaxOffset",
6322      value: function getMaxOffset(arcs) {
6323        var max = 0;
6324
6325        for (var i = 0, ilen = arcs.length; i < ilen; ++i) {
6326          var options = this.resolveDataElementOptions(i);
6327          max = Math.max(max, options.offset || 0, options.hoverOffset || 0);
6328        }
6329
6330        return max;
6331      }
6332    }, {
6333      key: "_getRingWeightOffset",
6334      value: function _getRingWeightOffset(datasetIndex) {
6335        var ringWeightOffset = 0;
6336
6337        for (var i = 0; i < datasetIndex; ++i) {
6338          if (this.chart.isDatasetVisible(i)) {
6339            ringWeightOffset += this._getRingWeight(i);
6340          }
6341        }
6342
6343        return ringWeightOffset;
6344      }
6345    }, {
6346      key: "_getRingWeight",
6347      value: function _getRingWeight(datasetIndex) {
6348        return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);
6349      }
6350    }, {
6351      key: "_getVisibleDatasetWeightTotal",
6352      value: function _getVisibleDatasetWeightTotal() {
6353        return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;
6354      }
6355    }]);
6356
6357    return DoughnutController;
6358  }(DatasetController);
6359
6360  DoughnutController.id = 'doughnut';
6361  DoughnutController.defaults = {
6362    datasetElementType: false,
6363    dataElementType: 'arc',
6364    animation: {
6365      animateRotate: true,
6366      animateScale: false
6367    },
6368    animations: {
6369      numbers: {
6370        type: 'number',
6371        properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing']
6372      }
6373    },
6374    cutout: '50%',
6375    rotation: 0,
6376    circumference: 360,
6377    radius: '100%',
6378    spacing: 0,
6379    indexAxis: 'r'
6380  };
6381  DoughnutController.descriptors = {
6382    _scriptable: function _scriptable(name) {
6383      return name !== 'spacing';
6384    },
6385    _indexable: function _indexable(name) {
6386      return name !== 'spacing';
6387    }
6388  };
6389  DoughnutController.overrides = {
6390    aspectRatio: 1,
6391    plugins: {
6392      legend: {
6393        labels: {
6394          generateLabels: function generateLabels(chart) {
6395            var data = chart.data;
6396
6397            if (data.labels.length && data.datasets.length) {
6398              var pointStyle = chart.legend.options.labels.pointStyle;
6399              return data.labels.map(function (label, i) {
6400                var meta = chart.getDatasetMeta(0);
6401                var style = meta.controller.getStyle(i);
6402                return {
6403                  text: label,
6404                  fillStyle: style.backgroundColor,
6405                  strokeStyle: style.borderColor,
6406                  lineWidth: style.borderWidth,
6407                  pointStyle: pointStyle,
6408                  hidden: !chart.getDataVisibility(i),
6409                  index: i
6410                };
6411              });
6412            }
6413
6414            return [];
6415          }
6416        },
6417        onClick: function onClick(e, legendItem, legend) {
6418          legend.chart.toggleDataVisibility(legendItem.index);
6419          legend.chart.update();
6420        }
6421      },
6422      tooltip: {
6423        callbacks: {
6424          title: function title() {
6425            return '';
6426          },
6427          label: function label(tooltipItem) {
6428            var dataLabel = tooltipItem.label;
6429            var value = ': ' + tooltipItem.formattedValue;
6430
6431            if (isArray(dataLabel)) {
6432              dataLabel = dataLabel.slice();
6433              dataLabel[0] += value;
6434            } else {
6435              dataLabel += value;
6436            }
6437
6438            return dataLabel;
6439          }
6440        }
6441      }
6442    }
6443  };
6444
6445  var LineController = /*#__PURE__*/function (_DatasetController4) {
6446    _inherits(LineController, _DatasetController4);
6447
6448    var _super4 = _createSuper(LineController);
6449
6450    function LineController() {
6451      _classCallCheck(this, LineController);
6452
6453      return _super4.apply(this, arguments);
6454    }
6455
6456    _createClass(LineController, [{
6457      key: "initialize",
6458      value: function initialize() {
6459        this.enableOptionSharing = true;
6460
6461        _get(_getPrototypeOf(LineController.prototype), "initialize", this).call(this);
6462      }
6463    }, {
6464      key: "update",
6465      value: function update(mode) {
6466        var me = this;
6467        var meta = me._cachedMeta;
6468        var line = meta.dataset,
6469            _meta$data = meta.data,
6470            points = _meta$data === void 0 ? [] : _meta$data,
6471            _dataset = meta._dataset;
6472        var animationsDisabled = me.chart._animationsDisabled;
6473
6474        var _getStartAndCountOfVi = getStartAndCountOfVisiblePoints(meta, points, animationsDisabled),
6475            start = _getStartAndCountOfVi.start,
6476            count = _getStartAndCountOfVi.count;
6477
6478        me._drawStart = start;
6479        me._drawCount = count;
6480
6481        if (scaleRangesChanged(meta)) {
6482          start = 0;
6483          count = points.length;
6484        }
6485
6486        line._decimated = !!_dataset._decimated;
6487        line.points = points;
6488        var options = me.resolveDatasetElementOptions(mode);
6489
6490        if (!me.options.showLine) {
6491          options.borderWidth = 0;
6492        }
6493
6494        options.segment = me.options.segment;
6495        me.updateElement(line, undefined, {
6496          animated: !animationsDisabled,
6497          options: options
6498        }, mode);
6499        me.updateElements(points, start, count, mode);
6500      }
6501    }, {
6502      key: "updateElements",
6503      value: function updateElements(points, start, count, mode) {
6504        var me = this;
6505        var reset = mode === 'reset';
6506        var _me$_cachedMeta3 = me._cachedMeta,
6507            iScale = _me$_cachedMeta3.iScale,
6508            vScale = _me$_cachedMeta3.vScale,
6509            _stacked = _me$_cachedMeta3._stacked;
6510        var firstOpts = me.resolveDataElementOptions(start, mode);
6511        var sharedOptions = me.getSharedOptions(firstOpts);
6512        var includeOptions = me.includeOptions(mode, sharedOptions);
6513        var iAxis = iScale.axis;
6514        var vAxis = vScale.axis;
6515        var spanGaps = me.options.spanGaps;
6516        var maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
6517        var directUpdate = me.chart._animationsDisabled || reset || mode === 'none';
6518        var prevParsed = start > 0 && me.getParsed(start - 1);
6519
6520        for (var i = start; i < start + count; ++i) {
6521          var point = points[i];
6522          var parsed = me.getParsed(i);
6523          var properties = directUpdate ? point : {};
6524          var nullData = isNullOrUndef(parsed[vAxis]);
6525          var iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
6526          var vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? me.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
6527          properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
6528          properties.stop = i > 0 && parsed[iAxis] - prevParsed[iAxis] > maxGapLength;
6529          properties.parsed = parsed;
6530
6531          if (includeOptions) {
6532            properties.options = sharedOptions || me.resolveDataElementOptions(i, point.active ? 'active' : mode);
6533          }
6534
6535          if (!directUpdate) {
6536            me.updateElement(point, i, properties, mode);
6537          }
6538
6539          prevParsed = parsed;
6540        }
6541
6542        me.updateSharedOptions(sharedOptions, mode, firstOpts);
6543      }
6544    }, {
6545      key: "getMaxOverflow",
6546      value: function getMaxOverflow() {
6547        var me = this;
6548        var meta = me._cachedMeta;
6549        var dataset = meta.dataset;
6550        var border = dataset.options && dataset.options.borderWidth || 0;
6551        var data = meta.data || [];
6552
6553        if (!data.length) {
6554          return border;
6555        }
6556
6557        var firstPoint = data[0].size(me.resolveDataElementOptions(0));
6558        var lastPoint = data[data.length - 1].size(me.resolveDataElementOptions(data.length - 1));
6559        return Math.max(border, firstPoint, lastPoint) / 2;
6560      }
6561    }, {
6562      key: "draw",
6563      value: function draw() {
6564        var meta = this._cachedMeta;
6565        meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);
6566
6567        _get(_getPrototypeOf(LineController.prototype), "draw", this).call(this);
6568      }
6569    }]);
6570
6571    return LineController;
6572  }(DatasetController);
6573
6574  LineController.id = 'line';
6575  LineController.defaults = {
6576    datasetElementType: 'line',
6577    dataElementType: 'point',
6578    showLine: true,
6579    spanGaps: false
6580  };
6581  LineController.overrides = {
6582    scales: {
6583      _index_: {
6584        type: 'category'
6585      },
6586      _value_: {
6587        type: 'linear'
6588      }
6589    }
6590  };
6591
6592  function getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) {
6593    var pointCount = points.length;
6594    var start = 0;
6595    var count = pointCount;
6596
6597    if (meta._sorted) {
6598      var iScale = meta.iScale,
6599          _parsed = meta._parsed;
6600      var axis = iScale.axis;
6601
6602      var _iScale$getUserBounds = iScale.getUserBounds(),
6603          min = _iScale$getUserBounds.min,
6604          max = _iScale$getUserBounds.max,
6605          minDefined = _iScale$getUserBounds.minDefined,
6606          maxDefined = _iScale$getUserBounds.maxDefined;
6607
6608      if (minDefined) {
6609        start = _limitValue(Math.min(_lookupByKey(_parsed, iScale.axis, min).lo, animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo), 0, pointCount - 1);
6610      }
6611
6612      if (maxDefined) {
6613        count = _limitValue(Math.max(_lookupByKey(_parsed, iScale.axis, max).hi + 1, animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max)).hi + 1), start, pointCount) - start;
6614      } else {
6615        count = pointCount - start;
6616      }
6617    }
6618
6619    return {
6620      start: start,
6621      count: count
6622    };
6623  }
6624
6625  function scaleRangesChanged(meta) {
6626    var xScale = meta.xScale,
6627        yScale = meta.yScale,
6628        _scaleRanges = meta._scaleRanges;
6629    var newRanges = {
6630      xmin: xScale.min,
6631      xmax: xScale.max,
6632      ymin: yScale.min,
6633      ymax: yScale.max
6634    };
6635
6636    if (!_scaleRanges) {
6637      meta._scaleRanges = newRanges;
6638      return true;
6639    }
6640
6641    var changed = _scaleRanges.xmin !== xScale.min || _scaleRanges.xmax !== xScale.max || _scaleRanges.ymin !== yScale.min || _scaleRanges.ymax !== yScale.max;
6642    Object.assign(_scaleRanges, newRanges);
6643    return changed;
6644  }
6645
6646  var PolarAreaController = /*#__PURE__*/function (_DatasetController5) {
6647    _inherits(PolarAreaController, _DatasetController5);
6648
6649    var _super5 = _createSuper(PolarAreaController);
6650
6651    function PolarAreaController(chart, datasetIndex) {
6652      var _this2;
6653
6654      _classCallCheck(this, PolarAreaController);
6655
6656      _this2 = _super5.call(this, chart, datasetIndex);
6657      _this2.innerRadius = undefined;
6658      _this2.outerRadius = undefined;
6659      return _this2;
6660    }
6661
6662    _createClass(PolarAreaController, [{
6663      key: "getLabelAndValue",
6664      value: function getLabelAndValue(index) {
6665        var me = this;
6666        var meta = me._cachedMeta;
6667        var chart = me.chart;
6668        var labels = chart.data.labels || [];
6669        var value = formatNumber(meta._parsed[index].r, chart.options.locale);
6670        return {
6671          label: labels[index] || '',
6672          value: value
6673        };
6674      }
6675    }, {
6676      key: "update",
6677      value: function update(mode) {
6678        var arcs = this._cachedMeta.data;
6679
6680        this._updateRadius();
6681
6682        this.updateElements(arcs, 0, arcs.length, mode);
6683      }
6684    }, {
6685      key: "_updateRadius",
6686      value: function _updateRadius() {
6687        var me = this;
6688        var chart = me.chart;
6689        var chartArea = chart.chartArea;
6690        var opts = chart.options;
6691        var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
6692        var outerRadius = Math.max(minSize / 2, 0);
6693        var innerRadius = Math.max(opts.cutoutPercentage ? outerRadius / 100 * opts.cutoutPercentage : 1, 0);
6694        var radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();
6695        me.outerRadius = outerRadius - radiusLength * me.index;
6696        me.innerRadius = me.outerRadius - radiusLength;
6697      }
6698    }, {
6699      key: "updateElements",
6700      value: function updateElements(arcs, start, count, mode) {
6701        var me = this;
6702        var reset = mode === 'reset';
6703        var chart = me.chart;
6704        var dataset = me.getDataset();
6705        var opts = chart.options;
6706        var animationOpts = opts.animation;
6707        var scale = me._cachedMeta.rScale;
6708        var centerX = scale.xCenter;
6709        var centerY = scale.yCenter;
6710        var datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;
6711        var angle = datasetStartAngle;
6712        var i;
6713        var defaultAngle = 360 / me.countVisibleElements();
6714
6715        for (i = 0; i < start; ++i) {
6716          angle += me._computeAngle(i, mode, defaultAngle);
6717        }
6718
6719        for (i = start; i < start + count; i++) {
6720          var arc = arcs[i];
6721          var startAngle = angle;
6722
6723          var endAngle = angle + me._computeAngle(i, mode, defaultAngle);
6724
6725          var outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(dataset.data[i]) : 0;
6726          angle = endAngle;
6727
6728          if (reset) {
6729            if (animationOpts.animateScale) {
6730              outerRadius = 0;
6731            }
6732
6733            if (animationOpts.animateRotate) {
6734              startAngle = endAngle = datasetStartAngle;
6735            }
6736          }
6737
6738          var properties = {
6739            x: centerX,
6740            y: centerY,
6741            innerRadius: 0,
6742            outerRadius: outerRadius,
6743            startAngle: startAngle,
6744            endAngle: endAngle,
6745            options: me.resolveDataElementOptions(i, arc.active ? 'active' : mode)
6746          };
6747          me.updateElement(arc, i, properties, mode);
6748        }
6749      }
6750    }, {
6751      key: "countVisibleElements",
6752      value: function countVisibleElements() {
6753        var _this3 = this;
6754
6755        var dataset = this.getDataset();
6756        var meta = this._cachedMeta;
6757        var count = 0;
6758        meta.data.forEach(function (element, index) {
6759          if (!isNaN(dataset.data[index]) && _this3.chart.getDataVisibility(index)) {
6760            count++;
6761          }
6762        });
6763        return count;
6764      }
6765    }, {
6766      key: "_computeAngle",
6767      value: function _computeAngle(index, mode, defaultAngle) {
6768        return this.chart.getDataVisibility(index) ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle) : 0;
6769      }
6770    }]);
6771
6772    return PolarAreaController;
6773  }(DatasetController);
6774
6775  PolarAreaController.id = 'polarArea';
6776  PolarAreaController.defaults = {
6777    dataElementType: 'arc',
6778    animation: {
6779      animateRotate: true,
6780      animateScale: true
6781    },
6782    animations: {
6783      numbers: {
6784        type: 'number',
6785        properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius']
6786      }
6787    },
6788    indexAxis: 'r',
6789    startAngle: 0
6790  };
6791  PolarAreaController.overrides = {
6792    aspectRatio: 1,
6793    plugins: {
6794      legend: {
6795        labels: {
6796          generateLabels: function generateLabels(chart) {
6797            var data = chart.data;
6798
6799            if (data.labels.length && data.datasets.length) {
6800              var pointStyle = chart.legend.options.labels.pointStyle;
6801              return data.labels.map(function (label, i) {
6802                var meta = chart.getDatasetMeta(0);
6803                var style = meta.controller.getStyle(i);
6804                return {
6805                  text: label,
6806                  fillStyle: style.backgroundColor,
6807                  strokeStyle: style.borderColor,
6808                  lineWidth: style.borderWidth,
6809                  pointStyle: pointStyle,
6810                  hidden: !chart.getDataVisibility(i),
6811                  index: i
6812                };
6813              });
6814            }
6815
6816            return [];
6817          }
6818        },
6819        onClick: function onClick(e, legendItem, legend) {
6820          legend.chart.toggleDataVisibility(legendItem.index);
6821          legend.chart.update();
6822        }
6823      },
6824      tooltip: {
6825        callbacks: {
6826          title: function title() {
6827            return '';
6828          },
6829          label: function label(context) {
6830            return context.chart.data.labels[context.dataIndex] + ': ' + context.formattedValue;
6831          }
6832        }
6833      }
6834    },
6835    scales: {
6836      r: {
6837        type: 'radialLinear',
6838        angleLines: {
6839          display: false
6840        },
6841        beginAtZero: true,
6842        grid: {
6843          circular: true
6844        },
6845        pointLabels: {
6846          display: false
6847        },
6848        startAngle: 0
6849      }
6850    }
6851  };
6852
6853  var PieController = /*#__PURE__*/function (_DoughnutController) {
6854    _inherits(PieController, _DoughnutController);
6855
6856    var _super6 = _createSuper(PieController);
6857
6858    function PieController() {
6859      _classCallCheck(this, PieController);
6860
6861      return _super6.apply(this, arguments);
6862    }
6863
6864    return PieController;
6865  }(DoughnutController);
6866
6867  PieController.id = 'pie';
6868  PieController.defaults = {
6869    cutout: 0,
6870    rotation: 0,
6871    circumference: 360,
6872    radius: '100%'
6873  };
6874
6875  var RadarController = /*#__PURE__*/function (_DatasetController6) {
6876    _inherits(RadarController, _DatasetController6);
6877
6878    var _super7 = _createSuper(RadarController);
6879
6880    function RadarController() {
6881      _classCallCheck(this, RadarController);
6882
6883      return _super7.apply(this, arguments);
6884    }
6885
6886    _createClass(RadarController, [{
6887      key: "getLabelAndValue",
6888      value: function getLabelAndValue(index) {
6889        var me = this;
6890        var vScale = me._cachedMeta.vScale;
6891        var parsed = me.getParsed(index);
6892        return {
6893          label: vScale.getLabels()[index],
6894          value: '' + vScale.getLabelForValue(parsed[vScale.axis])
6895        };
6896      }
6897    }, {
6898      key: "update",
6899      value: function update(mode) {
6900        var me = this;
6901        var meta = me._cachedMeta;
6902        var line = meta.dataset;
6903        var points = meta.data || [];
6904        var labels = meta.iScale.getLabels();
6905        line.points = points;
6906
6907        if (mode !== 'resize') {
6908          var options = me.resolveDatasetElementOptions(mode);
6909
6910          if (!me.options.showLine) {
6911            options.borderWidth = 0;
6912          }
6913
6914          var properties = {
6915            _loop: true,
6916            _fullLoop: labels.length === points.length,
6917            options: options
6918          };
6919          me.updateElement(line, undefined, properties, mode);
6920        }
6921
6922        me.updateElements(points, 0, points.length, mode);
6923      }
6924    }, {
6925      key: "updateElements",
6926      value: function updateElements(points, start, count, mode) {
6927        var me = this;
6928        var dataset = me.getDataset();
6929        var scale = me._cachedMeta.rScale;
6930        var reset = mode === 'reset';
6931
6932        for (var i = start; i < start + count; i++) {
6933          var point = points[i];
6934          var options = me.resolveDataElementOptions(i, point.active ? 'active' : mode);
6935          var pointPosition = scale.getPointPositionForValue(i, dataset.data[i]);
6936          var x = reset ? scale.xCenter : pointPosition.x;
6937          var y = reset ? scale.yCenter : pointPosition.y;
6938          var properties = {
6939            x: x,
6940            y: y,
6941            angle: pointPosition.angle,
6942            skip: isNaN(x) || isNaN(y),
6943            options: options
6944          };
6945          me.updateElement(point, i, properties, mode);
6946        }
6947      }
6948    }]);
6949
6950    return RadarController;
6951  }(DatasetController);
6952
6953  RadarController.id = 'radar';
6954  RadarController.defaults = {
6955    datasetElementType: 'line',
6956    dataElementType: 'point',
6957    indexAxis: 'r',
6958    showLine: true,
6959    elements: {
6960      line: {
6961        fill: 'start'
6962      }
6963    }
6964  };
6965  RadarController.overrides = {
6966    aspectRatio: 1,
6967    scales: {
6968      r: {
6969        type: 'radialLinear'
6970      }
6971    }
6972  };
6973
6974  var ScatterController = /*#__PURE__*/function (_LineController) {
6975    _inherits(ScatterController, _LineController);
6976
6977    var _super8 = _createSuper(ScatterController);
6978
6979    function ScatterController() {
6980      _classCallCheck(this, ScatterController);
6981
6982      return _super8.apply(this, arguments);
6983    }
6984
6985    return ScatterController;
6986  }(LineController);
6987
6988  ScatterController.id = 'scatter';
6989  ScatterController.defaults = {
6990    showLine: false,
6991    fill: false
6992  };
6993  ScatterController.overrides = {
6994    interaction: {
6995      mode: 'point'
6996    },
6997    plugins: {
6998      tooltip: {
6999        callbacks: {
7000          title: function title() {
7001            return '';
7002          },
7003          label: function label(item) {
7004            return '(' + item.label + ', ' + item.formattedValue + ')';
7005          }
7006        }
7007      }
7008    },
7009    scales: {
7010      x: {
7011        type: 'linear'
7012      },
7013      y: {
7014        type: 'linear'
7015      }
7016    }
7017  };
7018  var controllers = /*#__PURE__*/Object.freeze({
7019    __proto__: null,
7020    BarController: BarController,
7021    BubbleController: BubbleController,
7022    DoughnutController: DoughnutController,
7023    LineController: LineController,
7024    PolarAreaController: PolarAreaController,
7025    PieController: PieController,
7026    RadarController: RadarController,
7027    ScatterController: ScatterController
7028  });
7029
7030  function abstract() {
7031    throw new Error('This method is not implemented: Check that a complete date adapter is provided.');
7032  }
7033
7034  var DateAdapter = /*#__PURE__*/function () {
7035    function DateAdapter(options) {
7036      _classCallCheck(this, DateAdapter);
7037
7038      this.options = options || {};
7039    }
7040
7041    _createClass(DateAdapter, [{
7042      key: "formats",
7043      value: function formats() {
7044        return abstract();
7045      }
7046    }, {
7047      key: "parse",
7048      value: function parse(value, format) {
7049        return abstract();
7050      }
7051    }, {
7052      key: "format",
7053      value: function format(timestamp, _format) {
7054        return abstract();
7055      }
7056    }, {
7057      key: "add",
7058      value: function add(timestamp, amount, unit) {
7059        return abstract();
7060      }
7061    }, {
7062      key: "diff",
7063      value: function diff(a, b, unit) {
7064        return abstract();
7065      }
7066    }, {
7067      key: "startOf",
7068      value: function startOf(timestamp, unit, weekday) {
7069        return abstract();
7070      }
7071    }, {
7072      key: "endOf",
7073      value: function endOf(timestamp, unit) {
7074        return abstract();
7075      }
7076    }]);
7077
7078    return DateAdapter;
7079  }();
7080
7081  DateAdapter.override = function (members) {
7082    Object.assign(DateAdapter.prototype, members);
7083  };
7084
7085  var adapters = {
7086    _date: DateAdapter
7087  };
7088
7089  function getRelativePosition(e, chart) {
7090    if ('native' in e) {
7091      return {
7092        x: e.x,
7093        y: e.y
7094      };
7095    }
7096
7097    return getRelativePosition$1(e, chart);
7098  }
7099
7100  function evaluateAllVisibleItems(chart, handler) {
7101    var metasets = chart.getSortedVisibleDatasetMetas();
7102    var index, data, element;
7103
7104    for (var i = 0, ilen = metasets.length; i < ilen; ++i) {
7105      var _metasets$i = metasets[i];
7106      index = _metasets$i.index;
7107      data = _metasets$i.data;
7108
7109      for (var j = 0, jlen = data.length; j < jlen; ++j) {
7110        element = data[j];
7111
7112        if (!element.skip) {
7113          handler(element, index, j);
7114        }
7115      }
7116    }
7117  }
7118
7119  function binarySearch(metaset, axis, value, intersect) {
7120    var controller = metaset.controller,
7121        data = metaset.data,
7122        _sorted = metaset._sorted;
7123    var iScale = controller._cachedMeta.iScale;
7124
7125    if (iScale && axis === iScale.axis && _sorted && data.length) {
7126      var lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;
7127
7128      if (!intersect) {
7129        return lookupMethod(data, axis, value);
7130      } else if (controller._sharedOptions) {
7131        var el = data[0];
7132        var range = typeof el.getRange === 'function' && el.getRange(axis);
7133
7134        if (range) {
7135          var start = lookupMethod(data, axis, value - range);
7136          var end = lookupMethod(data, axis, value + range);
7137          return {
7138            lo: start.lo,
7139            hi: end.hi
7140          };
7141        }
7142      }
7143    }
7144
7145    return {
7146      lo: 0,
7147      hi: data.length - 1
7148    };
7149  }
7150
7151  function optimizedEvaluateItems(chart, axis, position, handler, intersect) {
7152    var metasets = chart.getSortedVisibleDatasetMetas();
7153    var value = position[axis];
7154
7155    for (var i = 0, ilen = metasets.length; i < ilen; ++i) {
7156      var _metasets$i2 = metasets[i],
7157          index = _metasets$i2.index,
7158          data = _metasets$i2.data;
7159
7160      var _binarySearch = binarySearch(metasets[i], axis, value, intersect),
7161          lo = _binarySearch.lo,
7162          hi = _binarySearch.hi;
7163
7164      for (var j = lo; j <= hi; ++j) {
7165        var element = data[j];
7166
7167        if (!element.skip) {
7168          handler(element, index, j);
7169        }
7170      }
7171    }
7172  }
7173
7174  function getDistanceMetricForAxis(axis) {
7175    var useX = axis.indexOf('x') !== -1;
7176    var useY = axis.indexOf('y') !== -1;
7177    return function (pt1, pt2) {
7178      var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
7179      var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
7180      return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
7181    };
7182  }
7183
7184  function getIntersectItems(chart, position, axis, useFinalPosition) {
7185    var items = [];
7186
7187    if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) {
7188      return items;
7189    }
7190
7191    var evaluationFunc = function evaluationFunc(element, datasetIndex, index) {
7192      if (element.inRange(position.x, position.y, useFinalPosition)) {
7193        items.push({
7194          element: element,
7195          datasetIndex: datasetIndex,
7196          index: index
7197        });
7198      }
7199    };
7200
7201    optimizedEvaluateItems(chart, axis, position, evaluationFunc, true);
7202    return items;
7203  }
7204
7205  function getNearestItems(chart, position, axis, intersect, useFinalPosition) {
7206    var distanceMetric = getDistanceMetricForAxis(axis);
7207    var minDistance = Number.POSITIVE_INFINITY;
7208    var items = [];
7209
7210    if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) {
7211      return items;
7212    }
7213
7214    var evaluationFunc = function evaluationFunc(element, datasetIndex, index) {
7215      if (intersect && !element.inRange(position.x, position.y, useFinalPosition)) {
7216        return;
7217      }
7218
7219      var center = element.getCenterPoint(useFinalPosition);
7220
7221      if (!_isPointInArea(center, chart.chartArea, chart._minPadding)) {
7222        return;
7223      }
7224
7225      var distance = distanceMetric(position, center);
7226
7227      if (distance < minDistance) {
7228        items = [{
7229          element: element,
7230          datasetIndex: datasetIndex,
7231          index: index
7232        }];
7233        minDistance = distance;
7234      } else if (distance === minDistance) {
7235        items.push({
7236          element: element,
7237          datasetIndex: datasetIndex,
7238          index: index
7239        });
7240      }
7241    };
7242
7243    optimizedEvaluateItems(chart, axis, position, evaluationFunc);
7244    return items;
7245  }
7246
7247  function getAxisItems(chart, e, options, useFinalPosition) {
7248    var position = getRelativePosition(e, chart);
7249    var items = [];
7250    var axis = options.axis;
7251    var rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';
7252    var intersectsItem = false;
7253    evaluateAllVisibleItems(chart, function (element, datasetIndex, index) {
7254      if (element[rangeMethod](position[axis], useFinalPosition)) {
7255        items.push({
7256          element: element,
7257          datasetIndex: datasetIndex,
7258          index: index
7259        });
7260      }
7261
7262      if (element.inRange(position.x, position.y, useFinalPosition)) {
7263        intersectsItem = true;
7264      }
7265    });
7266
7267    if (options.intersect && !intersectsItem) {
7268      return [];
7269    }
7270
7271    return items;
7272  }
7273
7274  var Interaction = {
7275    modes: {
7276      index: function index(chart, e, options, useFinalPosition) {
7277        var position = getRelativePosition(e, chart);
7278        var axis = options.axis || 'x';
7279        var items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition) : getNearestItems(chart, position, axis, false, useFinalPosition);
7280        var elements = [];
7281
7282        if (!items.length) {
7283          return [];
7284        }
7285
7286        chart.getSortedVisibleDatasetMetas().forEach(function (meta) {
7287          var index = items[0].index;
7288          var element = meta.data[index];
7289
7290          if (element && !element.skip) {
7291            elements.push({
7292              element: element,
7293              datasetIndex: meta.index,
7294              index: index
7295            });
7296          }
7297        });
7298        return elements;
7299      },
7300      dataset: function dataset(chart, e, options, useFinalPosition) {
7301        var position = getRelativePosition(e, chart);
7302        var axis = options.axis || 'xy';
7303        var items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition) : getNearestItems(chart, position, axis, false, useFinalPosition);
7304
7305        if (items.length > 0) {
7306          var datasetIndex = items[0].datasetIndex;
7307          var data = chart.getDatasetMeta(datasetIndex).data;
7308          items = [];
7309
7310          for (var i = 0; i < data.length; ++i) {
7311            items.push({
7312              element: data[i],
7313              datasetIndex: datasetIndex,
7314              index: i
7315            });
7316          }
7317        }
7318
7319        return items;
7320      },
7321      point: function point(chart, e, options, useFinalPosition) {
7322        var position = getRelativePosition(e, chart);
7323        var axis = options.axis || 'xy';
7324        return getIntersectItems(chart, position, axis, useFinalPosition);
7325      },
7326      nearest: function nearest(chart, e, options, useFinalPosition) {
7327        var position = getRelativePosition(e, chart);
7328        var axis = options.axis || 'xy';
7329        return getNearestItems(chart, position, axis, options.intersect, useFinalPosition);
7330      },
7331      x: function x(chart, e, options, useFinalPosition) {
7332        options.axis = 'x';
7333        return getAxisItems(chart, e, options, useFinalPosition);
7334      },
7335      y: function y(chart, e, options, useFinalPosition) {
7336        options.axis = 'y';
7337        return getAxisItems(chart, e, options, useFinalPosition);
7338      }
7339    }
7340  };
7341  var STATIC_POSITIONS = ['left', 'top', 'right', 'bottom'];
7342
7343  function filterByPosition(array, position) {
7344    return array.filter(function (v) {
7345      return v.pos === position;
7346    });
7347  }
7348
7349  function filterDynamicPositionByAxis(array, axis) {
7350    return array.filter(function (v) {
7351      return STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis;
7352    });
7353  }
7354
7355  function sortByWeight(array, reverse) {
7356    return array.sort(function (a, b) {
7357      var v0 = reverse ? b : a;
7358      var v1 = reverse ? a : b;
7359      return v0.weight === v1.weight ? v0.index - v1.index : v0.weight - v1.weight;
7360    });
7361  }
7362
7363  function wrapBoxes(boxes) {
7364    var layoutBoxes = [];
7365    var i, ilen, box;
7366
7367    for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
7368      box = boxes[i];
7369      layoutBoxes.push({
7370        index: i,
7371        box: box,
7372        pos: box.position,
7373        horizontal: box.isHorizontal(),
7374        weight: box.weight
7375      });
7376    }
7377
7378    return layoutBoxes;
7379  }
7380
7381  function setLayoutDims(layouts, params) {
7382    var i, ilen, layout;
7383
7384    for (i = 0, ilen = layouts.length; i < ilen; ++i) {
7385      layout = layouts[i];
7386
7387      if (layout.horizontal) {
7388        layout.width = layout.box.fullSize && params.availableWidth;
7389        layout.height = params.hBoxMaxHeight;
7390      } else {
7391        layout.width = params.vBoxMaxWidth;
7392        layout.height = layout.box.fullSize && params.availableHeight;
7393      }
7394    }
7395  }
7396
7397  function buildLayoutBoxes(boxes) {
7398    var layoutBoxes = wrapBoxes(boxes);
7399    var fullSize = sortByWeight(layoutBoxes.filter(function (wrap) {
7400      return wrap.box.fullSize;
7401    }), true);
7402    var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
7403    var right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
7404    var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
7405    var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
7406    var centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');
7407    var centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');
7408    return {
7409      fullSize: fullSize,
7410      leftAndTop: left.concat(top),
7411      rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),
7412      chartArea: filterByPosition(layoutBoxes, 'chartArea'),
7413      vertical: left.concat(right).concat(centerVertical),
7414      horizontal: top.concat(bottom).concat(centerHorizontal)
7415    };
7416  }
7417
7418  function getCombinedMax(maxPadding, chartArea, a, b) {
7419    return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
7420  }
7421
7422  function updateMaxPadding(maxPadding, boxPadding) {
7423    maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
7424    maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
7425    maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
7426    maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
7427  }
7428
7429  function updateDims(chartArea, params, layout) {
7430    var box = layout.box;
7431    var maxPadding = chartArea.maxPadding;
7432
7433    if (!isObject(layout.pos)) {
7434      if (layout.size) {
7435        chartArea[layout.pos] -= layout.size;
7436      }
7437
7438      layout.size = layout.horizontal ? box.height : box.width;
7439      chartArea[layout.pos] += layout.size;
7440    }
7441
7442    if (box.getPadding) {
7443      updateMaxPadding(maxPadding, box.getPadding());
7444    }
7445
7446    var newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));
7447    var newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));
7448    var widthChanged = newWidth !== chartArea.w;
7449    var heightChanged = newHeight !== chartArea.h;
7450    chartArea.w = newWidth;
7451    chartArea.h = newHeight;
7452    return layout.horizontal ? {
7453      same: widthChanged,
7454      other: heightChanged
7455    } : {
7456      same: heightChanged,
7457      other: widthChanged
7458    };
7459  }
7460
7461  function handleMaxPadding(chartArea) {
7462    var maxPadding = chartArea.maxPadding;
7463
7464    function updatePos(pos) {
7465      var change = Math.max(maxPadding[pos] - chartArea[pos], 0);
7466      chartArea[pos] += change;
7467      return change;
7468    }
7469
7470    chartArea.y += updatePos('top');
7471    chartArea.x += updatePos('left');
7472    updatePos('right');
7473    updatePos('bottom');
7474  }
7475
7476  function getMargins(horizontal, chartArea) {
7477    var maxPadding = chartArea.maxPadding;
7478
7479    function marginForPositions(positions) {
7480      var margin = {
7481        left: 0,
7482        top: 0,
7483        right: 0,
7484        bottom: 0
7485      };
7486      positions.forEach(function (pos) {
7487        margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
7488      });
7489      return margin;
7490    }
7491
7492    return horizontal ? marginForPositions(['left', 'right']) : marginForPositions(['top', 'bottom']);
7493  }
7494
7495  function fitBoxes(boxes, chartArea, params) {
7496    var refitBoxes = [];
7497    var i, ilen, layout, box, refit, changed;
7498
7499    for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) {
7500      layout = boxes[i];
7501      box = layout.box;
7502      box.update(layout.width || chartArea.w, layout.height || chartArea.h, getMargins(layout.horizontal, chartArea));
7503
7504      var _updateDims = updateDims(chartArea, params, layout),
7505          same = _updateDims.same,
7506          other = _updateDims.other;
7507
7508      refit |= same && refitBoxes.length;
7509      changed = changed || other;
7510
7511      if (!box.fullSize) {
7512        refitBoxes.push(layout);
7513      }
7514    }
7515
7516    return refit && fitBoxes(refitBoxes, chartArea, params) || changed;
7517  }
7518
7519  function placeBoxes(boxes, chartArea, params) {
7520    var userPadding = params.padding;
7521    var x = chartArea.x;
7522    var y = chartArea.y;
7523    var i, ilen, layout, box;
7524
7525    for (i = 0, ilen = boxes.length; i < ilen; ++i) {
7526      layout = boxes[i];
7527      box = layout.box;
7528
7529      if (layout.horizontal) {
7530        box.left = box.fullSize ? userPadding.left : chartArea.left;
7531        box.right = box.fullSize ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;
7532        box.top = y;
7533        box.bottom = y + box.height;
7534        box.width = box.right - box.left;
7535        y = box.bottom;
7536      } else {
7537        box.left = x;
7538        box.right = x + box.width;
7539        box.top = box.fullSize ? userPadding.top : chartArea.top;
7540        box.bottom = box.fullSize ? params.outerHeight - userPadding.bottom : chartArea.top + chartArea.h;
7541        box.height = box.bottom - box.top;
7542        x = box.right;
7543      }
7544    }
7545
7546    chartArea.x = x;
7547    chartArea.y = y;
7548  }
7549
7550  defaults.set('layout', {
7551    padding: {
7552      top: 0,
7553      right: 0,
7554      bottom: 0,
7555      left: 0
7556    }
7557  });
7558  var layouts = {
7559    addBox: function addBox(chart, item) {
7560      if (!chart.boxes) {
7561        chart.boxes = [];
7562      }
7563
7564      item.fullSize = item.fullSize || false;
7565      item.position = item.position || 'top';
7566      item.weight = item.weight || 0;
7567
7568      item._layers = item._layers || function () {
7569        return [{
7570          z: 0,
7571          draw: function draw(chartArea) {
7572            item.draw(chartArea);
7573          }
7574        }];
7575      };
7576
7577      chart.boxes.push(item);
7578    },
7579    removeBox: function removeBox(chart, layoutItem) {
7580      var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
7581
7582      if (index !== -1) {
7583        chart.boxes.splice(index, 1);
7584      }
7585    },
7586    configure: function configure(chart, item, options) {
7587      item.fullSize = options.fullSize;
7588      item.position = options.position;
7589      item.weight = options.weight;
7590    },
7591    update: function update(chart, width, height, minPadding) {
7592      if (!chart) {
7593        return;
7594      }
7595
7596      var padding = toPadding(chart.options.layout.padding);
7597      var availableWidth = Math.max(width - padding.width, 0);
7598      var availableHeight = Math.max(height - padding.height, 0);
7599      var boxes = buildLayoutBoxes(chart.boxes);
7600      var verticalBoxes = boxes.vertical;
7601      var horizontalBoxes = boxes.horizontal;
7602      each(chart.boxes, function (box) {
7603        if (typeof box.beforeLayout === 'function') {
7604          box.beforeLayout();
7605        }
7606      });
7607      var visibleVerticalBoxCount = verticalBoxes.reduce(function (total, wrap) {
7608        return wrap.box.options && wrap.box.options.display === false ? total : total + 1;
7609      }, 0) || 1;
7610      var params = Object.freeze({
7611        outerWidth: width,
7612        outerHeight: height,
7613        padding: padding,
7614        availableWidth: availableWidth,
7615        availableHeight: availableHeight,
7616        vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,
7617        hBoxMaxHeight: availableHeight / 2
7618      });
7619      var maxPadding = Object.assign({}, padding);
7620      updateMaxPadding(maxPadding, toPadding(minPadding));
7621      var chartArea = Object.assign({
7622        maxPadding: maxPadding,
7623        w: availableWidth,
7624        h: availableHeight,
7625        x: padding.left,
7626        y: padding.top
7627      }, padding);
7628      setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
7629      fitBoxes(boxes.fullSize, chartArea, params);
7630      fitBoxes(verticalBoxes, chartArea, params);
7631
7632      if (fitBoxes(horizontalBoxes, chartArea, params)) {
7633        fitBoxes(verticalBoxes, chartArea, params);
7634      }
7635
7636      handleMaxPadding(chartArea);
7637      placeBoxes(boxes.leftAndTop, chartArea, params);
7638      chartArea.x += chartArea.w;
7639      chartArea.y += chartArea.h;
7640      placeBoxes(boxes.rightAndBottom, chartArea, params);
7641      chart.chartArea = {
7642        left: chartArea.left,
7643        top: chartArea.top,
7644        right: chartArea.left + chartArea.w,
7645        bottom: chartArea.top + chartArea.h,
7646        height: chartArea.h,
7647        width: chartArea.w
7648      };
7649      each(boxes.chartArea, function (layout) {
7650        var box = layout.box;
7651        Object.assign(box, chart.chartArea);
7652        box.update(chartArea.w, chartArea.h);
7653      });
7654    }
7655  };
7656
7657  var BasePlatform = /*#__PURE__*/function () {
7658    function BasePlatform() {
7659      _classCallCheck(this, BasePlatform);
7660    }
7661
7662    _createClass(BasePlatform, [{
7663      key: "acquireContext",
7664      value: function acquireContext(canvas, aspectRatio) {}
7665    }, {
7666      key: "releaseContext",
7667      value: function releaseContext(context) {
7668        return false;
7669      }
7670    }, {
7671      key: "addEventListener",
7672      value: function addEventListener(chart, type, listener) {}
7673    }, {
7674      key: "removeEventListener",
7675      value: function removeEventListener(chart, type, listener) {}
7676    }, {
7677      key: "getDevicePixelRatio",
7678      value: function getDevicePixelRatio() {
7679        return 1;
7680      }
7681    }, {
7682      key: "getMaximumSize",
7683      value: function getMaximumSize(element, width, height, aspectRatio) {
7684        width = Math.max(0, width || element.width);
7685        height = height || element.height;
7686        return {
7687          width: width,
7688          height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)
7689        };
7690      }
7691    }, {
7692      key: "isAttached",
7693      value: function isAttached(canvas) {
7694        return true;
7695      }
7696    }]);
7697
7698    return BasePlatform;
7699  }();
7700
7701  var BasicPlatform = /*#__PURE__*/function (_BasePlatform) {
7702    _inherits(BasicPlatform, _BasePlatform);
7703
7704    var _super9 = _createSuper(BasicPlatform);
7705
7706    function BasicPlatform() {
7707      _classCallCheck(this, BasicPlatform);
7708
7709      return _super9.apply(this, arguments);
7710    }
7711
7712    _createClass(BasicPlatform, [{
7713      key: "acquireContext",
7714      value: function acquireContext(item) {
7715        return item && item.getContext && item.getContext('2d') || null;
7716      }
7717    }]);
7718
7719    return BasicPlatform;
7720  }(BasePlatform);
7721
7722  var EXPANDO_KEY = '$chartjs';
7723  var EVENT_TYPES = {
7724    touchstart: 'mousedown',
7725    touchmove: 'mousemove',
7726    touchend: 'mouseup',
7727    pointerenter: 'mouseenter',
7728    pointerdown: 'mousedown',
7729    pointermove: 'mousemove',
7730    pointerup: 'mouseup',
7731    pointerleave: 'mouseout',
7732    pointerout: 'mouseout'
7733  };
7734
7735  var isNullOrEmpty = function isNullOrEmpty(value) {
7736    return value === null || value === '';
7737  };
7738
7739  function initCanvas(canvas, aspectRatio) {
7740    var style = canvas.style;
7741    var renderHeight = canvas.getAttribute('height');
7742    var renderWidth = canvas.getAttribute('width');
7743    canvas[EXPANDO_KEY] = {
7744      initial: {
7745        height: renderHeight,
7746        width: renderWidth,
7747        style: {
7748          display: style.display,
7749          height: style.height,
7750          width: style.width
7751        }
7752      }
7753    };
7754    style.display = style.display || 'block';
7755    style.boxSizing = style.boxSizing || 'border-box';
7756
7757    if (isNullOrEmpty(renderWidth)) {
7758      var displayWidth = readUsedSize(canvas, 'width');
7759
7760      if (displayWidth !== undefined) {
7761        canvas.width = displayWidth;
7762      }
7763    }
7764
7765    if (isNullOrEmpty(renderHeight)) {
7766      if (canvas.style.height === '') {
7767        canvas.height = canvas.width / (aspectRatio || 2);
7768      } else {
7769        var displayHeight = readUsedSize(canvas, 'height');
7770
7771        if (displayHeight !== undefined) {
7772          canvas.height = displayHeight;
7773        }
7774      }
7775    }
7776
7777    return canvas;
7778  }
7779
7780  var eventListenerOptions = supportsEventListenerOptions ? {
7781    passive: true
7782  } : false;
7783
7784  function addListener(node, type, listener) {
7785    node.addEventListener(type, listener, eventListenerOptions);
7786  }
7787
7788  function removeListener(chart, type, listener) {
7789    chart.canvas.removeEventListener(type, listener, eventListenerOptions);
7790  }
7791
7792  function fromNativeEvent(event, chart) {
7793    var type = EVENT_TYPES[event.type] || event.type;
7794
7795    var _getRelativePosition$ = getRelativePosition$1(event, chart),
7796        x = _getRelativePosition$.x,
7797        y = _getRelativePosition$.y;
7798
7799    return {
7800      type: type,
7801      chart: chart,
7802      native: event,
7803      x: x !== undefined ? x : null,
7804      y: y !== undefined ? y : null
7805    };
7806  }
7807
7808  function createAttachObserver(chart, type, listener) {
7809    var canvas = chart.canvas;
7810
7811    var container = canvas && _getParentNode(canvas);
7812
7813    var element = container || canvas;
7814    var observer = new MutationObserver(function (entries) {
7815      var parent = _getParentNode(element);
7816
7817      entries.forEach(function (entry) {
7818        for (var i = 0; i < entry.addedNodes.length; i++) {
7819          var added = entry.addedNodes[i];
7820
7821          if (added === element || added === parent) {
7822            listener(entry.target);
7823          }
7824        }
7825      });
7826    });
7827    observer.observe(document, {
7828      childList: true,
7829      subtree: true
7830    });
7831    return observer;
7832  }
7833
7834  function createDetachObserver(chart, type, listener) {
7835    var canvas = chart.canvas;
7836
7837    var container = canvas && _getParentNode(canvas);
7838
7839    if (!container) {
7840      return;
7841    }
7842
7843    var observer = new MutationObserver(function (entries) {
7844      entries.forEach(function (entry) {
7845        for (var i = 0; i < entry.removedNodes.length; i++) {
7846          if (entry.removedNodes[i] === canvas) {
7847            listener();
7848            break;
7849          }
7850        }
7851      });
7852    });
7853    observer.observe(container, {
7854      childList: true
7855    });
7856    return observer;
7857  }
7858
7859  var drpListeningCharts = new Map();
7860  var oldDevicePixelRatio = 0;
7861
7862  function onWindowResize() {
7863    var dpr = window.devicePixelRatio;
7864
7865    if (dpr === oldDevicePixelRatio) {
7866      return;
7867    }
7868
7869    oldDevicePixelRatio = dpr;
7870    drpListeningCharts.forEach(function (resize, chart) {
7871      if (chart.currentDevicePixelRatio !== dpr) {
7872        resize();
7873      }
7874    });
7875  }
7876
7877  function listenDevicePixelRatioChanges(chart, resize) {
7878    if (!drpListeningCharts.size) {
7879      window.addEventListener('resize', onWindowResize);
7880    }
7881
7882    drpListeningCharts.set(chart, resize);
7883  }
7884
7885  function unlistenDevicePixelRatioChanges(chart) {
7886    drpListeningCharts.delete(chart);
7887
7888    if (!drpListeningCharts.size) {
7889      window.removeEventListener('resize', onWindowResize);
7890    }
7891  }
7892
7893  function createResizeObserver(chart, type, listener) {
7894    var canvas = chart.canvas;
7895
7896    var container = canvas && _getParentNode(canvas);
7897
7898    if (!container) {
7899      return;
7900    }
7901
7902    var resize = throttled(function (width, height) {
7903      var w = container.clientWidth;
7904      listener(width, height);
7905
7906      if (w < container.clientWidth) {
7907        listener();
7908      }
7909    }, window);
7910    var observer = new ResizeObserver(function (entries) {
7911      var entry = entries[0];
7912      var width = entry.contentRect.width;
7913      var height = entry.contentRect.height;
7914
7915      if (width === 0 && height === 0) {
7916        return;
7917      }
7918
7919      resize(width, height);
7920    });
7921    observer.observe(container);
7922    listenDevicePixelRatioChanges(chart, resize);
7923    return observer;
7924  }
7925
7926  function releaseObserver(chart, type, observer) {
7927    if (observer) {
7928      observer.disconnect();
7929    }
7930
7931    if (type === 'resize') {
7932      unlistenDevicePixelRatioChanges(chart);
7933    }
7934  }
7935
7936  function createProxyAndListen(chart, type, listener) {
7937    var canvas = chart.canvas;
7938    var proxy = throttled(function (event) {
7939      if (chart.ctx !== null) {
7940        listener(fromNativeEvent(event, chart));
7941      }
7942    }, chart, function (args) {
7943      var event = args[0];
7944      return [event, event.offsetX, event.offsetY];
7945    });
7946    addListener(canvas, type, proxy);
7947    return proxy;
7948  }
7949
7950  var DomPlatform = /*#__PURE__*/function (_BasePlatform2) {
7951    _inherits(DomPlatform, _BasePlatform2);
7952
7953    var _super10 = _createSuper(DomPlatform);
7954
7955    function DomPlatform() {
7956      _classCallCheck(this, DomPlatform);
7957
7958      return _super10.apply(this, arguments);
7959    }
7960
7961    _createClass(DomPlatform, [{
7962      key: "acquireContext",
7963      value: function acquireContext(canvas, aspectRatio) {
7964        var context = canvas && canvas.getContext && canvas.getContext('2d');
7965
7966        if (context && context.canvas === canvas) {
7967          initCanvas(canvas, aspectRatio);
7968          return context;
7969        }
7970
7971        return null;
7972      }
7973    }, {
7974      key: "releaseContext",
7975      value: function releaseContext(context) {
7976        var canvas = context.canvas;
7977
7978        if (!canvas[EXPANDO_KEY]) {
7979          return false;
7980        }
7981
7982        var initial = canvas[EXPANDO_KEY].initial;
7983        ['height', 'width'].forEach(function (prop) {
7984          var value = initial[prop];
7985
7986          if (isNullOrUndef(value)) {
7987            canvas.removeAttribute(prop);
7988          } else {
7989            canvas.setAttribute(prop, value);
7990          }
7991        });
7992        var style = initial.style || {};
7993        Object.keys(style).forEach(function (key) {
7994          canvas.style[key] = style[key];
7995        });
7996        canvas.width = canvas.width;
7997        delete canvas[EXPANDO_KEY];
7998        return true;
7999      }
8000    }, {
8001      key: "addEventListener",
8002      value: function addEventListener(chart, type, listener) {
8003        this.removeEventListener(chart, type);
8004        var proxies = chart.$proxies || (chart.$proxies = {});
8005        var handlers = {
8006          attach: createAttachObserver,
8007          detach: createDetachObserver,
8008          resize: createResizeObserver
8009        };
8010        var handler = handlers[type] || createProxyAndListen;
8011        proxies[type] = handler(chart, type, listener);
8012      }
8013    }, {
8014      key: "removeEventListener",
8015      value: function removeEventListener(chart, type) {
8016        var proxies = chart.$proxies || (chart.$proxies = {});
8017        var proxy = proxies[type];
8018
8019        if (!proxy) {
8020          return;
8021        }
8022
8023        var handlers = {
8024          attach: releaseObserver,
8025          detach: releaseObserver,
8026          resize: releaseObserver
8027        };
8028        var handler = handlers[type] || removeListener;
8029        handler(chart, type, proxy);
8030        proxies[type] = undefined;
8031      }
8032    }, {
8033      key: "getDevicePixelRatio",
8034      value: function getDevicePixelRatio() {
8035        return window.devicePixelRatio;
8036      }
8037    }, {
8038      key: "getMaximumSize",
8039      value: function getMaximumSize$1(canvas, width, height, aspectRatio) {
8040        return getMaximumSize(canvas, width, height, aspectRatio);
8041      }
8042    }, {
8043      key: "isAttached",
8044      value: function isAttached(canvas) {
8045        var container = _getParentNode(canvas);
8046
8047        return !!(container && _getParentNode(container));
8048      }
8049    }]);
8050
8051    return DomPlatform;
8052  }(BasePlatform);
8053
8054  var Element = /*#__PURE__*/function () {
8055    function Element() {
8056      _classCallCheck(this, Element);
8057
8058      this.x = undefined;
8059      this.y = undefined;
8060      this.active = false;
8061      this.options = undefined;
8062      this.$animations = undefined;
8063    }
8064
8065    _createClass(Element, [{
8066      key: "tooltipPosition",
8067      value: function tooltipPosition(useFinalPosition) {
8068        var _this$getProps = this.getProps(['x', 'y'], useFinalPosition),
8069            x = _this$getProps.x,
8070            y = _this$getProps.y;
8071
8072        return {
8073          x: x,
8074          y: y
8075        };
8076      }
8077    }, {
8078      key: "hasValue",
8079      value: function hasValue() {
8080        return isNumber(this.x) && isNumber(this.y);
8081      }
8082    }, {
8083      key: "getProps",
8084      value: function getProps(props, final) {
8085        var me = this;
8086        var anims = this.$animations;
8087
8088        if (!final || !anims) {
8089          return me;
8090        }
8091
8092        var ret = {};
8093        props.forEach(function (prop) {
8094          ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : me[prop];
8095        });
8096        return ret;
8097      }
8098    }]);
8099
8100    return Element;
8101  }();
8102
8103  Element.defaults = {};
8104  Element.defaultRoutes = undefined;
8105  var formatters$2 = {
8106    values: function values(value) {
8107      return isArray(value) ? value : '' + value;
8108    },
8109    numeric: function numeric(tickValue, index, ticks) {
8110      if (tickValue === 0) {
8111        return '0';
8112      }
8113
8114      var locale = this.chart.options.locale;
8115      var notation;
8116      var delta = tickValue;
8117
8118      if (ticks.length > 1) {
8119        var maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));
8120
8121        if (maxTick < 1e-4 || maxTick > 1e+15) {
8122          notation = 'scientific';
8123        }
8124
8125        delta = calculateDelta(tickValue, ticks);
8126      }
8127
8128      var logDelta = log10(Math.abs(delta));
8129      var numDecimal = Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);
8130      var options = {
8131        notation: notation,
8132        minimumFractionDigits: numDecimal,
8133        maximumFractionDigits: numDecimal
8134      };
8135      Object.assign(options, this.options.ticks.format);
8136      return formatNumber(tickValue, locale, options);
8137    },
8138    logarithmic: function logarithmic(tickValue, index, ticks) {
8139      if (tickValue === 0) {
8140        return '0';
8141      }
8142
8143      var remain = tickValue / Math.pow(10, Math.floor(log10(tickValue)));
8144
8145      if (remain === 1 || remain === 2 || remain === 5) {
8146        return formatters$2.numeric.call(this, tickValue, index, ticks);
8147      }
8148
8149      return '';
8150    }
8151  };
8152
8153  function calculateDelta(tickValue, ticks) {
8154    var delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;
8155
8156    if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) {
8157      delta = tickValue - Math.floor(tickValue);
8158    }
8159
8160    return delta;
8161  }
8162
8163  var Ticks = {
8164    formatters: formatters$2
8165  };
8166  defaults.set('scale', {
8167    display: true,
8168    offset: false,
8169    reverse: false,
8170    beginAtZero: false,
8171    bounds: 'ticks',
8172    grace: 0,
8173    grid: {
8174      display: true,
8175      lineWidth: 1,
8176      drawBorder: true,
8177      drawOnChartArea: true,
8178      drawTicks: true,
8179      tickLength: 8,
8180      tickWidth: function tickWidth(_ctx, options) {
8181        return options.lineWidth;
8182      },
8183      tickColor: function tickColor(_ctx, options) {
8184        return options.color;
8185      },
8186      offset: false,
8187      borderDash: [],
8188      borderDashOffset: 0.0,
8189      borderWidth: 1
8190    },
8191    title: {
8192      display: false,
8193      text: '',
8194      padding: {
8195        top: 4,
8196        bottom: 4
8197      }
8198    },
8199    ticks: {
8200      minRotation: 0,
8201      maxRotation: 50,
8202      mirror: false,
8203      textStrokeWidth: 0,
8204      textStrokeColor: '',
8205      padding: 3,
8206      display: true,
8207      autoSkip: true,
8208      autoSkipPadding: 3,
8209      labelOffset: 0,
8210      callback: Ticks.formatters.values,
8211      minor: {},
8212      major: {},
8213      align: 'center',
8214      crossAlign: 'near',
8215      showLabelBackdrop: false,
8216      backdropColor: 'rgba(255, 255, 255, 0.75)',
8217      backdropPadding: 2
8218    }
8219  });
8220  defaults.route('scale.ticks', 'color', '', 'color');
8221  defaults.route('scale.grid', 'color', '', 'borderColor');
8222  defaults.route('scale.grid', 'borderColor', '', 'borderColor');
8223  defaults.route('scale.title', 'color', '', 'color');
8224  defaults.describe('scale', {
8225    _fallback: false,
8226    _scriptable: function _scriptable(name) {
8227      return !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser';
8228    },
8229    _indexable: function _indexable(name) {
8230      return name !== 'borderDash' && name !== 'tickBorderDash';
8231    }
8232  });
8233  defaults.describe('scales', {
8234    _fallback: 'scale'
8235  });
8236  defaults.describe('scale.ticks', {
8237    _scriptable: function _scriptable(name) {
8238      return name !== 'backdropPadding' && name !== 'callback';
8239    },
8240    _indexable: function _indexable(name) {
8241      return name !== 'backdropPadding';
8242    }
8243  });
8244
8245  function autoSkip(scale, ticks) {
8246    var tickOpts = scale.options.ticks;
8247    var ticksLimit = tickOpts.maxTicksLimit || determineMaxTicks(scale);
8248    var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
8249    var numMajorIndices = majorIndices.length;
8250    var first = majorIndices[0];
8251    var last = majorIndices[numMajorIndices - 1];
8252    var newTicks = [];
8253
8254    if (numMajorIndices > ticksLimit) {
8255      skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);
8256      return newTicks;
8257    }
8258
8259    var spacing = calculateSpacing(majorIndices, ticks, ticksLimit);
8260
8261    if (numMajorIndices > 0) {
8262      var i, ilen;
8263      var avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
8264      skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
8265
8266      for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
8267        skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
8268      }
8269
8270      skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
8271      return newTicks;
8272    }
8273
8274    skip(ticks, newTicks, spacing);
8275    return newTicks;
8276  }
8277
8278  function determineMaxTicks(scale) {
8279    var offset = scale.options.offset;
8280
8281    var tickLength = scale._tickSize();
8282
8283    var maxScale = scale._length / tickLength + (offset ? 0 : 1);
8284    var maxChart = scale._maxLength / tickLength;
8285    return Math.floor(Math.min(maxScale, maxChart));
8286  }
8287
8288  function calculateSpacing(majorIndices, ticks, ticksLimit) {
8289    var evenMajorSpacing = getEvenSpacing(majorIndices);
8290    var spacing = ticks.length / ticksLimit;
8291
8292    if (!evenMajorSpacing) {
8293      return Math.max(spacing, 1);
8294    }
8295
8296    var factors = _factorize(evenMajorSpacing);
8297
8298    for (var i = 0, ilen = factors.length - 1; i < ilen; i++) {
8299      var factor = factors[i];
8300
8301      if (factor > spacing) {
8302        return factor;
8303      }
8304    }
8305
8306    return Math.max(spacing, 1);
8307  }
8308
8309  function getMajorIndices(ticks) {
8310    var result = [];
8311    var i, ilen;
8312
8313    for (i = 0, ilen = ticks.length; i < ilen; i++) {
8314      if (ticks[i].major) {
8315        result.push(i);
8316      }
8317    }
8318
8319    return result;
8320  }
8321
8322  function skipMajors(ticks, newTicks, majorIndices, spacing) {
8323    var count = 0;
8324    var next = majorIndices[0];
8325    var i;
8326    spacing = Math.ceil(spacing);
8327
8328    for (i = 0; i < ticks.length; i++) {
8329      if (i === next) {
8330        newTicks.push(ticks[i]);
8331        count++;
8332        next = majorIndices[count * spacing];
8333      }
8334    }
8335  }
8336
8337  function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
8338    var start = valueOrDefault(majorStart, 0);
8339    var end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);
8340    var count = 0;
8341    var length, i, next;
8342    spacing = Math.ceil(spacing);
8343
8344    if (majorEnd) {
8345      length = majorEnd - majorStart;
8346      spacing = length / Math.floor(length / spacing);
8347    }
8348
8349    next = start;
8350
8351    while (next < 0) {
8352      count++;
8353      next = Math.round(start + count * spacing);
8354    }
8355
8356    for (i = Math.max(start, 0); i < end; i++) {
8357      if (i === next) {
8358        newTicks.push(ticks[i]);
8359        count++;
8360        next = Math.round(start + count * spacing);
8361      }
8362    }
8363  }
8364
8365  function getEvenSpacing(arr) {
8366    var len = arr.length;
8367    var i, diff;
8368
8369    if (len < 2) {
8370      return false;
8371    }
8372
8373    for (diff = arr[0], i = 1; i < len; ++i) {
8374      if (arr[i] - arr[i - 1] !== diff) {
8375        return false;
8376      }
8377    }
8378
8379    return diff;
8380  }
8381
8382  var reverseAlign = function reverseAlign(align) {
8383    return align === 'left' ? 'right' : align === 'right' ? 'left' : align;
8384  };
8385
8386  var offsetFromEdge = function offsetFromEdge(scale, edge, offset) {
8387    return edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;
8388  };
8389
8390  function sample(arr, numItems) {
8391    var result = [];
8392    var increment = arr.length / numItems;
8393    var len = arr.length;
8394    var i = 0;
8395
8396    for (; i < len; i += increment) {
8397      result.push(arr[Math.floor(i)]);
8398    }
8399
8400    return result;
8401  }
8402
8403  function getPixelForGridLine(scale, index, offsetGridLines) {
8404    var length = scale.ticks.length;
8405    var validIndex = Math.min(index, length - 1);
8406    var start = scale._startPixel;
8407    var end = scale._endPixel;
8408    var epsilon = 1e-6;
8409    var lineValue = scale.getPixelForTick(validIndex);
8410    var offset;
8411
8412    if (offsetGridLines) {
8413      if (length === 1) {
8414        offset = Math.max(lineValue - start, end - lineValue);
8415      } else if (index === 0) {
8416        offset = (scale.getPixelForTick(1) - lineValue) / 2;
8417      } else {
8418        offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
8419      }
8420
8421      lineValue += validIndex < index ? offset : -offset;
8422
8423      if (lineValue < start - epsilon || lineValue > end + epsilon) {
8424        return;
8425      }
8426    }
8427
8428    return lineValue;
8429  }
8430
8431  function garbageCollect(caches, length) {
8432    each(caches, function (cache) {
8433      var gc = cache.gc;
8434      var gcLen = gc.length / 2;
8435      var i;
8436
8437      if (gcLen > length) {
8438        for (i = 0; i < gcLen; ++i) {
8439          delete cache.data[gc[i]];
8440        }
8441
8442        gc.splice(0, gcLen);
8443      }
8444    });
8445  }
8446
8447  function getTickMarkLength(options) {
8448    return options.drawTicks ? options.tickLength : 0;
8449  }
8450
8451  function getTitleHeight(options, fallback) {
8452    if (!options.display) {
8453      return 0;
8454    }
8455
8456    var font = toFont(options.font, fallback);
8457    var padding = toPadding(options.padding);
8458    var lines = isArray(options.text) ? options.text.length : 1;
8459    return lines * font.lineHeight + padding.height;
8460  }
8461
8462  function createScaleContext(parent, scale) {
8463    return Object.assign(Object.create(parent), {
8464      scale: scale,
8465      type: 'scale'
8466    });
8467  }
8468
8469  function createTickContext(parent, index, tick) {
8470    return Object.assign(Object.create(parent), {
8471      tick: tick,
8472      index: index,
8473      type: 'tick'
8474    });
8475  }
8476
8477  function titleAlign(align, position, reverse) {
8478    var ret = _toLeftRightCenter(align);
8479
8480    if (reverse && position !== 'right' || !reverse && position === 'right') {
8481      ret = reverseAlign(ret);
8482    }
8483
8484    return ret;
8485  }
8486
8487  function titleArgs(scale, offset, position, align) {
8488    var top = scale.top,
8489        left = scale.left,
8490        bottom = scale.bottom,
8491        right = scale.right;
8492    var rotation = 0;
8493    var maxWidth, titleX, titleY;
8494
8495    if (scale.isHorizontal()) {
8496      titleX = _alignStartEnd(align, left, right);
8497      titleY = offsetFromEdge(scale, position, offset);
8498      maxWidth = right - left;
8499    } else {
8500      titleX = offsetFromEdge(scale, position, offset);
8501      titleY = _alignStartEnd(align, bottom, top);
8502      rotation = position === 'left' ? -HALF_PI : HALF_PI;
8503    }
8504
8505    return {
8506      titleX: titleX,
8507      titleY: titleY,
8508      maxWidth: maxWidth,
8509      rotation: rotation
8510    };
8511  }
8512
8513  var Scale = /*#__PURE__*/function (_Element) {
8514    _inherits(Scale, _Element);
8515
8516    var _super11 = _createSuper(Scale);
8517
8518    function Scale(cfg) {
8519      var _this4;
8520
8521      _classCallCheck(this, Scale);
8522
8523      _this4 = _super11.call(this);
8524      _this4.id = cfg.id;
8525      _this4.type = cfg.type;
8526      _this4.options = undefined;
8527      _this4.ctx = cfg.ctx;
8528      _this4.chart = cfg.chart;
8529      _this4.top = undefined;
8530      _this4.bottom = undefined;
8531      _this4.left = undefined;
8532      _this4.right = undefined;
8533      _this4.width = undefined;
8534      _this4.height = undefined;
8535      _this4._margins = {
8536        left: 0,
8537        right: 0,
8538        top: 0,
8539        bottom: 0
8540      };
8541      _this4.maxWidth = undefined;
8542      _this4.maxHeight = undefined;
8543      _this4.paddingTop = undefined;
8544      _this4.paddingBottom = undefined;
8545      _this4.paddingLeft = undefined;
8546      _this4.paddingRight = undefined;
8547      _this4.axis = undefined;
8548      _this4.labelRotation = undefined;
8549      _this4.min = undefined;
8550      _this4.max = undefined;
8551      _this4._range = undefined;
8552      _this4.ticks = [];
8553      _this4._gridLineItems = null;
8554      _this4._labelItems = null;
8555      _this4._labelSizes = null;
8556      _this4._length = 0;
8557      _this4._maxLength = 0;
8558      _this4._longestTextCache = {};
8559      _this4._startPixel = undefined;
8560      _this4._endPixel = undefined;
8561      _this4._reversePixels = false;
8562      _this4._userMax = undefined;
8563      _this4._userMin = undefined;
8564      _this4._suggestedMax = undefined;
8565      _this4._suggestedMin = undefined;
8566      _this4._ticksLength = 0;
8567      _this4._borderValue = 0;
8568      _this4._cache = {};
8569      _this4._dataLimitsCached = false;
8570      _this4.$context = undefined;
8571      return _this4;
8572    }
8573
8574    _createClass(Scale, [{
8575      key: "init",
8576      value: function init(options) {
8577        var me = this;
8578        me.options = options.setContext(me.getContext());
8579        me.axis = options.axis;
8580        me._userMin = me.parse(options.min);
8581        me._userMax = me.parse(options.max);
8582        me._suggestedMin = me.parse(options.suggestedMin);
8583        me._suggestedMax = me.parse(options.suggestedMax);
8584      }
8585    }, {
8586      key: "parse",
8587      value: function parse(raw, index) {
8588        return raw;
8589      }
8590    }, {
8591      key: "getUserBounds",
8592      value: function getUserBounds() {
8593        var _userMin = this._userMin,
8594            _userMax = this._userMax,
8595            _suggestedMin = this._suggestedMin,
8596            _suggestedMax = this._suggestedMax;
8597        _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);
8598        _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);
8599        _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);
8600        _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);
8601        return {
8602          min: finiteOrDefault(_userMin, _suggestedMin),
8603          max: finiteOrDefault(_userMax, _suggestedMax),
8604          minDefined: isNumberFinite(_userMin),
8605          maxDefined: isNumberFinite(_userMax)
8606        };
8607      }
8608    }, {
8609      key: "getMinMax",
8610      value: function getMinMax(canStack) {
8611        var me = this;
8612
8613        var _me$getUserBounds = me.getUserBounds(),
8614            min = _me$getUserBounds.min,
8615            max = _me$getUserBounds.max,
8616            minDefined = _me$getUserBounds.minDefined,
8617            maxDefined = _me$getUserBounds.maxDefined;
8618
8619        var range;
8620
8621        if (minDefined && maxDefined) {
8622          return {
8623            min: min,
8624            max: max
8625          };
8626        }
8627
8628        var metas = me.getMatchingVisibleMetas();
8629
8630        for (var i = 0, ilen = metas.length; i < ilen; ++i) {
8631          range = metas[i].controller.getMinMax(me, canStack);
8632
8633          if (!minDefined) {
8634            min = Math.min(min, range.min);
8635          }
8636
8637          if (!maxDefined) {
8638            max = Math.max(max, range.max);
8639          }
8640        }
8641
8642        return {
8643          min: finiteOrDefault(min, finiteOrDefault(max, min)),
8644          max: finiteOrDefault(max, finiteOrDefault(min, max))
8645        };
8646      }
8647    }, {
8648      key: "getPadding",
8649      value: function getPadding() {
8650        var me = this;
8651        return {
8652          left: me.paddingLeft || 0,
8653          top: me.paddingTop || 0,
8654          right: me.paddingRight || 0,
8655          bottom: me.paddingBottom || 0
8656        };
8657      }
8658    }, {
8659      key: "getTicks",
8660      value: function getTicks() {
8661        return this.ticks;
8662      }
8663    }, {
8664      key: "getLabels",
8665      value: function getLabels() {
8666        var data = this.chart.data;
8667        return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
8668      }
8669    }, {
8670      key: "beforeLayout",
8671      value: function beforeLayout() {
8672        this._cache = {};
8673        this._dataLimitsCached = false;
8674      }
8675    }, {
8676      key: "beforeUpdate",
8677      value: function beforeUpdate() {
8678        callback(this.options.beforeUpdate, [this]);
8679      }
8680    }, {
8681      key: "update",
8682      value: function update(maxWidth, maxHeight, margins) {
8683        var me = this;
8684        var tickOpts = me.options.ticks;
8685        var sampleSize = tickOpts.sampleSize;
8686        me.beforeUpdate();
8687        me.maxWidth = maxWidth;
8688        me.maxHeight = maxHeight;
8689        me._margins = margins = Object.assign({
8690          left: 0,
8691          right: 0,
8692          top: 0,
8693          bottom: 0
8694        }, margins);
8695        me.ticks = null;
8696        me._labelSizes = null;
8697        me._gridLineItems = null;
8698        me._labelItems = null;
8699        me.beforeSetDimensions();
8700        me.setDimensions();
8701        me.afterSetDimensions();
8702        me._maxLength = me.isHorizontal() ? me.width + margins.left + margins.right : me.height + margins.top + margins.bottom;
8703
8704        if (!me._dataLimitsCached) {
8705          me.beforeDataLimits();
8706          me.determineDataLimits();
8707          me.afterDataLimits();
8708          me._range = _addGrace(me, me.options.grace);
8709          me._dataLimitsCached = true;
8710        }
8711
8712        me.beforeBuildTicks();
8713        me.ticks = me.buildTicks() || [];
8714        me.afterBuildTicks();
8715        var samplingEnabled = sampleSize < me.ticks.length;
8716
8717        me._convertTicksToLabels(samplingEnabled ? sample(me.ticks, sampleSize) : me.ticks);
8718
8719        me.configure();
8720        me.beforeCalculateLabelRotation();
8721        me.calculateLabelRotation();
8722        me.afterCalculateLabelRotation();
8723
8724        if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {
8725          me.ticks = autoSkip(me, me.ticks);
8726          me._labelSizes = null;
8727        }
8728
8729        if (samplingEnabled) {
8730          me._convertTicksToLabels(me.ticks);
8731        }
8732
8733        me.beforeFit();
8734        me.fit();
8735        me.afterFit();
8736        me.afterUpdate();
8737      }
8738    }, {
8739      key: "configure",
8740      value: function configure() {
8741        var me = this;
8742        var reversePixels = me.options.reverse;
8743        var startPixel, endPixel;
8744
8745        if (me.isHorizontal()) {
8746          startPixel = me.left;
8747          endPixel = me.right;
8748        } else {
8749          startPixel = me.top;
8750          endPixel = me.bottom;
8751          reversePixels = !reversePixels;
8752        }
8753
8754        me._startPixel = startPixel;
8755        me._endPixel = endPixel;
8756        me._reversePixels = reversePixels;
8757        me._length = endPixel - startPixel;
8758        me._alignToPixels = me.options.alignToPixels;
8759      }
8760    }, {
8761      key: "afterUpdate",
8762      value: function afterUpdate() {
8763        callback(this.options.afterUpdate, [this]);
8764      }
8765    }, {
8766      key: "beforeSetDimensions",
8767      value: function beforeSetDimensions() {
8768        callback(this.options.beforeSetDimensions, [this]);
8769      }
8770    }, {
8771      key: "setDimensions",
8772      value: function setDimensions() {
8773        var me = this;
8774
8775        if (me.isHorizontal()) {
8776          me.width = me.maxWidth;
8777          me.left = 0;
8778          me.right = me.width;
8779        } else {
8780          me.height = me.maxHeight;
8781          me.top = 0;
8782          me.bottom = me.height;
8783        }
8784
8785        me.paddingLeft = 0;
8786        me.paddingTop = 0;
8787        me.paddingRight = 0;
8788        me.paddingBottom = 0;
8789      }
8790    }, {
8791      key: "afterSetDimensions",
8792      value: function afterSetDimensions() {
8793        callback(this.options.afterSetDimensions, [this]);
8794      }
8795    }, {
8796      key: "_callHooks",
8797      value: function _callHooks(name) {
8798        var me = this;
8799        me.chart.notifyPlugins(name, me.getContext());
8800        callback(me.options[name], [me]);
8801      }
8802    }, {
8803      key: "beforeDataLimits",
8804      value: function beforeDataLimits() {
8805        this._callHooks('beforeDataLimits');
8806      }
8807    }, {
8808      key: "determineDataLimits",
8809      value: function determineDataLimits() {}
8810    }, {
8811      key: "afterDataLimits",
8812      value: function afterDataLimits() {
8813        this._callHooks('afterDataLimits');
8814      }
8815    }, {
8816      key: "beforeBuildTicks",
8817      value: function beforeBuildTicks() {
8818        this._callHooks('beforeBuildTicks');
8819      }
8820    }, {
8821      key: "buildTicks",
8822      value: function buildTicks() {
8823        return [];
8824      }
8825    }, {
8826      key: "afterBuildTicks",
8827      value: function afterBuildTicks() {
8828        this._callHooks('afterBuildTicks');
8829      }
8830    }, {
8831      key: "beforeTickToLabelConversion",
8832      value: function beforeTickToLabelConversion() {
8833        callback(this.options.beforeTickToLabelConversion, [this]);
8834      }
8835    }, {
8836      key: "generateTickLabels",
8837      value: function generateTickLabels(ticks) {
8838        var me = this;
8839        var tickOpts = me.options.ticks;
8840        var i, ilen, tick;
8841
8842        for (i = 0, ilen = ticks.length; i < ilen; i++) {
8843          tick = ticks[i];
8844          tick.label = callback(tickOpts.callback, [tick.value, i, ticks], me);
8845        }
8846      }
8847    }, {
8848      key: "afterTickToLabelConversion",
8849      value: function afterTickToLabelConversion() {
8850        callback(this.options.afterTickToLabelConversion, [this]);
8851      }
8852    }, {
8853      key: "beforeCalculateLabelRotation",
8854      value: function beforeCalculateLabelRotation() {
8855        callback(this.options.beforeCalculateLabelRotation, [this]);
8856      }
8857    }, {
8858      key: "calculateLabelRotation",
8859      value: function calculateLabelRotation() {
8860        var me = this;
8861        var options = me.options;
8862        var tickOpts = options.ticks;
8863        var numTicks = me.ticks.length;
8864        var minRotation = tickOpts.minRotation || 0;
8865        var maxRotation = tickOpts.maxRotation;
8866        var labelRotation = minRotation;
8867        var tickWidth, maxHeight, maxLabelDiagonal;
8868
8869        if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
8870          me.labelRotation = minRotation;
8871          return;
8872        }
8873
8874        var labelSizes = me._getLabelSizes();
8875
8876        var maxLabelWidth = labelSizes.widest.width;
8877        var maxLabelHeight = labelSizes.highest.height;
8878
8879        var maxWidth = _limitValue(me.chart.width - maxLabelWidth, 0, me.maxWidth);
8880
8881        tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
8882
8883        if (maxLabelWidth + 6 > tickWidth) {
8884          tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
8885          maxHeight = me.maxHeight - getTickMarkLength(options.grid) - tickOpts.padding - getTitleHeight(options.title, me.chart.options.font);
8886          maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
8887          labelRotation = toDegrees(Math.min(Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)), Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)));
8888          labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
8889        }
8890
8891        me.labelRotation = labelRotation;
8892      }
8893    }, {
8894      key: "afterCalculateLabelRotation",
8895      value: function afterCalculateLabelRotation() {
8896        callback(this.options.afterCalculateLabelRotation, [this]);
8897      }
8898    }, {
8899      key: "beforeFit",
8900      value: function beforeFit() {
8901        callback(this.options.beforeFit, [this]);
8902      }
8903    }, {
8904      key: "fit",
8905      value: function fit() {
8906        var me = this;
8907        var minSize = {
8908          width: 0,
8909          height: 0
8910        };
8911        var chart = me.chart,
8912            _me$options2 = me.options,
8913            tickOpts = _me$options2.ticks,
8914            titleOpts = _me$options2.title,
8915            gridOpts = _me$options2.grid;
8916
8917        var display = me._isVisible();
8918
8919        var isHorizontal = me.isHorizontal();
8920
8921        if (display) {
8922          var titleHeight = getTitleHeight(titleOpts, chart.options.font);
8923
8924          if (isHorizontal) {
8925            minSize.width = me.maxWidth;
8926            minSize.height = getTickMarkLength(gridOpts) + titleHeight;
8927          } else {
8928            minSize.height = me.maxHeight;
8929            minSize.width = getTickMarkLength(gridOpts) + titleHeight;
8930          }
8931
8932          if (tickOpts.display && me.ticks.length) {
8933            var _me$_getLabelSizes = me._getLabelSizes(),
8934                first = _me$_getLabelSizes.first,
8935                last = _me$_getLabelSizes.last,
8936                widest = _me$_getLabelSizes.widest,
8937                highest = _me$_getLabelSizes.highest;
8938
8939            var tickPadding = tickOpts.padding * 2;
8940            var angleRadians = toRadians(me.labelRotation);
8941            var cos = Math.cos(angleRadians);
8942            var sin = Math.sin(angleRadians);
8943
8944            if (isHorizontal) {
8945              var labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;
8946              minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
8947            } else {
8948              var labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;
8949              minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth + tickPadding);
8950            }
8951
8952            me._calculatePadding(first, last, sin, cos);
8953          }
8954        }
8955
8956        me._handleMargins();
8957
8958        if (isHorizontal) {
8959          me.width = me._length = chart.width - me._margins.left - me._margins.right;
8960          me.height = minSize.height;
8961        } else {
8962          me.width = minSize.width;
8963          me.height = me._length = chart.height - me._margins.top - me._margins.bottom;
8964        }
8965      }
8966    }, {
8967      key: "_calculatePadding",
8968      value: function _calculatePadding(first, last, sin, cos) {
8969        var me = this;
8970        var _me$options3 = me.options,
8971            _me$options3$ticks = _me$options3.ticks,
8972            align = _me$options3$ticks.align,
8973            padding = _me$options3$ticks.padding,
8974            position = _me$options3.position;
8975        var isRotated = me.labelRotation !== 0;
8976        var labelsBelowTicks = position !== 'top' && me.axis === 'x';
8977
8978        if (me.isHorizontal()) {
8979          var offsetLeft = me.getPixelForTick(0) - me.left;
8980          var offsetRight = me.right - me.getPixelForTick(me.ticks.length - 1);
8981          var paddingLeft = 0;
8982          var paddingRight = 0;
8983
8984          if (isRotated) {
8985            if (labelsBelowTicks) {
8986              paddingLeft = cos * first.width;
8987              paddingRight = sin * last.height;
8988            } else {
8989              paddingLeft = sin * first.height;
8990              paddingRight = cos * last.width;
8991            }
8992          } else if (align === 'start') {
8993            paddingRight = last.width;
8994          } else if (align === 'end') {
8995            paddingLeft = first.width;
8996          } else {
8997            paddingLeft = first.width / 2;
8998            paddingRight = last.width / 2;
8999          }
9000
9001          me.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * me.width / (me.width - offsetLeft), 0);
9002          me.paddingRight = Math.max((paddingRight - offsetRight + padding) * me.width / (me.width - offsetRight), 0);
9003        } else {
9004          var paddingTop = last.height / 2;
9005          var paddingBottom = first.height / 2;
9006
9007          if (align === 'start') {
9008            paddingTop = 0;
9009            paddingBottom = first.height;
9010          } else if (align === 'end') {
9011            paddingTop = last.height;
9012            paddingBottom = 0;
9013          }
9014
9015          me.paddingTop = paddingTop + padding;
9016          me.paddingBottom = paddingBottom + padding;
9017        }
9018      }
9019    }, {
9020      key: "_handleMargins",
9021      value: function _handleMargins() {
9022        var me = this;
9023
9024        if (me._margins) {
9025          me._margins.left = Math.max(me.paddingLeft, me._margins.left);
9026          me._margins.top = Math.max(me.paddingTop, me._margins.top);
9027          me._margins.right = Math.max(me.paddingRight, me._margins.right);
9028          me._margins.bottom = Math.max(me.paddingBottom, me._margins.bottom);
9029        }
9030      }
9031    }, {
9032      key: "afterFit",
9033      value: function afterFit() {
9034        callback(this.options.afterFit, [this]);
9035      }
9036    }, {
9037      key: "isHorizontal",
9038      value: function isHorizontal() {
9039        var _this$options = this.options,
9040            axis = _this$options.axis,
9041            position = _this$options.position;
9042        return position === 'top' || position === 'bottom' || axis === 'x';
9043      }
9044    }, {
9045      key: "isFullSize",
9046      value: function isFullSize() {
9047        return this.options.fullSize;
9048      }
9049    }, {
9050      key: "_convertTicksToLabels",
9051      value: function _convertTicksToLabels(ticks) {
9052        var me = this;
9053        me.beforeTickToLabelConversion();
9054        me.generateTickLabels(ticks);
9055        var i, ilen;
9056
9057        for (i = 0, ilen = ticks.length; i < ilen; i++) {
9058          if (isNullOrUndef(ticks[i].label)) {
9059            ticks.splice(i, 1);
9060            ilen--;
9061            i--;
9062          }
9063        }
9064
9065        me.afterTickToLabelConversion();
9066      }
9067    }, {
9068      key: "_getLabelSizes",
9069      value: function _getLabelSizes() {
9070        var me = this;
9071        var labelSizes = me._labelSizes;
9072
9073        if (!labelSizes) {
9074          var sampleSize = me.options.ticks.sampleSize;
9075          var ticks = me.ticks;
9076
9077          if (sampleSize < ticks.length) {
9078            ticks = sample(ticks, sampleSize);
9079          }
9080
9081          me._labelSizes = labelSizes = me._computeLabelSizes(ticks, ticks.length);
9082        }
9083
9084        return labelSizes;
9085      }
9086    }, {
9087      key: "_computeLabelSizes",
9088      value: function _computeLabelSizes(ticks, length) {
9089        var ctx = this.ctx,
9090            caches = this._longestTextCache;
9091        var widths = [];
9092        var heights = [];
9093        var widestLabelSize = 0;
9094        var highestLabelSize = 0;
9095        var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;
9096
9097        for (i = 0; i < length; ++i) {
9098          label = ticks[i].label;
9099          tickFont = this._resolveTickFontOptions(i);
9100          ctx.font = fontString = tickFont.string;
9101          cache = caches[fontString] = caches[fontString] || {
9102            data: {},
9103            gc: []
9104          };
9105          lineHeight = tickFont.lineHeight;
9106          width = height = 0;
9107
9108          if (!isNullOrUndef(label) && !isArray(label)) {
9109            width = _measureText(ctx, cache.data, cache.gc, width, label);
9110            height = lineHeight;
9111          } else if (isArray(label)) {
9112            for (j = 0, jlen = label.length; j < jlen; ++j) {
9113              nestedLabel = label[j];
9114
9115              if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
9116                width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);
9117                height += lineHeight;
9118              }
9119            }
9120          }
9121
9122          widths.push(width);
9123          heights.push(height);
9124          widestLabelSize = Math.max(width, widestLabelSize);
9125          highestLabelSize = Math.max(height, highestLabelSize);
9126        }
9127
9128        garbageCollect(caches, length);
9129        var widest = widths.indexOf(widestLabelSize);
9130        var highest = heights.indexOf(highestLabelSize);
9131
9132        var valueAt = function valueAt(idx) {
9133          return {
9134            width: widths[idx] || 0,
9135            height: heights[idx] || 0
9136          };
9137        };
9138
9139        return {
9140          first: valueAt(0),
9141          last: valueAt(length - 1),
9142          widest: valueAt(widest),
9143          highest: valueAt(highest),
9144          widths: widths,
9145          heights: heights
9146        };
9147      }
9148    }, {
9149      key: "getLabelForValue",
9150      value: function getLabelForValue(value) {
9151        return value;
9152      }
9153    }, {
9154      key: "getPixelForValue",
9155      value: function getPixelForValue(value, index) {
9156        return NaN;
9157      }
9158    }, {
9159      key: "getValueForPixel",
9160      value: function getValueForPixel(pixel) {}
9161    }, {
9162      key: "getPixelForTick",
9163      value: function getPixelForTick(index) {
9164        var ticks = this.ticks;
9165
9166        if (index < 0 || index > ticks.length - 1) {
9167          return null;
9168        }
9169
9170        return this.getPixelForValue(ticks[index].value);
9171      }
9172    }, {
9173      key: "getPixelForDecimal",
9174      value: function getPixelForDecimal(decimal) {
9175        var me = this;
9176
9177        if (me._reversePixels) {
9178          decimal = 1 - decimal;
9179        }
9180
9181        var pixel = me._startPixel + decimal * me._length;
9182        return _int16Range(me._alignToPixels ? _alignPixel(me.chart, pixel, 0) : pixel);
9183      }
9184    }, {
9185      key: "getDecimalForPixel",
9186      value: function getDecimalForPixel(pixel) {
9187        var decimal = (pixel - this._startPixel) / this._length;
9188        return this._reversePixels ? 1 - decimal : decimal;
9189      }
9190    }, {
9191      key: "getBasePixel",
9192      value: function getBasePixel() {
9193        return this.getPixelForValue(this.getBaseValue());
9194      }
9195    }, {
9196      key: "getBaseValue",
9197      value: function getBaseValue() {
9198        var min = this.min,
9199            max = this.max;
9200        return min < 0 && max < 0 ? max : min > 0 && max > 0 ? min : 0;
9201      }
9202    }, {
9203      key: "getContext",
9204      value: function getContext(index) {
9205        var me = this;
9206        var ticks = me.ticks || [];
9207
9208        if (index >= 0 && index < ticks.length) {
9209          var tick = ticks[index];
9210          return tick.$context || (tick.$context = createTickContext(me.getContext(), index, tick));
9211        }
9212
9213        return me.$context || (me.$context = createScaleContext(me.chart.getContext(), me));
9214      }
9215    }, {
9216      key: "_tickSize",
9217      value: function _tickSize() {
9218        var me = this;
9219        var optionTicks = me.options.ticks;
9220        var rot = toRadians(me.labelRotation);
9221        var cos = Math.abs(Math.cos(rot));
9222        var sin = Math.abs(Math.sin(rot));
9223
9224        var labelSizes = me._getLabelSizes();
9225
9226        var padding = optionTicks.autoSkipPadding || 0;
9227        var w = labelSizes ? labelSizes.widest.width + padding : 0;
9228        var h = labelSizes ? labelSizes.highest.height + padding : 0;
9229        return me.isHorizontal() ? h * cos > w * sin ? w / cos : h / sin : h * sin < w * cos ? h / cos : w / sin;
9230      }
9231    }, {
9232      key: "_isVisible",
9233      value: function _isVisible() {
9234        var display = this.options.display;
9235
9236        if (display !== 'auto') {
9237          return !!display;
9238        }
9239
9240        return this.getMatchingVisibleMetas().length > 0;
9241      }
9242    }, {
9243      key: "_computeGridLineItems",
9244      value: function _computeGridLineItems(chartArea) {
9245        var me = this;
9246        var axis = me.axis;
9247        var chart = me.chart;
9248        var options = me.options;
9249        var grid = options.grid,
9250            position = options.position;
9251        var offset = grid.offset;
9252        var isHorizontal = me.isHorizontal();
9253        var ticks = me.ticks;
9254        var ticksLength = ticks.length + (offset ? 1 : 0);
9255        var tl = getTickMarkLength(grid);
9256        var items = [];
9257        var borderOpts = grid.setContext(me.getContext());
9258        var axisWidth = borderOpts.drawBorder ? borderOpts.borderWidth : 0;
9259        var axisHalfWidth = axisWidth / 2;
9260
9261        var alignBorderValue = function alignBorderValue(pixel) {
9262          return _alignPixel(chart, pixel, axisWidth);
9263        };
9264
9265        var borderValue, i, lineValue, alignedLineValue;
9266        var tx1, ty1, tx2, ty2, x1, y1, x2, y2;
9267
9268        if (position === 'top') {
9269          borderValue = alignBorderValue(me.bottom);
9270          ty1 = me.bottom - tl;
9271          ty2 = borderValue - axisHalfWidth;
9272          y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
9273          y2 = chartArea.bottom;
9274        } else if (position === 'bottom') {
9275          borderValue = alignBorderValue(me.top);
9276          y1 = chartArea.top;
9277          y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
9278          ty1 = borderValue + axisHalfWidth;
9279          ty2 = me.top + tl;
9280        } else if (position === 'left') {
9281          borderValue = alignBorderValue(me.right);
9282          tx1 = me.right - tl;
9283          tx2 = borderValue - axisHalfWidth;
9284          x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
9285          x2 = chartArea.right;
9286        } else if (position === 'right') {
9287          borderValue = alignBorderValue(me.left);
9288          x1 = chartArea.left;
9289          x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
9290          tx1 = borderValue + axisHalfWidth;
9291          tx2 = me.left + tl;
9292        } else if (axis === 'x') {
9293          if (position === 'center') {
9294            borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);
9295          } else if (isObject(position)) {
9296            var positionAxisID = Object.keys(position)[0];
9297            var value = position[positionAxisID];
9298            borderValue = alignBorderValue(me.chart.scales[positionAxisID].getPixelForValue(value));
9299          }
9300
9301          y1 = chartArea.top;
9302          y2 = chartArea.bottom;
9303          ty1 = borderValue + axisHalfWidth;
9304          ty2 = ty1 + tl;
9305        } else if (axis === 'y') {
9306          if (position === 'center') {
9307            borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
9308          } else if (isObject(position)) {
9309            var _positionAxisID = Object.keys(position)[0];
9310            var _value = position[_positionAxisID];
9311            borderValue = alignBorderValue(me.chart.scales[_positionAxisID].getPixelForValue(_value));
9312          }
9313
9314          tx1 = borderValue - axisHalfWidth;
9315          tx2 = tx1 - tl;
9316          x1 = chartArea.left;
9317          x2 = chartArea.right;
9318        }
9319
9320        var limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength);
9321        var step = Math.max(1, Math.ceil(ticksLength / limit));
9322
9323        for (i = 0; i < ticksLength; i += step) {
9324          var optsAtIndex = grid.setContext(me.getContext(i));
9325          var lineWidth = optsAtIndex.lineWidth;
9326          var lineColor = optsAtIndex.color;
9327          var borderDash = grid.borderDash || [];
9328          var borderDashOffset = optsAtIndex.borderDashOffset;
9329          var tickWidth = optsAtIndex.tickWidth;
9330          var tickColor = optsAtIndex.tickColor;
9331          var tickBorderDash = optsAtIndex.tickBorderDash || [];
9332          var tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;
9333          lineValue = getPixelForGridLine(me, i, offset);
9334
9335          if (lineValue === undefined) {
9336            continue;
9337          }
9338
9339          alignedLineValue = _alignPixel(chart, lineValue, lineWidth);
9340
9341          if (isHorizontal) {
9342            tx1 = tx2 = x1 = x2 = alignedLineValue;
9343          } else {
9344            ty1 = ty2 = y1 = y2 = alignedLineValue;
9345          }
9346
9347          items.push({
9348            tx1: tx1,
9349            ty1: ty1,
9350            tx2: tx2,
9351            ty2: ty2,
9352            x1: x1,
9353            y1: y1,
9354            x2: x2,
9355            y2: y2,
9356            width: lineWidth,
9357            color: lineColor,
9358            borderDash: borderDash,
9359            borderDashOffset: borderDashOffset,
9360            tickWidth: tickWidth,
9361            tickColor: tickColor,
9362            tickBorderDash: tickBorderDash,
9363            tickBorderDashOffset: tickBorderDashOffset
9364          });
9365        }
9366
9367        me._ticksLength = ticksLength;
9368        me._borderValue = borderValue;
9369        return items;
9370      }
9371    }, {
9372      key: "_computeLabelItems",
9373      value: function _computeLabelItems(chartArea) {
9374        var me = this;
9375        var axis = me.axis;
9376        var options = me.options;
9377        var position = options.position,
9378            optionTicks = options.ticks;
9379        var isHorizontal = me.isHorizontal();
9380        var ticks = me.ticks;
9381        var align = optionTicks.align,
9382            crossAlign = optionTicks.crossAlign,
9383            padding = optionTicks.padding,
9384            mirror = optionTicks.mirror;
9385        var tl = getTickMarkLength(options.grid);
9386        var tickAndPadding = tl + padding;
9387        var hTickAndPadding = mirror ? -padding : tickAndPadding;
9388        var rotation = -toRadians(me.labelRotation);
9389        var items = [];
9390        var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
9391        var textBaseline = 'middle';
9392
9393        if (position === 'top') {
9394          y = me.bottom - hTickAndPadding;
9395          textAlign = me._getXAxisLabelAlignment();
9396        } else if (position === 'bottom') {
9397          y = me.top + hTickAndPadding;
9398          textAlign = me._getXAxisLabelAlignment();
9399        } else if (position === 'left') {
9400          var ret = me._getYAxisLabelAlignment(tl);
9401
9402          textAlign = ret.textAlign;
9403          x = ret.x;
9404        } else if (position === 'right') {
9405          var _ret = me._getYAxisLabelAlignment(tl);
9406
9407          textAlign = _ret.textAlign;
9408          x = _ret.x;
9409        } else if (axis === 'x') {
9410          if (position === 'center') {
9411            y = (chartArea.top + chartArea.bottom) / 2 + tickAndPadding;
9412          } else if (isObject(position)) {
9413            var positionAxisID = Object.keys(position)[0];
9414            var value = position[positionAxisID];
9415            y = me.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;
9416          }
9417
9418          textAlign = me._getXAxisLabelAlignment();
9419        } else if (axis === 'y') {
9420          if (position === 'center') {
9421            x = (chartArea.left + chartArea.right) / 2 - tickAndPadding;
9422          } else if (isObject(position)) {
9423            var _positionAxisID2 = Object.keys(position)[0];
9424            var _value2 = position[_positionAxisID2];
9425            x = me.chart.scales[_positionAxisID2].getPixelForValue(_value2);
9426          }
9427
9428          textAlign = me._getYAxisLabelAlignment(tl).textAlign;
9429        }
9430
9431        if (axis === 'y') {
9432          if (align === 'start') {
9433            textBaseline = 'top';
9434          } else if (align === 'end') {
9435            textBaseline = 'bottom';
9436          }
9437        }
9438
9439        var labelSizes = me._getLabelSizes();
9440
9441        for (i = 0, ilen = ticks.length; i < ilen; ++i) {
9442          tick = ticks[i];
9443          label = tick.label;
9444          var optsAtIndex = optionTicks.setContext(me.getContext(i));
9445          pixel = me.getPixelForTick(i) + optionTicks.labelOffset;
9446          font = me._resolveTickFontOptions(i);
9447          lineHeight = font.lineHeight;
9448          lineCount = isArray(label) ? label.length : 1;
9449          var halfCount = lineCount / 2;
9450          var color = optsAtIndex.color;
9451          var strokeColor = optsAtIndex.textStrokeColor;
9452          var strokeWidth = optsAtIndex.textStrokeWidth;
9453
9454          if (isHorizontal) {
9455            x = pixel;
9456
9457            if (position === 'top') {
9458              if (crossAlign === 'near' || rotation !== 0) {
9459                textOffset = -lineCount * lineHeight + lineHeight / 2;
9460              } else if (crossAlign === 'center') {
9461                textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;
9462              } else {
9463                textOffset = -labelSizes.highest.height + lineHeight / 2;
9464              }
9465            } else {
9466              if (crossAlign === 'near' || rotation !== 0) {
9467                textOffset = lineHeight / 2;
9468              } else if (crossAlign === 'center') {
9469                textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;
9470              } else {
9471                textOffset = labelSizes.highest.height - lineCount * lineHeight;
9472              }
9473            }
9474
9475            if (mirror) {
9476              textOffset *= -1;
9477            }
9478          } else {
9479            y = pixel;
9480            textOffset = (1 - lineCount) * lineHeight / 2;
9481          }
9482
9483          var backdrop = void 0;
9484
9485          if (optsAtIndex.showLabelBackdrop) {
9486            var labelPadding = toPadding(optsAtIndex.backdropPadding);
9487            var height = labelSizes.heights[i];
9488            var width = labelSizes.widths[i];
9489            var top = y + textOffset - labelPadding.top;
9490            var left = x - labelPadding.left;
9491
9492            switch (textBaseline) {
9493              case 'middle':
9494                top -= height / 2;
9495                break;
9496
9497              case 'bottom':
9498                top -= height;
9499                break;
9500            }
9501
9502            switch (textAlign) {
9503              case 'center':
9504                left -= width / 2;
9505                break;
9506
9507              case 'right':
9508                left -= width;
9509                break;
9510            }
9511
9512            backdrop = {
9513              left: left,
9514              top: top,
9515              width: width + labelPadding.width,
9516              height: height + labelPadding.height,
9517              color: optsAtIndex.backdropColor
9518            };
9519          }
9520
9521          items.push({
9522            rotation: rotation,
9523            label: label,
9524            font: font,
9525            color: color,
9526            strokeColor: strokeColor,
9527            strokeWidth: strokeWidth,
9528            textOffset: textOffset,
9529            textAlign: textAlign,
9530            textBaseline: textBaseline,
9531            translation: [x, y],
9532            backdrop: backdrop
9533          });
9534        }
9535
9536        return items;
9537      }
9538    }, {
9539      key: "_getXAxisLabelAlignment",
9540      value: function _getXAxisLabelAlignment() {
9541        var me = this;
9542        var _me$options4 = me.options,
9543            position = _me$options4.position,
9544            ticks = _me$options4.ticks;
9545        var rotation = -toRadians(me.labelRotation);
9546
9547        if (rotation) {
9548          return position === 'top' ? 'left' : 'right';
9549        }
9550
9551        var align = 'center';
9552
9553        if (ticks.align === 'start') {
9554          align = 'left';
9555        } else if (ticks.align === 'end') {
9556          align = 'right';
9557        }
9558
9559        return align;
9560      }
9561    }, {
9562      key: "_getYAxisLabelAlignment",
9563      value: function _getYAxisLabelAlignment(tl) {
9564        var me = this;
9565        var _me$options5 = me.options,
9566            position = _me$options5.position,
9567            _me$options5$ticks = _me$options5.ticks,
9568            crossAlign = _me$options5$ticks.crossAlign,
9569            mirror = _me$options5$ticks.mirror,
9570            padding = _me$options5$ticks.padding;
9571
9572        var labelSizes = me._getLabelSizes();
9573
9574        var tickAndPadding = tl + padding;
9575        var widest = labelSizes.widest.width;
9576        var textAlign;
9577        var x;
9578
9579        if (position === 'left') {
9580          if (mirror) {
9581            textAlign = 'left';
9582            x = me.right + padding;
9583          } else {
9584            x = me.right - tickAndPadding;
9585
9586            if (crossAlign === 'near') {
9587              textAlign = 'right';
9588            } else if (crossAlign === 'center') {
9589              textAlign = 'center';
9590              x -= widest / 2;
9591            } else {
9592              textAlign = 'left';
9593              x = me.left;
9594            }
9595          }
9596        } else if (position === 'right') {
9597          if (mirror) {
9598            textAlign = 'right';
9599            x = me.left + padding;
9600          } else {
9601            x = me.left + tickAndPadding;
9602
9603            if (crossAlign === 'near') {
9604              textAlign = 'left';
9605            } else if (crossAlign === 'center') {
9606              textAlign = 'center';
9607              x += widest / 2;
9608            } else {
9609              textAlign = 'right';
9610              x = me.right;
9611            }
9612          }
9613        } else {
9614          textAlign = 'right';
9615        }
9616
9617        return {
9618          textAlign: textAlign,
9619          x: x
9620        };
9621      }
9622    }, {
9623      key: "_computeLabelArea",
9624      value: function _computeLabelArea() {
9625        var me = this;
9626
9627        if (me.options.ticks.mirror) {
9628          return;
9629        }
9630
9631        var chart = me.chart;
9632        var position = me.options.position;
9633
9634        if (position === 'left' || position === 'right') {
9635          return {
9636            top: 0,
9637            left: me.left,
9638            bottom: chart.height,
9639            right: me.right
9640          };
9641        }
9642
9643        if (position === 'top' || position === 'bottom') {
9644          return {
9645            top: me.top,
9646            left: 0,
9647            bottom: me.bottom,
9648            right: chart.width
9649          };
9650        }
9651      }
9652    }, {
9653      key: "drawBackground",
9654      value: function drawBackground() {
9655        var ctx = this.ctx,
9656            backgroundColor = this.options.backgroundColor,
9657            left = this.left,
9658            top = this.top,
9659            width = this.width,
9660            height = this.height;
9661
9662        if (backgroundColor) {
9663          ctx.save();
9664          ctx.fillStyle = backgroundColor;
9665          ctx.fillRect(left, top, width, height);
9666          ctx.restore();
9667        }
9668      }
9669    }, {
9670      key: "getLineWidthForValue",
9671      value: function getLineWidthForValue(value) {
9672        var me = this;
9673        var grid = me.options.grid;
9674
9675        if (!me._isVisible() || !grid.display) {
9676          return 0;
9677        }
9678
9679        var ticks = me.ticks;
9680        var index = ticks.findIndex(function (t) {
9681          return t.value === value;
9682        });
9683
9684        if (index >= 0) {
9685          var opts = grid.setContext(me.getContext(index));
9686          return opts.lineWidth;
9687        }
9688
9689        return 0;
9690      }
9691    }, {
9692      key: "drawGrid",
9693      value: function drawGrid(chartArea) {
9694        var me = this;
9695        var grid = me.options.grid;
9696        var ctx = me.ctx;
9697
9698        var items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
9699
9700        var i, ilen;
9701
9702        var drawLine = function drawLine(p1, p2, style) {
9703          if (!style.width || !style.color) {
9704            return;
9705          }
9706
9707          ctx.save();
9708          ctx.lineWidth = style.width;
9709          ctx.strokeStyle = style.color;
9710          ctx.setLineDash(style.borderDash || []);
9711          ctx.lineDashOffset = style.borderDashOffset;
9712          ctx.beginPath();
9713          ctx.moveTo(p1.x, p1.y);
9714          ctx.lineTo(p2.x, p2.y);
9715          ctx.stroke();
9716          ctx.restore();
9717        };
9718
9719        if (grid.display) {
9720          for (i = 0, ilen = items.length; i < ilen; ++i) {
9721            var item = items[i];
9722
9723            if (grid.drawOnChartArea) {
9724              drawLine({
9725                x: item.x1,
9726                y: item.y1
9727              }, {
9728                x: item.x2,
9729                y: item.y2
9730              }, item);
9731            }
9732
9733            if (grid.drawTicks) {
9734              drawLine({
9735                x: item.tx1,
9736                y: item.ty1
9737              }, {
9738                x: item.tx2,
9739                y: item.ty2
9740              }, {
9741                color: item.tickColor,
9742                width: item.tickWidth,
9743                borderDash: item.tickBorderDash,
9744                borderDashOffset: item.tickBorderDashOffset
9745              });
9746            }
9747          }
9748        }
9749      }
9750    }, {
9751      key: "drawBorder",
9752      value: function drawBorder() {
9753        var me = this;
9754        var chart = me.chart,
9755            ctx = me.ctx,
9756            grid = me.options.grid;
9757        var borderOpts = grid.setContext(me.getContext());
9758        var axisWidth = grid.drawBorder ? borderOpts.borderWidth : 0;
9759
9760        if (!axisWidth) {
9761          return;
9762        }
9763
9764        var lastLineWidth = grid.setContext(me.getContext(0)).lineWidth;
9765        var borderValue = me._borderValue;
9766        var x1, x2, y1, y2;
9767
9768        if (me.isHorizontal()) {
9769          x1 = _alignPixel(chart, me.left, axisWidth) - axisWidth / 2;
9770          x2 = _alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
9771          y1 = y2 = borderValue;
9772        } else {
9773          y1 = _alignPixel(chart, me.top, axisWidth) - axisWidth / 2;
9774          y2 = _alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
9775          x1 = x2 = borderValue;
9776        }
9777
9778        ctx.save();
9779        ctx.lineWidth = borderOpts.borderWidth;
9780        ctx.strokeStyle = borderOpts.borderColor;
9781        ctx.beginPath();
9782        ctx.moveTo(x1, y1);
9783        ctx.lineTo(x2, y2);
9784        ctx.stroke();
9785        ctx.restore();
9786      }
9787    }, {
9788      key: "drawLabels",
9789      value: function drawLabels(chartArea) {
9790        var me = this;
9791        var optionTicks = me.options.ticks;
9792
9793        if (!optionTicks.display) {
9794          return;
9795        }
9796
9797        var ctx = me.ctx;
9798
9799        var area = me._computeLabelArea();
9800
9801        if (area) {
9802          clipArea(ctx, area);
9803        }
9804
9805        var items = me._labelItems || (me._labelItems = me._computeLabelItems(chartArea));
9806
9807        var i, ilen;
9808
9809        for (i = 0, ilen = items.length; i < ilen; ++i) {
9810          var item = items[i];
9811          var tickFont = item.font;
9812          var label = item.label;
9813
9814          if (item.backdrop) {
9815            ctx.fillStyle = item.backdrop.color;
9816            ctx.fillRect(item.backdrop.left, item.backdrop.top, item.backdrop.width, item.backdrop.height);
9817          }
9818
9819          var y = item.textOffset;
9820          renderText(ctx, label, 0, y, tickFont, item);
9821        }
9822
9823        if (area) {
9824          unclipArea(ctx);
9825        }
9826      }
9827    }, {
9828      key: "drawTitle",
9829      value: function drawTitle() {
9830        var ctx = this.ctx,
9831            _this$options2 = this.options,
9832            position = _this$options2.position,
9833            title = _this$options2.title,
9834            reverse = _this$options2.reverse;
9835
9836        if (!title.display) {
9837          return;
9838        }
9839
9840        var font = toFont(title.font);
9841        var padding = toPadding(title.padding);
9842        var align = title.align;
9843        var offset = font.lineHeight / 2;
9844
9845        if (position === 'bottom') {
9846          offset += padding.bottom;
9847
9848          if (isArray(title.text)) {
9849            offset += font.lineHeight * (title.text.length - 1);
9850          }
9851        } else {
9852          offset += padding.top;
9853        }
9854
9855        var _titleArgs = titleArgs(this, offset, position, align),
9856            titleX = _titleArgs.titleX,
9857            titleY = _titleArgs.titleY,
9858            maxWidth = _titleArgs.maxWidth,
9859            rotation = _titleArgs.rotation;
9860
9861        renderText(ctx, title.text, 0, 0, font, {
9862          color: title.color,
9863          maxWidth: maxWidth,
9864          rotation: rotation,
9865          textAlign: titleAlign(align, position, reverse),
9866          textBaseline: 'middle',
9867          translation: [titleX, titleY]
9868        });
9869      }
9870    }, {
9871      key: "draw",
9872      value: function draw(chartArea) {
9873        var me = this;
9874
9875        if (!me._isVisible()) {
9876          return;
9877        }
9878
9879        me.drawBackground();
9880        me.drawGrid(chartArea);
9881        me.drawBorder();
9882        me.drawTitle();
9883        me.drawLabels(chartArea);
9884      }
9885    }, {
9886      key: "_layers",
9887      value: function _layers() {
9888        var me = this;
9889        var opts = me.options;
9890        var tz = opts.ticks && opts.ticks.z || 0;
9891        var gz = opts.grid && opts.grid.z || 0;
9892
9893        if (!me._isVisible() || me.draw !== Scale.prototype.draw) {
9894          return [{
9895            z: tz,
9896            draw: function draw(chartArea) {
9897              me.draw(chartArea);
9898            }
9899          }];
9900        }
9901
9902        return [{
9903          z: gz,
9904          draw: function draw(chartArea) {
9905            me.drawBackground();
9906            me.drawGrid(chartArea);
9907            me.drawTitle();
9908          }
9909        }, {
9910          z: gz + 1,
9911          draw: function draw() {
9912            me.drawBorder();
9913          }
9914        }, {
9915          z: tz,
9916          draw: function draw(chartArea) {
9917            me.drawLabels(chartArea);
9918          }
9919        }];
9920      }
9921    }, {
9922      key: "getMatchingVisibleMetas",
9923      value: function getMatchingVisibleMetas(type) {
9924        var me = this;
9925        var metas = me.chart.getSortedVisibleDatasetMetas();
9926        var axisID = me.axis + 'AxisID';
9927        var result = [];
9928        var i, ilen;
9929
9930        for (i = 0, ilen = metas.length; i < ilen; ++i) {
9931          var meta = metas[i];
9932
9933          if (meta[axisID] === me.id && (!type || meta.type === type)) {
9934            result.push(meta);
9935          }
9936        }
9937
9938        return result;
9939      }
9940    }, {
9941      key: "_resolveTickFontOptions",
9942      value: function _resolveTickFontOptions(index) {
9943        var opts = this.options.ticks.setContext(this.getContext(index));
9944        return toFont(opts.font);
9945      }
9946    }, {
9947      key: "_maxDigits",
9948      value: function _maxDigits() {
9949        var me = this;
9950
9951        var fontSize = me._resolveTickFontOptions(0).lineHeight;
9952
9953        return (me.isHorizontal() ? me.width : me.height) / fontSize;
9954      }
9955    }]);
9956
9957    return Scale;
9958  }(Element);
9959
9960  var TypedRegistry = /*#__PURE__*/function () {
9961    function TypedRegistry(type, scope, override) {
9962      _classCallCheck(this, TypedRegistry);
9963
9964      this.type = type;
9965      this.scope = scope;
9966      this.override = override;
9967      this.items = Object.create(null);
9968    }
9969
9970    _createClass(TypedRegistry, [{
9971      key: "isForType",
9972      value: function isForType(type) {
9973        return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);
9974      }
9975    }, {
9976      key: "register",
9977      value: function register(item) {
9978        var me = this;
9979        var proto = Object.getPrototypeOf(item);
9980        var parentScope;
9981
9982        if (isIChartComponent(proto)) {
9983          parentScope = me.register(proto);
9984        }
9985
9986        var items = me.items;
9987        var id = item.id;
9988        var scope = me.scope + '.' + id;
9989
9990        if (!id) {
9991          throw new Error('class does not have id: ' + item);
9992        }
9993
9994        if (id in items) {
9995          return scope;
9996        }
9997
9998        items[id] = item;
9999        registerDefaults(item, scope, parentScope);
10000
10001        if (me.override) {
10002          defaults.override(item.id, item.overrides);
10003        }
10004
10005        return scope;
10006      }
10007    }, {
10008      key: "get",
10009      value: function get(id) {
10010        return this.items[id];
10011      }
10012    }, {
10013      key: "unregister",
10014      value: function unregister(item) {
10015        var items = this.items;
10016        var id = item.id;
10017        var scope = this.scope;
10018
10019        if (id in items) {
10020          delete items[id];
10021        }
10022
10023        if (scope && id in defaults[scope]) {
10024          delete defaults[scope][id];
10025
10026          if (this.override) {
10027            delete overrides[id];
10028          }
10029        }
10030      }
10031    }]);
10032
10033    return TypedRegistry;
10034  }();
10035
10036  function registerDefaults(item, scope, parentScope) {
10037    var itemDefaults = merge(Object.create(null), [parentScope ? defaults.get(parentScope) : {}, defaults.get(scope), item.defaults]);
10038    defaults.set(scope, itemDefaults);
10039
10040    if (item.defaultRoutes) {
10041      routeDefaults(scope, item.defaultRoutes);
10042    }
10043
10044    if (item.descriptors) {
10045      defaults.describe(scope, item.descriptors);
10046    }
10047  }
10048
10049  function routeDefaults(scope, routes) {
10050    Object.keys(routes).forEach(function (property) {
10051      var propertyParts = property.split('.');
10052      var sourceName = propertyParts.pop();
10053      var sourceScope = [scope].concat(propertyParts).join('.');
10054      var parts = routes[property].split('.');
10055      var targetName = parts.pop();
10056      var targetScope = parts.join('.');
10057      defaults.route(sourceScope, sourceName, targetScope, targetName);
10058    });
10059  }
10060
10061  function isIChartComponent(proto) {
10062    return 'id' in proto && 'defaults' in proto;
10063  }
10064
10065  var Registry = /*#__PURE__*/function () {
10066    function Registry() {
10067      _classCallCheck(this, Registry);
10068
10069      this.controllers = new TypedRegistry(DatasetController, 'datasets', true);
10070      this.elements = new TypedRegistry(Element, 'elements');
10071      this.plugins = new TypedRegistry(Object, 'plugins');
10072      this.scales = new TypedRegistry(Scale, 'scales');
10073      this._typedRegistries = [this.controllers, this.scales, this.elements];
10074    }
10075
10076    _createClass(Registry, [{
10077      key: "add",
10078      value: function add() {
10079        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
10080          args[_key] = arguments[_key];
10081        }
10082
10083        this._each('register', args);
10084      }
10085    }, {
10086      key: "remove",
10087      value: function remove() {
10088        for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
10089          args[_key2] = arguments[_key2];
10090        }
10091
10092        this._each('unregister', args);
10093      }
10094    }, {
10095      key: "addControllers",
10096      value: function addControllers() {
10097        for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
10098          args[_key3] = arguments[_key3];
10099        }
10100
10101        this._each('register', args, this.controllers);
10102      }
10103    }, {
10104      key: "addElements",
10105      value: function addElements() {
10106        for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
10107          args[_key4] = arguments[_key4];
10108        }
10109
10110        this._each('register', args, this.elements);
10111      }
10112    }, {
10113      key: "addPlugins",
10114      value: function addPlugins() {
10115        for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
10116          args[_key5] = arguments[_key5];
10117        }
10118
10119        this._each('register', args, this.plugins);
10120      }
10121    }, {
10122      key: "addScales",
10123      value: function addScales() {
10124        for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
10125          args[_key6] = arguments[_key6];
10126        }
10127
10128        this._each('register', args, this.scales);
10129      }
10130    }, {
10131      key: "getController",
10132      value: function getController(id) {
10133        return this._get(id, this.controllers, 'controller');
10134      }
10135    }, {
10136      key: "getElement",
10137      value: function getElement(id) {
10138        return this._get(id, this.elements, 'element');
10139      }
10140    }, {
10141      key: "getPlugin",
10142      value: function getPlugin(id) {
10143        return this._get(id, this.plugins, 'plugin');
10144      }
10145    }, {
10146      key: "getScale",
10147      value: function getScale(id) {
10148        return this._get(id, this.scales, 'scale');
10149      }
10150    }, {
10151      key: "removeControllers",
10152      value: function removeControllers() {
10153        for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
10154          args[_key7] = arguments[_key7];
10155        }
10156
10157        this._each('unregister', args, this.controllers);
10158      }
10159    }, {
10160      key: "removeElements",
10161      value: function removeElements() {
10162        for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
10163          args[_key8] = arguments[_key8];
10164        }
10165
10166        this._each('unregister', args, this.elements);
10167      }
10168    }, {
10169      key: "removePlugins",
10170      value: function removePlugins() {
10171        for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
10172          args[_key9] = arguments[_key9];
10173        }
10174
10175        this._each('unregister', args, this.plugins);
10176      }
10177    }, {
10178      key: "removeScales",
10179      value: function removeScales() {
10180        for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {
10181          args[_key10] = arguments[_key10];
10182        }
10183
10184        this._each('unregister', args, this.scales);
10185      }
10186    }, {
10187      key: "_each",
10188      value: function _each(method, args, typedRegistry) {
10189        var me = this;
10190
10191        _toConsumableArray(args).forEach(function (arg) {
10192          var reg = typedRegistry || me._getRegistryForType(arg);
10193
10194          if (typedRegistry || reg.isForType(arg) || reg === me.plugins && arg.id) {
10195            me._exec(method, reg, arg);
10196          } else {
10197            each(arg, function (item) {
10198              var itemReg = typedRegistry || me._getRegistryForType(item);
10199
10200              me._exec(method, itemReg, item);
10201            });
10202          }
10203        });
10204      }
10205    }, {
10206      key: "_exec",
10207      value: function _exec(method, registry, component) {
10208        var camelMethod = _capitalize(method);
10209
10210        callback(component['before' + camelMethod], [], component);
10211        registry[method](component);
10212        callback(component['after' + camelMethod], [], component);
10213      }
10214    }, {
10215      key: "_getRegistryForType",
10216      value: function _getRegistryForType(type) {
10217        for (var i = 0; i < this._typedRegistries.length; i++) {
10218          var reg = this._typedRegistries[i];
10219
10220          if (reg.isForType(type)) {
10221            return reg;
10222          }
10223        }
10224
10225        return this.plugins;
10226      }
10227    }, {
10228      key: "_get",
10229      value: function _get(id, typedRegistry, type) {
10230        var item = typedRegistry.get(id);
10231
10232        if (item === undefined) {
10233          throw new Error('"' + id + '" is not a registered ' + type + '.');
10234        }
10235
10236        return item;
10237      }
10238    }]);
10239
10240    return Registry;
10241  }();
10242
10243  var registry = new Registry();
10244
10245  var PluginService = /*#__PURE__*/function () {
10246    function PluginService() {
10247      _classCallCheck(this, PluginService);
10248
10249      this._init = [];
10250    }
10251
10252    _createClass(PluginService, [{
10253      key: "notify",
10254      value: function notify(chart, hook, args, filter) {
10255        var me = this;
10256
10257        if (hook === 'beforeInit') {
10258          me._init = me._createDescriptors(chart, true);
10259
10260          me._notify(me._init, chart, 'install');
10261        }
10262
10263        var descriptors = filter ? me._descriptors(chart).filter(filter) : me._descriptors(chart);
10264
10265        var result = me._notify(descriptors, chart, hook, args);
10266
10267        if (hook === 'destroy') {
10268          me._notify(descriptors, chart, 'stop');
10269
10270          me._notify(me._init, chart, 'uninstall');
10271        }
10272
10273        return result;
10274      }
10275    }, {
10276      key: "_notify",
10277      value: function _notify(descriptors, chart, hook, args) {
10278        args = args || {};
10279
10280        var _iterator5 = _createForOfIteratorHelper(descriptors),
10281            _step5;
10282
10283        try {
10284          for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
10285            var descriptor = _step5.value;
10286            var plugin = descriptor.plugin;
10287            var method = plugin[hook];
10288            var params = [chart, args, descriptor.options];
10289
10290            if (callback(method, params, plugin) === false && args.cancelable) {
10291              return false;
10292            }
10293          }
10294        } catch (err) {
10295          _iterator5.e(err);
10296        } finally {
10297          _iterator5.f();
10298        }
10299
10300        return true;
10301      }
10302    }, {
10303      key: "invalidate",
10304      value: function invalidate() {
10305        if (!isNullOrUndef(this._cache)) {
10306          this._oldCache = this._cache;
10307          this._cache = undefined;
10308        }
10309      }
10310    }, {
10311      key: "_descriptors",
10312      value: function _descriptors(chart) {
10313        if (this._cache) {
10314          return this._cache;
10315        }
10316
10317        var descriptors = this._cache = this._createDescriptors(chart);
10318
10319        this._notifyStateChanges(chart);
10320
10321        return descriptors;
10322      }
10323    }, {
10324      key: "_createDescriptors",
10325      value: function _createDescriptors(chart, all) {
10326        var config = chart && chart.config;
10327        var options = valueOrDefault(config.options && config.options.plugins, {});
10328        var plugins = allPlugins(config);
10329        return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);
10330      }
10331    }, {
10332      key: "_notifyStateChanges",
10333      value: function _notifyStateChanges(chart) {
10334        var previousDescriptors = this._oldCache || [];
10335        var descriptors = this._cache;
10336
10337        var diff = function diff(a, b) {
10338          return a.filter(function (x) {
10339            return !b.some(function (y) {
10340              return x.plugin.id === y.plugin.id;
10341            });
10342          });
10343        };
10344
10345        this._notify(diff(previousDescriptors, descriptors), chart, 'stop');
10346
10347        this._notify(diff(descriptors, previousDescriptors), chart, 'start');
10348      }
10349    }]);
10350
10351    return PluginService;
10352  }();
10353
10354  function allPlugins(config) {
10355    var plugins = [];
10356    var keys = Object.keys(registry.plugins.items);
10357
10358    for (var i = 0; i < keys.length; i++) {
10359      plugins.push(registry.getPlugin(keys[i]));
10360    }
10361
10362    var local = config.plugins || [];
10363
10364    for (var _i = 0; _i < local.length; _i++) {
10365      var plugin = local[_i];
10366
10367      if (plugins.indexOf(plugin) === -1) {
10368        plugins.push(plugin);
10369      }
10370    }
10371
10372    return plugins;
10373  }
10374
10375  function getOpts(options, all) {
10376    if (!all && options === false) {
10377      return null;
10378    }
10379
10380    if (options === true) {
10381      return {};
10382    }
10383
10384    return options;
10385  }
10386
10387  function createDescriptors(chart, plugins, options, all) {
10388    var result = [];
10389    var context = chart.getContext();
10390
10391    for (var i = 0; i < plugins.length; i++) {
10392      var plugin = plugins[i];
10393      var id = plugin.id;
10394      var opts = getOpts(options[id], all);
10395
10396      if (opts === null) {
10397        continue;
10398      }
10399
10400      result.push({
10401        plugin: plugin,
10402        options: pluginOpts(chart.config, plugin, opts, context)
10403      });
10404    }
10405
10406    return result;
10407  }
10408
10409  function pluginOpts(config, plugin, opts, context) {
10410    var keys = config.pluginScopeKeys(plugin);
10411    var scopes = config.getOptionScopes(opts, keys);
10412    return config.createResolver(scopes, context, [''], {
10413      scriptable: false,
10414      indexable: false,
10415      allKeys: true
10416    });
10417  }
10418
10419  function getIndexAxis(type, options) {
10420    var datasetDefaults = defaults.datasets[type] || {};
10421    var datasetOptions = (options.datasets || {})[type] || {};
10422    return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';
10423  }
10424
10425  function getAxisFromDefaultScaleID(id, indexAxis) {
10426    var axis = id;
10427
10428    if (id === '_index_') {
10429      axis = indexAxis;
10430    } else if (id === '_value_') {
10431      axis = indexAxis === 'x' ? 'y' : 'x';
10432    }
10433
10434    return axis;
10435  }
10436
10437  function getDefaultScaleIDFromAxis(axis, indexAxis) {
10438    return axis === indexAxis ? '_index_' : '_value_';
10439  }
10440
10441  function axisFromPosition(position) {
10442    if (position === 'top' || position === 'bottom') {
10443      return 'x';
10444    }
10445
10446    if (position === 'left' || position === 'right') {
10447      return 'y';
10448    }
10449  }
10450
10451  function determineAxis(id, scaleOptions) {
10452    if (id === 'x' || id === 'y') {
10453      return id;
10454    }
10455
10456    return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id.charAt(0).toLowerCase();
10457  }
10458
10459  function mergeScaleConfig(config, options) {
10460    var chartDefaults = overrides[config.type] || {
10461      scales: {}
10462    };
10463    var configScales = options.scales || {};
10464    var chartIndexAxis = getIndexAxis(config.type, options);
10465    var firstIDs = Object.create(null);
10466    var scales = Object.create(null);
10467    Object.keys(configScales).forEach(function (id) {
10468      var scaleConf = configScales[id];
10469      var axis = determineAxis(id, scaleConf);
10470      var defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
10471      var defaultScaleOptions = chartDefaults.scales || {};
10472      firstIDs[axis] = firstIDs[axis] || id;
10473      scales[id] = mergeIf(Object.create(null), [{
10474        axis: axis
10475      }, scaleConf, defaultScaleOptions[axis], defaultScaleOptions[defaultId]]);
10476    });
10477    config.data.datasets.forEach(function (dataset) {
10478      var type = dataset.type || config.type;
10479      var indexAxis = dataset.indexAxis || getIndexAxis(type, options);
10480      var datasetDefaults = overrides[type] || {};
10481      var defaultScaleOptions = datasetDefaults.scales || {};
10482      Object.keys(defaultScaleOptions).forEach(function (defaultID) {
10483        var axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
10484        var id = dataset[axis + 'AxisID'] || firstIDs[axis] || axis;
10485        scales[id] = scales[id] || Object.create(null);
10486        mergeIf(scales[id], [{
10487          axis: axis
10488        }, configScales[id], defaultScaleOptions[defaultID]]);
10489      });
10490    });
10491    Object.keys(scales).forEach(function (key) {
10492      var scale = scales[key];
10493      mergeIf(scale, [defaults.scales[scale.type], defaults.scale]);
10494    });
10495    return scales;
10496  }
10497
10498  function initOptions(config) {
10499    var options = config.options || (config.options = {});
10500    options.plugins = valueOrDefault(options.plugins, {});
10501    options.scales = mergeScaleConfig(config, options);
10502  }
10503
10504  function initData(data) {
10505    data = data || {};
10506    data.datasets = data.datasets || [];
10507    data.labels = data.labels || [];
10508    return data;
10509  }
10510
10511  function initConfig(config) {
10512    config = config || {};
10513    config.data = initData(config.data);
10514    initOptions(config);
10515    return config;
10516  }
10517
10518  var keyCache = new Map();
10519  var keysCached = new Set();
10520
10521  function cachedKeys(cacheKey, generate) {
10522    var keys = keyCache.get(cacheKey);
10523
10524    if (!keys) {
10525      keys = generate();
10526      keyCache.set(cacheKey, keys);
10527      keysCached.add(keys);
10528    }
10529
10530    return keys;
10531  }
10532
10533  var addIfFound = function addIfFound(set, obj, key) {
10534    var opts = resolveObjectKey(obj, key);
10535
10536    if (opts !== undefined) {
10537      set.add(opts);
10538    }
10539  };
10540
10541  var Config = /*#__PURE__*/function () {
10542    function Config(config) {
10543      _classCallCheck(this, Config);
10544
10545      this._config = initConfig(config);
10546      this._scopeCache = new Map();
10547      this._resolverCache = new Map();
10548    }
10549
10550    _createClass(Config, [{
10551      key: "type",
10552      get: function get() {
10553        return this._config.type;
10554      },
10555      set: function set(type) {
10556        this._config.type = type;
10557      }
10558    }, {
10559      key: "data",
10560      get: function get() {
10561        return this._config.data;
10562      },
10563      set: function set(data) {
10564        this._config.data = initData(data);
10565      }
10566    }, {
10567      key: "options",
10568      get: function get() {
10569        return this._config.options;
10570      },
10571      set: function set(options) {
10572        this._config.options = options;
10573      }
10574    }, {
10575      key: "plugins",
10576      get: function get() {
10577        return this._config.plugins;
10578      }
10579    }, {
10580      key: "update",
10581      value: function update() {
10582        var config = this._config;
10583        this.clearCache();
10584        initOptions(config);
10585      }
10586    }, {
10587      key: "clearCache",
10588      value: function clearCache() {
10589        this._scopeCache.clear();
10590
10591        this._resolverCache.clear();
10592      }
10593    }, {
10594      key: "datasetScopeKeys",
10595      value: function datasetScopeKeys(datasetType) {
10596        return cachedKeys(datasetType, function () {
10597          return [["datasets.".concat(datasetType), '']];
10598        });
10599      }
10600    }, {
10601      key: "datasetAnimationScopeKeys",
10602      value: function datasetAnimationScopeKeys(datasetType, transition) {
10603        return cachedKeys("".concat(datasetType, ".transition.").concat(transition), function () {
10604          return [["datasets.".concat(datasetType, ".transitions.").concat(transition), "transitions.".concat(transition)], ["datasets.".concat(datasetType), '']];
10605        });
10606      }
10607    }, {
10608      key: "datasetElementScopeKeys",
10609      value: function datasetElementScopeKeys(datasetType, elementType) {
10610        return cachedKeys("".concat(datasetType, "-").concat(elementType), function () {
10611          return [["datasets.".concat(datasetType, ".elements.").concat(elementType), "datasets.".concat(datasetType), "elements.".concat(elementType), '']];
10612        });
10613      }
10614    }, {
10615      key: "pluginScopeKeys",
10616      value: function pluginScopeKeys(plugin) {
10617        var id = plugin.id;
10618        var type = this.type;
10619        return cachedKeys("".concat(type, "-plugin-").concat(id), function () {
10620          return [["plugins.".concat(id)].concat(_toConsumableArray(plugin.additionalOptionScopes || []))];
10621        });
10622      }
10623    }, {
10624      key: "_cachedScopes",
10625      value: function _cachedScopes(mainScope, resetCache) {
10626        var _scopeCache = this._scopeCache;
10627
10628        var cache = _scopeCache.get(mainScope);
10629
10630        if (!cache || resetCache) {
10631          cache = new Map();
10632
10633          _scopeCache.set(mainScope, cache);
10634        }
10635
10636        return cache;
10637      }
10638    }, {
10639      key: "getOptionScopes",
10640      value: function getOptionScopes(mainScope, keyLists, resetCache) {
10641        var options = this.options,
10642            type = this.type;
10643
10644        var cache = this._cachedScopes(mainScope, resetCache);
10645
10646        var cached = cache.get(keyLists);
10647
10648        if (cached) {
10649          return cached;
10650        }
10651
10652        var scopes = new Set();
10653        keyLists.forEach(function (keys) {
10654          if (mainScope) {
10655            scopes.add(mainScope);
10656            keys.forEach(function (key) {
10657              return addIfFound(scopes, mainScope, key);
10658            });
10659          }
10660
10661          keys.forEach(function (key) {
10662            return addIfFound(scopes, options, key);
10663          });
10664          keys.forEach(function (key) {
10665            return addIfFound(scopes, overrides[type] || {}, key);
10666          });
10667          keys.forEach(function (key) {
10668            return addIfFound(scopes, defaults, key);
10669          });
10670          keys.forEach(function (key) {
10671            return addIfFound(scopes, descriptors, key);
10672          });
10673        });
10674        var array = Array.from(scopes);
10675
10676        if (keysCached.has(keyLists)) {
10677          cache.set(keyLists, array);
10678        }
10679
10680        return array;
10681      }
10682    }, {
10683      key: "chartOptionScopes",
10684      value: function chartOptionScopes() {
10685        var options = this.options,
10686            type = this.type;
10687        return [options, overrides[type] || {}, defaults.datasets[type] || {}, {
10688          type: type
10689        }, defaults, descriptors];
10690      }
10691    }, {
10692      key: "resolveNamedOptions",
10693      value: function resolveNamedOptions(scopes, names, context) {
10694        var prefixes = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [''];
10695        var result = {
10696          $shared: true
10697        };
10698
10699        var _getResolver = getResolver(this._resolverCache, scopes, prefixes),
10700            resolver = _getResolver.resolver,
10701            subPrefixes = _getResolver.subPrefixes;
10702
10703        var options = resolver;
10704
10705        if (needContext(resolver, names)) {
10706          result.$shared = false;
10707          context = isFunction(context) ? context() : context;
10708          var subResolver = this.createResolver(scopes, context, subPrefixes);
10709          options = _attachContext(resolver, context, subResolver);
10710        }
10711
10712        var _iterator6 = _createForOfIteratorHelper(names),
10713            _step6;
10714
10715        try {
10716          for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
10717            var prop = _step6.value;
10718            result[prop] = options[prop];
10719          }
10720        } catch (err) {
10721          _iterator6.e(err);
10722        } finally {
10723          _iterator6.f();
10724        }
10725
10726        return result;
10727      }
10728    }, {
10729      key: "createResolver",
10730      value: function createResolver(scopes, context) {
10731        var prefixes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [''];
10732        var descriptorDefaults = arguments.length > 3 ? arguments[3] : undefined;
10733
10734        var _getResolver2 = getResolver(this._resolverCache, scopes, prefixes),
10735            resolver = _getResolver2.resolver;
10736
10737        return isObject(context) ? _attachContext(resolver, context, undefined, descriptorDefaults) : resolver;
10738      }
10739    }]);
10740
10741    return Config;
10742  }();
10743
10744  function getResolver(resolverCache, scopes, prefixes) {
10745    var cache = resolverCache.get(scopes);
10746
10747    if (!cache) {
10748      cache = new Map();
10749      resolverCache.set(scopes, cache);
10750    }
10751
10752    var cacheKey = prefixes.join();
10753    var cached = cache.get(cacheKey);
10754
10755    if (!cached) {
10756      var resolver = _createResolver(scopes, prefixes);
10757
10758      cached = {
10759        resolver: resolver,
10760        subPrefixes: prefixes.filter(function (p) {
10761          return !p.toLowerCase().includes('hover');
10762        })
10763      };
10764      cache.set(cacheKey, cached);
10765    }
10766
10767    return cached;
10768  }
10769
10770  function needContext(proxy, names) {
10771    var _descriptors2 = _descriptors(proxy),
10772        isScriptable = _descriptors2.isScriptable,
10773        isIndexable = _descriptors2.isIndexable;
10774
10775    var _iterator7 = _createForOfIteratorHelper(names),
10776        _step7;
10777
10778    try {
10779      for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
10780        var prop = _step7.value;
10781
10782        if (isScriptable(prop) && isFunction(proxy[prop]) || isIndexable(prop) && isArray(proxy[prop])) {
10783          return true;
10784        }
10785      }
10786    } catch (err) {
10787      _iterator7.e(err);
10788    } finally {
10789      _iterator7.f();
10790    }
10791
10792    return false;
10793  }
10794
10795  var version = "3.4.1";
10796  var KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea'];
10797
10798  function positionIsHorizontal(position, axis) {
10799    return position === 'top' || position === 'bottom' || KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x';
10800  }
10801
10802  function compare2Level(l1, l2) {
10803    return function (a, b) {
10804      return a[l1] === b[l1] ? a[l2] - b[l2] : a[l1] - b[l1];
10805    };
10806  }
10807
10808  function onAnimationsComplete(context) {
10809    var chart = context.chart;
10810    var animationOptions = chart.options.animation;
10811    chart.notifyPlugins('afterRender');
10812    callback(animationOptions && animationOptions.onComplete, [context], chart);
10813  }
10814
10815  function onAnimationProgress(context) {
10816    var chart = context.chart;
10817    var animationOptions = chart.options.animation;
10818    callback(animationOptions && animationOptions.onProgress, [context], chart);
10819  }
10820
10821  function isDomSupported() {
10822    return typeof window !== 'undefined' && typeof document !== 'undefined';
10823  }
10824
10825  function getCanvas(item) {
10826    if (isDomSupported() && typeof item === 'string') {
10827      item = document.getElementById(item);
10828    } else if (item && item.length) {
10829      item = item[0];
10830    }
10831
10832    if (item && item.canvas) {
10833      item = item.canvas;
10834    }
10835
10836    return item;
10837  }
10838
10839  var instances = {};
10840
10841  var getChart = function getChart(key) {
10842    var canvas = getCanvas(key);
10843    return Object.values(instances).filter(function (c) {
10844      return c.canvas === canvas;
10845    }).pop();
10846  };
10847
10848  var Chart = /*#__PURE__*/function () {
10849    function Chart(item, config) {
10850      var _this5 = this;
10851
10852      _classCallCheck(this, Chart);
10853
10854      var me = this;
10855      this.config = config = new Config(config);
10856      var initialCanvas = getCanvas(item);
10857      var existingChart = getChart(initialCanvas);
10858
10859      if (existingChart) {
10860        throw new Error('Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' + ' must be destroyed before the canvas can be reused.');
10861      }
10862
10863      var options = config.createResolver(config.chartOptionScopes(), me.getContext());
10864      this.platform = me._initializePlatform(initialCanvas, config);
10865      var context = me.platform.acquireContext(initialCanvas, options.aspectRatio);
10866      var canvas = context && context.canvas;
10867      var height = canvas && canvas.height;
10868      var width = canvas && canvas.width;
10869      this.id = uid();
10870      this.ctx = context;
10871      this.canvas = canvas;
10872      this.width = width;
10873      this.height = height;
10874      this._options = options;
10875      this._aspectRatio = this.aspectRatio;
10876      this._layers = [];
10877      this._metasets = [];
10878      this._stacks = undefined;
10879      this.boxes = [];
10880      this.currentDevicePixelRatio = undefined;
10881      this.chartArea = undefined;
10882      this._active = [];
10883      this._lastEvent = undefined;
10884      this._listeners = {};
10885      this._responsiveListeners = undefined;
10886      this._sortedMetasets = [];
10887      this.scales = {};
10888      this.scale = undefined;
10889      this._plugins = new PluginService();
10890      this.$proxies = {};
10891      this._hiddenIndices = {};
10892      this.attached = false;
10893      this._animationsDisabled = undefined;
10894      this.$context = undefined;
10895      this._doResize = debounce(function () {
10896        return _this5.update('resize');
10897      }, options.resizeDelay || 0);
10898      instances[me.id] = me;
10899
10900      if (!context || !canvas) {
10901        console.error("Failed to create chart: can't acquire context from the given item");
10902        return;
10903      }
10904
10905      animator.listen(me, 'complete', onAnimationsComplete);
10906      animator.listen(me, 'progress', onAnimationProgress);
10907
10908      me._initialize();
10909
10910      if (me.attached) {
10911        me.update();
10912      }
10913    }
10914
10915    _createClass(Chart, [{
10916      key: "aspectRatio",
10917      get: function get() {
10918        var _this$options3 = this.options,
10919            aspectRatio = _this$options3.aspectRatio,
10920            maintainAspectRatio = _this$options3.maintainAspectRatio,
10921            width = this.width,
10922            height = this.height,
10923            _aspectRatio = this._aspectRatio;
10924
10925        if (!isNullOrUndef(aspectRatio)) {
10926          return aspectRatio;
10927        }
10928
10929        if (maintainAspectRatio && _aspectRatio) {
10930          return _aspectRatio;
10931        }
10932
10933        return height ? width / height : null;
10934      }
10935    }, {
10936      key: "data",
10937      get: function get() {
10938        return this.config.data;
10939      },
10940      set: function set(data) {
10941        this.config.data = data;
10942      }
10943    }, {
10944      key: "options",
10945      get: function get() {
10946        return this._options;
10947      },
10948      set: function set(options) {
10949        this.config.options = options;
10950      }
10951    }, {
10952      key: "_initialize",
10953      value: function _initialize() {
10954        var me = this;
10955        me.notifyPlugins('beforeInit');
10956
10957        if (me.options.responsive) {
10958          me.resize();
10959        } else {
10960          retinaScale(me, me.options.devicePixelRatio);
10961        }
10962
10963        me.bindEvents();
10964        me.notifyPlugins('afterInit');
10965        return me;
10966      }
10967    }, {
10968      key: "_initializePlatform",
10969      value: function _initializePlatform(canvas, config) {
10970        if (config.platform) {
10971          return new config.platform();
10972        } else if (!isDomSupported() || typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) {
10973          return new BasicPlatform();
10974        }
10975
10976        return new DomPlatform();
10977      }
10978    }, {
10979      key: "clear",
10980      value: function clear() {
10981        clearCanvas(this.canvas, this.ctx);
10982        return this;
10983      }
10984    }, {
10985      key: "stop",
10986      value: function stop() {
10987        animator.stop(this);
10988        return this;
10989      }
10990    }, {
10991      key: "resize",
10992      value: function resize(width, height) {
10993        if (!animator.running(this)) {
10994          this._resize(width, height);
10995        } else {
10996          this._resizeBeforeDraw = {
10997            width: width,
10998            height: height
10999          };
11000        }
11001      }
11002    }, {
11003      key: "_resize",
11004      value: function _resize(width, height) {
11005        var me = this;
11006        var options = me.options;
11007        var canvas = me.canvas;
11008        var aspectRatio = options.maintainAspectRatio && me.aspectRatio;
11009        var newSize = me.platform.getMaximumSize(canvas, width, height, aspectRatio);
11010        var newRatio = options.devicePixelRatio || me.platform.getDevicePixelRatio();
11011        me.width = newSize.width;
11012        me.height = newSize.height;
11013        me._aspectRatio = me.aspectRatio;
11014
11015        if (!retinaScale(me, newRatio, true)) {
11016          return;
11017        }
11018
11019        me.notifyPlugins('resize', {
11020          size: newSize
11021        });
11022        callback(options.onResize, [me, newSize], me);
11023
11024        if (me.attached) {
11025          if (me._doResize()) {
11026            me.render();
11027          }
11028        }
11029      }
11030    }, {
11031      key: "ensureScalesHaveIDs",
11032      value: function ensureScalesHaveIDs() {
11033        var options = this.options;
11034        var scalesOptions = options.scales || {};
11035        each(scalesOptions, function (axisOptions, axisID) {
11036          axisOptions.id = axisID;
11037        });
11038      }
11039    }, {
11040      key: "buildOrUpdateScales",
11041      value: function buildOrUpdateScales() {
11042        var me = this;
11043        var options = me.options;
11044        var scaleOpts = options.scales;
11045        var scales = me.scales;
11046        var updated = Object.keys(scales).reduce(function (obj, id) {
11047          obj[id] = false;
11048          return obj;
11049        }, {});
11050        var items = [];
11051
11052        if (scaleOpts) {
11053          items = items.concat(Object.keys(scaleOpts).map(function (id) {
11054            var scaleOptions = scaleOpts[id];
11055            var axis = determineAxis(id, scaleOptions);
11056            var isRadial = axis === 'r';
11057            var isHorizontal = axis === 'x';
11058            return {
11059              options: scaleOptions,
11060              dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',
11061              dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'
11062            };
11063          }));
11064        }
11065
11066        each(items, function (item) {
11067          var scaleOptions = item.options;
11068          var id = scaleOptions.id;
11069          var axis = determineAxis(id, scaleOptions);
11070          var scaleType = valueOrDefault(scaleOptions.type, item.dtype);
11071
11072          if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {
11073            scaleOptions.position = item.dposition;
11074          }
11075
11076          updated[id] = true;
11077          var scale = null;
11078
11079          if (id in scales && scales[id].type === scaleType) {
11080            scale = scales[id];
11081          } else {
11082            var scaleClass = registry.getScale(scaleType);
11083            scale = new scaleClass({
11084              id: id,
11085              type: scaleType,
11086              ctx: me.ctx,
11087              chart: me
11088            });
11089            scales[scale.id] = scale;
11090          }
11091
11092          scale.init(scaleOptions, options);
11093        });
11094        each(updated, function (hasUpdated, id) {
11095          if (!hasUpdated) {
11096            delete scales[id];
11097          }
11098        });
11099        each(scales, function (scale) {
11100          layouts.configure(me, scale, scale.options);
11101          layouts.addBox(me, scale);
11102        });
11103      }
11104    }, {
11105      key: "_updateMetasets",
11106      value: function _updateMetasets() {
11107        var me = this;
11108        var metasets = me._metasets;
11109        var numData = me.data.datasets.length;
11110        var numMeta = metasets.length;
11111        metasets.sort(function (a, b) {
11112          return a.index - b.index;
11113        });
11114
11115        if (numMeta > numData) {
11116          for (var i = numData; i < numMeta; ++i) {
11117            me._destroyDatasetMeta(i);
11118          }
11119
11120          metasets.splice(numData, numMeta - numData);
11121        }
11122
11123        me._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));
11124      }
11125    }, {
11126      key: "_removeUnreferencedMetasets",
11127      value: function _removeUnreferencedMetasets() {
11128        var me = this;
11129        var metasets = me._metasets,
11130            datasets = me.data.datasets;
11131
11132        if (metasets.length > datasets.length) {
11133          delete me._stacks;
11134        }
11135
11136        metasets.forEach(function (meta, index) {
11137          if (datasets.filter(function (x) {
11138            return x === meta._dataset;
11139          }).length === 0) {
11140            me._destroyDatasetMeta(index);
11141          }
11142        });
11143      }
11144    }, {
11145      key: "buildOrUpdateControllers",
11146      value: function buildOrUpdateControllers() {
11147        var me = this;
11148        var newControllers = [];
11149        var datasets = me.data.datasets;
11150        var i, ilen;
11151
11152        me._removeUnreferencedMetasets();
11153
11154        for (i = 0, ilen = datasets.length; i < ilen; i++) {
11155          var dataset = datasets[i];
11156          var meta = me.getDatasetMeta(i);
11157          var type = dataset.type || me.config.type;
11158
11159          if (meta.type && meta.type !== type) {
11160            me._destroyDatasetMeta(i);
11161
11162            meta = me.getDatasetMeta(i);
11163          }
11164
11165          meta.type = type;
11166          meta.indexAxis = dataset.indexAxis || getIndexAxis(type, me.options);
11167          meta.order = dataset.order || 0;
11168          meta.index = i;
11169          meta.label = '' + dataset.label;
11170          meta.visible = me.isDatasetVisible(i);
11171
11172          if (meta.controller) {
11173            meta.controller.updateIndex(i);
11174            meta.controller.linkScales();
11175          } else {
11176            var ControllerClass = registry.getController(type);
11177            var _defaults$datasets$ty = defaults.datasets[type],
11178                datasetElementType = _defaults$datasets$ty.datasetElementType,
11179                dataElementType = _defaults$datasets$ty.dataElementType;
11180            Object.assign(ControllerClass.prototype, {
11181              dataElementType: registry.getElement(dataElementType),
11182              datasetElementType: datasetElementType && registry.getElement(datasetElementType)
11183            });
11184            meta.controller = new ControllerClass(me, i);
11185            newControllers.push(meta.controller);
11186          }
11187        }
11188
11189        me._updateMetasets();
11190
11191        return newControllers;
11192      }
11193    }, {
11194      key: "_resetElements",
11195      value: function _resetElements() {
11196        var me = this;
11197        each(me.data.datasets, function (dataset, datasetIndex) {
11198          me.getDatasetMeta(datasetIndex).controller.reset();
11199        }, me);
11200      }
11201    }, {
11202      key: "reset",
11203      value: function reset() {
11204        this._resetElements();
11205
11206        this.notifyPlugins('reset');
11207      }
11208    }, {
11209      key: "update",
11210      value: function update(mode) {
11211        var me = this;
11212        var config = me.config;
11213        config.update();
11214        me._options = config.createResolver(config.chartOptionScopes(), me.getContext());
11215        each(me.scales, function (scale) {
11216          layouts.removeBox(me, scale);
11217        });
11218        var animsDisabled = me._animationsDisabled = !me.options.animation;
11219        me.ensureScalesHaveIDs();
11220        me.buildOrUpdateScales();
11221        var existingEvents = new Set(Object.keys(me._listeners));
11222        var newEvents = new Set(me.options.events);
11223
11224        if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== me.options.responsive) {
11225          me.unbindEvents();
11226          me.bindEvents();
11227        }
11228
11229        me._plugins.invalidate();
11230
11231        if (me.notifyPlugins('beforeUpdate', {
11232          mode: mode,
11233          cancelable: true
11234        }) === false) {
11235          return;
11236        }
11237
11238        var newControllers = me.buildOrUpdateControllers();
11239        me.notifyPlugins('beforeElementsUpdate');
11240        var minPadding = 0;
11241
11242        for (var i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
11243          var _me$getDatasetMeta = me.getDatasetMeta(i),
11244              controller = _me$getDatasetMeta.controller;
11245
11246          var reset = !animsDisabled && newControllers.indexOf(controller) === -1;
11247          controller.buildOrUpdateElements(reset);
11248          minPadding = Math.max(+controller.getMaxOverflow(), minPadding);
11249        }
11250
11251        me._minPadding = minPadding;
11252
11253        me._updateLayout(minPadding);
11254
11255        if (!animsDisabled) {
11256          each(newControllers, function (controller) {
11257            controller.reset();
11258          });
11259        }
11260
11261        me._updateDatasets(mode);
11262
11263        me.notifyPlugins('afterUpdate', {
11264          mode: mode
11265        });
11266
11267        me._layers.sort(compare2Level('z', '_idx'));
11268
11269        if (me._lastEvent) {
11270          me._eventHandler(me._lastEvent, true);
11271        }
11272
11273        me.render();
11274      }
11275    }, {
11276      key: "_updateLayout",
11277      value: function _updateLayout(minPadding) {
11278        var me = this;
11279
11280        if (me.notifyPlugins('beforeLayout', {
11281          cancelable: true
11282        }) === false) {
11283          return;
11284        }
11285
11286        layouts.update(me, me.width, me.height, minPadding);
11287        var area = me.chartArea;
11288        var noArea = area.width <= 0 || area.height <= 0;
11289        me._layers = [];
11290        each(me.boxes, function (box) {
11291          var _me$_layers;
11292
11293          if (noArea && box.position === 'chartArea') {
11294            return;
11295          }
11296
11297          if (box.configure) {
11298            box.configure();
11299          }
11300
11301          (_me$_layers = me._layers).push.apply(_me$_layers, _toConsumableArray(box._layers()));
11302        }, me);
11303
11304        me._layers.forEach(function (item, index) {
11305          item._idx = index;
11306        });
11307
11308        me.notifyPlugins('afterLayout');
11309      }
11310    }, {
11311      key: "_updateDatasets",
11312      value: function _updateDatasets(mode) {
11313        var me = this;
11314        var isFunction = typeof mode === 'function';
11315
11316        if (me.notifyPlugins('beforeDatasetsUpdate', {
11317          mode: mode,
11318          cancelable: true
11319        }) === false) {
11320          return;
11321        }
11322
11323        for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
11324          me._updateDataset(i, isFunction ? mode({
11325            datasetIndex: i
11326          }) : mode);
11327        }
11328
11329        me.notifyPlugins('afterDatasetsUpdate', {
11330          mode: mode
11331        });
11332      }
11333    }, {
11334      key: "_updateDataset",
11335      value: function _updateDataset(index, mode) {
11336        var me = this;
11337        var meta = me.getDatasetMeta(index);
11338        var args = {
11339          meta: meta,
11340          index: index,
11341          mode: mode,
11342          cancelable: true
11343        };
11344
11345        if (me.notifyPlugins('beforeDatasetUpdate', args) === false) {
11346          return;
11347        }
11348
11349        meta.controller._update(mode);
11350
11351        args.cancelable = false;
11352        me.notifyPlugins('afterDatasetUpdate', args);
11353      }
11354    }, {
11355      key: "render",
11356      value: function render() {
11357        var me = this;
11358
11359        if (me.notifyPlugins('beforeRender', {
11360          cancelable: true
11361        }) === false) {
11362          return;
11363        }
11364
11365        if (animator.has(me)) {
11366          if (me.attached && !animator.running(me)) {
11367            animator.start(me);
11368          }
11369        } else {
11370          me.draw();
11371          onAnimationsComplete({
11372            chart: me
11373          });
11374        }
11375      }
11376    }, {
11377      key: "draw",
11378      value: function draw() {
11379        var me = this;
11380        var i;
11381
11382        if (me._resizeBeforeDraw) {
11383          var _me$_resizeBeforeDraw = me._resizeBeforeDraw,
11384              width = _me$_resizeBeforeDraw.width,
11385              height = _me$_resizeBeforeDraw.height;
11386
11387          me._resize(width, height);
11388
11389          me._resizeBeforeDraw = null;
11390        }
11391
11392        me.clear();
11393
11394        if (me.width <= 0 || me.height <= 0) {
11395          return;
11396        }
11397
11398        if (me.notifyPlugins('beforeDraw', {
11399          cancelable: true
11400        }) === false) {
11401          return;
11402        }
11403
11404        var layers = me._layers;
11405
11406        for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
11407          layers[i].draw(me.chartArea);
11408        }
11409
11410        me._drawDatasets();
11411
11412        for (; i < layers.length; ++i) {
11413          layers[i].draw(me.chartArea);
11414        }
11415
11416        me.notifyPlugins('afterDraw');
11417      }
11418    }, {
11419      key: "_getSortedDatasetMetas",
11420      value: function _getSortedDatasetMetas(filterVisible) {
11421        var me = this;
11422        var metasets = me._sortedMetasets;
11423        var result = [];
11424        var i, ilen;
11425
11426        for (i = 0, ilen = metasets.length; i < ilen; ++i) {
11427          var meta = metasets[i];
11428
11429          if (!filterVisible || meta.visible) {
11430            result.push(meta);
11431          }
11432        }
11433
11434        return result;
11435      }
11436    }, {
11437      key: "getSortedVisibleDatasetMetas",
11438      value: function getSortedVisibleDatasetMetas() {
11439        return this._getSortedDatasetMetas(true);
11440      }
11441    }, {
11442      key: "_drawDatasets",
11443      value: function _drawDatasets() {
11444        var me = this;
11445
11446        if (me.notifyPlugins('beforeDatasetsDraw', {
11447          cancelable: true
11448        }) === false) {
11449          return;
11450        }
11451
11452        var metasets = me.getSortedVisibleDatasetMetas();
11453
11454        for (var i = metasets.length - 1; i >= 0; --i) {
11455          me._drawDataset(metasets[i]);
11456        }
11457
11458        me.notifyPlugins('afterDatasetsDraw');
11459      }
11460    }, {
11461      key: "_drawDataset",
11462      value: function _drawDataset(meta) {
11463        var me = this;
11464        var ctx = me.ctx;
11465        var clip = meta._clip;
11466        var useClip = !clip.disabled;
11467        var area = me.chartArea;
11468        var args = {
11469          meta: meta,
11470          index: meta.index,
11471          cancelable: true
11472        };
11473
11474        if (me.notifyPlugins('beforeDatasetDraw', args) === false) {
11475          return;
11476        }
11477
11478        if (useClip) {
11479          clipArea(ctx, {
11480            left: clip.left === false ? 0 : area.left - clip.left,
11481            right: clip.right === false ? me.width : area.right + clip.right,
11482            top: clip.top === false ? 0 : area.top - clip.top,
11483            bottom: clip.bottom === false ? me.height : area.bottom + clip.bottom
11484          });
11485        }
11486
11487        meta.controller.draw();
11488
11489        if (useClip) {
11490          unclipArea(ctx);
11491        }
11492
11493        args.cancelable = false;
11494        me.notifyPlugins('afterDatasetDraw', args);
11495      }
11496    }, {
11497      key: "getElementsAtEventForMode",
11498      value: function getElementsAtEventForMode(e, mode, options, useFinalPosition) {
11499        var method = Interaction.modes[mode];
11500
11501        if (typeof method === 'function') {
11502          return method(this, e, options, useFinalPosition);
11503        }
11504
11505        return [];
11506      }
11507    }, {
11508      key: "getDatasetMeta",
11509      value: function getDatasetMeta(datasetIndex) {
11510        var me = this;
11511        var dataset = me.data.datasets[datasetIndex];
11512        var metasets = me._metasets;
11513        var meta = metasets.filter(function (x) {
11514          return x && x._dataset === dataset;
11515        }).pop();
11516
11517        if (!meta) {
11518          meta = {
11519            type: null,
11520            data: [],
11521            dataset: null,
11522            controller: null,
11523            hidden: null,
11524            xAxisID: null,
11525            yAxisID: null,
11526            order: dataset && dataset.order || 0,
11527            index: datasetIndex,
11528            _dataset: dataset,
11529            _parsed: [],
11530            _sorted: false
11531          };
11532          metasets.push(meta);
11533        }
11534
11535        return meta;
11536      }
11537    }, {
11538      key: "getContext",
11539      value: function getContext() {
11540        return this.$context || (this.$context = {
11541          chart: this,
11542          type: 'chart'
11543        });
11544      }
11545    }, {
11546      key: "getVisibleDatasetCount",
11547      value: function getVisibleDatasetCount() {
11548        return this.getSortedVisibleDatasetMetas().length;
11549      }
11550    }, {
11551      key: "isDatasetVisible",
11552      value: function isDatasetVisible(datasetIndex) {
11553        var dataset = this.data.datasets[datasetIndex];
11554
11555        if (!dataset) {
11556          return false;
11557        }
11558
11559        var meta = this.getDatasetMeta(datasetIndex);
11560        return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;
11561      }
11562    }, {
11563      key: "setDatasetVisibility",
11564      value: function setDatasetVisibility(datasetIndex, visible) {
11565        var meta = this.getDatasetMeta(datasetIndex);
11566        meta.hidden = !visible;
11567      }
11568    }, {
11569      key: "toggleDataVisibility",
11570      value: function toggleDataVisibility(index) {
11571        this._hiddenIndices[index] = !this._hiddenIndices[index];
11572      }
11573    }, {
11574      key: "getDataVisibility",
11575      value: function getDataVisibility(index) {
11576        return !this._hiddenIndices[index];
11577      }
11578    }, {
11579      key: "_updateDatasetVisibility",
11580      value: function _updateDatasetVisibility(datasetIndex, visible) {
11581        var me = this;
11582        var mode = visible ? 'show' : 'hide';
11583        var meta = me.getDatasetMeta(datasetIndex);
11584
11585        var anims = meta.controller._resolveAnimations(undefined, mode);
11586
11587        me.setDatasetVisibility(datasetIndex, visible);
11588        anims.update(meta, {
11589          visible: visible
11590        });
11591        me.update(function (ctx) {
11592          return ctx.datasetIndex === datasetIndex ? mode : undefined;
11593        });
11594      }
11595    }, {
11596      key: "hide",
11597      value: function hide(datasetIndex) {
11598        this._updateDatasetVisibility(datasetIndex, false);
11599      }
11600    }, {
11601      key: "show",
11602      value: function show(datasetIndex) {
11603        this._updateDatasetVisibility(datasetIndex, true);
11604      }
11605    }, {
11606      key: "_destroyDatasetMeta",
11607      value: function _destroyDatasetMeta(datasetIndex) {
11608        var me = this;
11609        var meta = me._metasets && me._metasets[datasetIndex];
11610
11611        if (meta && meta.controller) {
11612          meta.controller._destroy();
11613
11614          delete me._metasets[datasetIndex];
11615        }
11616      }
11617    }, {
11618      key: "destroy",
11619      value: function destroy() {
11620        var me = this;
11621        var canvas = me.canvas,
11622            ctx = me.ctx;
11623        var i, ilen;
11624        me.stop();
11625        animator.remove(me);
11626
11627        for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
11628          me._destroyDatasetMeta(i);
11629        }
11630
11631        me.config.clearCache();
11632
11633        if (canvas) {
11634          me.unbindEvents();
11635          clearCanvas(canvas, ctx);
11636          me.platform.releaseContext(ctx);
11637          me.canvas = null;
11638          me.ctx = null;
11639        }
11640
11641        me.notifyPlugins('destroy');
11642        delete instances[me.id];
11643      }
11644    }, {
11645      key: "toBase64Image",
11646      value: function toBase64Image() {
11647        var _this$canvas;
11648
11649        return (_this$canvas = this.canvas).toDataURL.apply(_this$canvas, arguments);
11650      }
11651    }, {
11652      key: "bindEvents",
11653      value: function bindEvents() {
11654        this.bindUserEvents();
11655
11656        if (this.options.responsive) {
11657          this.bindResponsiveEvents();
11658        } else {
11659          this.attached = true;
11660        }
11661      }
11662    }, {
11663      key: "bindUserEvents",
11664      value: function bindUserEvents() {
11665        var me = this;
11666        var listeners = me._listeners;
11667        var platform = me.platform;
11668
11669        var _add = function _add(type, listener) {
11670          platform.addEventListener(me, type, listener);
11671          listeners[type] = listener;
11672        };
11673
11674        var listener = function listener(e, x, y) {
11675          e.offsetX = x;
11676          e.offsetY = y;
11677
11678          me._eventHandler(e);
11679        };
11680
11681        each(me.options.events, function (type) {
11682          return _add(type, listener);
11683        });
11684      }
11685    }, {
11686      key: "bindResponsiveEvents",
11687      value: function bindResponsiveEvents() {
11688        var me = this;
11689
11690        if (!me._responsiveListeners) {
11691          me._responsiveListeners = {};
11692        }
11693
11694        var listeners = me._responsiveListeners;
11695        var platform = me.platform;
11696
11697        var _add = function _add(type, listener) {
11698          platform.addEventListener(me, type, listener);
11699          listeners[type] = listener;
11700        };
11701
11702        var _remove = function _remove(type, listener) {
11703          if (listeners[type]) {
11704            platform.removeEventListener(me, type, listener);
11705            delete listeners[type];
11706          }
11707        };
11708
11709        var listener = function listener(width, height) {
11710          if (me.canvas) {
11711            me.resize(width, height);
11712          }
11713        };
11714
11715        var detached;
11716
11717        var attached = function attached() {
11718          _remove('attach', attached);
11719
11720          me.attached = true;
11721          me.resize();
11722
11723          _add('resize', listener);
11724
11725          _add('detach', detached);
11726        };
11727
11728        detached = function detached() {
11729          me.attached = false;
11730
11731          _remove('resize', listener);
11732
11733          _add('attach', attached);
11734        };
11735
11736        if (platform.isAttached(me.canvas)) {
11737          attached();
11738        } else {
11739          detached();
11740        }
11741      }
11742    }, {
11743      key: "unbindEvents",
11744      value: function unbindEvents() {
11745        var me = this;
11746        each(me._listeners, function (listener, type) {
11747          me.platform.removeEventListener(me, type, listener);
11748        });
11749        me._listeners = {};
11750        each(me._responsiveListeners, function (listener, type) {
11751          me.platform.removeEventListener(me, type, listener);
11752        });
11753        me._responsiveListeners = undefined;
11754      }
11755    }, {
11756      key: "updateHoverStyle",
11757      value: function updateHoverStyle(items, mode, enabled) {
11758        var prefix = enabled ? 'set' : 'remove';
11759        var meta, item, i, ilen;
11760
11761        if (mode === 'dataset') {
11762          meta = this.getDatasetMeta(items[0].datasetIndex);
11763          meta.controller['_' + prefix + 'DatasetHoverStyle']();
11764        }
11765
11766        for (i = 0, ilen = items.length; i < ilen; ++i) {
11767          item = items[i];
11768          var controller = item && this.getDatasetMeta(item.datasetIndex).controller;
11769
11770          if (controller) {
11771            controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
11772          }
11773        }
11774      }
11775    }, {
11776      key: "getActiveElements",
11777      value: function getActiveElements() {
11778        return this._active || [];
11779      }
11780    }, {
11781      key: "setActiveElements",
11782      value: function setActiveElements(activeElements) {
11783        var me = this;
11784        var lastActive = me._active || [];
11785        var active = activeElements.map(function (_ref) {
11786          var datasetIndex = _ref.datasetIndex,
11787              index = _ref.index;
11788          var meta = me.getDatasetMeta(datasetIndex);
11789
11790          if (!meta) {
11791            throw new Error('No dataset found at index ' + datasetIndex);
11792          }
11793
11794          return {
11795            datasetIndex: datasetIndex,
11796            element: meta.data[index],
11797            index: index
11798          };
11799        });
11800        var changed = !_elementsEqual(active, lastActive);
11801
11802        if (changed) {
11803          me._active = active;
11804
11805          me._updateHoverStyles(active, lastActive);
11806        }
11807      }
11808    }, {
11809      key: "notifyPlugins",
11810      value: function notifyPlugins(hook, args, filter) {
11811        return this._plugins.notify(this, hook, args, filter);
11812      }
11813    }, {
11814      key: "_updateHoverStyles",
11815      value: function _updateHoverStyles(active, lastActive, replay) {
11816        var me = this;
11817        var hoverOptions = me.options.hover;
11818
11819        var diff = function diff(a, b) {
11820          return a.filter(function (x) {
11821            return !b.some(function (y) {
11822              return x.datasetIndex === y.datasetIndex && x.index === y.index;
11823            });
11824          });
11825        };
11826
11827        var deactivated = diff(lastActive, active);
11828        var activated = replay ? active : diff(active, lastActive);
11829
11830        if (deactivated.length) {
11831          me.updateHoverStyle(deactivated, hoverOptions.mode, false);
11832        }
11833
11834        if (activated.length && hoverOptions.mode) {
11835          me.updateHoverStyle(activated, hoverOptions.mode, true);
11836        }
11837      }
11838    }, {
11839      key: "_eventHandler",
11840      value: function _eventHandler(e, replay) {
11841        var _this6 = this;
11842
11843        var me = this;
11844        var args = {
11845          event: e,
11846          replay: replay,
11847          cancelable: true
11848        };
11849
11850        var eventFilter = function eventFilter(plugin) {
11851          return (plugin.options.events || _this6.options.events).includes(e.type);
11852        };
11853
11854        if (me.notifyPlugins('beforeEvent', args, eventFilter) === false) {
11855          return;
11856        }
11857
11858        var changed = me._handleEvent(e, replay);
11859
11860        args.cancelable = false;
11861        me.notifyPlugins('afterEvent', args, eventFilter);
11862
11863        if (changed || args.changed) {
11864          me.render();
11865        }
11866
11867        return me;
11868      }
11869    }, {
11870      key: "_handleEvent",
11871      value: function _handleEvent(e, replay) {
11872        var me = this;
11873        var _me$_active = me._active,
11874            lastActive = _me$_active === void 0 ? [] : _me$_active,
11875            options = me.options;
11876        var hoverOptions = options.hover;
11877        var useFinalPosition = replay;
11878        var active = [];
11879        var changed = false;
11880        var lastEvent = null;
11881
11882        if (e.type !== 'mouseout') {
11883          active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);
11884          lastEvent = e.type === 'click' ? me._lastEvent : e;
11885        }
11886
11887        me._lastEvent = null;
11888
11889        if (_isPointInArea(e, me.chartArea, me._minPadding)) {
11890          callback(options.onHover, [e, active, me], me);
11891
11892          if (e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu') {
11893            callback(options.onClick, [e, active, me], me);
11894          }
11895        }
11896
11897        changed = !_elementsEqual(active, lastActive);
11898
11899        if (changed || replay) {
11900          me._active = active;
11901
11902          me._updateHoverStyles(active, lastActive, replay);
11903        }
11904
11905        me._lastEvent = lastEvent;
11906        return changed;
11907      }
11908    }]);
11909
11910    return Chart;
11911  }();
11912
11913  var invalidatePlugins = function invalidatePlugins() {
11914    return each(Chart.instances, function (chart) {
11915      return chart._plugins.invalidate();
11916    });
11917  };
11918
11919  var enumerable = true;
11920  Object.defineProperties(Chart, {
11921    defaults: {
11922      enumerable: enumerable,
11923      value: defaults
11924    },
11925    instances: {
11926      enumerable: enumerable,
11927      value: instances
11928    },
11929    overrides: {
11930      enumerable: enumerable,
11931      value: overrides
11932    },
11933    registry: {
11934      enumerable: enumerable,
11935      value: registry
11936    },
11937    version: {
11938      enumerable: enumerable,
11939      value: version
11940    },
11941    getChart: {
11942      enumerable: enumerable,
11943      value: getChart
11944    },
11945    register: {
11946      enumerable: enumerable,
11947      value: function value() {
11948        registry.add.apply(registry, arguments);
11949        invalidatePlugins();
11950      }
11951    },
11952    unregister: {
11953      enumerable: enumerable,
11954      value: function value() {
11955        registry.remove.apply(registry, arguments);
11956        invalidatePlugins();
11957      }
11958    }
11959  });
11960
11961  function clipArc(ctx, element, endAngle) {
11962    var startAngle = element.startAngle,
11963        pixelMargin = element.pixelMargin,
11964        x = element.x,
11965        y = element.y,
11966        outerRadius = element.outerRadius,
11967        innerRadius = element.innerRadius;
11968    var angleMargin = pixelMargin / outerRadius;
11969    ctx.beginPath();
11970    ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);
11971
11972    if (innerRadius > pixelMargin) {
11973      angleMargin = pixelMargin / innerRadius;
11974      ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);
11975    } else {
11976      ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI);
11977    }
11978
11979    ctx.closePath();
11980    ctx.clip();
11981  }
11982
11983  function toRadiusCorners(value) {
11984    return _readValueToProps(value, ['outerStart', 'outerEnd', 'innerStart', 'innerEnd']);
11985  }
11986
11987  function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) {
11988    var o = toRadiusCorners(arc.options.borderRadius);
11989    var halfThickness = (outerRadius - innerRadius) / 2;
11990    var innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);
11991
11992    var computeOuterLimit = function computeOuterLimit(val) {
11993      var outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;
11994      return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit));
11995    };
11996
11997    return {
11998      outerStart: computeOuterLimit(o.outerStart),
11999      outerEnd: computeOuterLimit(o.outerEnd),
12000      innerStart: _limitValue(o.innerStart, 0, innerLimit),
12001      innerEnd: _limitValue(o.innerEnd, 0, innerLimit)
12002    };
12003  }
12004
12005  function rThetaToXY(r, theta, x, y) {
12006    return {
12007      x: x + r * Math.cos(theta),
12008      y: y + r * Math.sin(theta)
12009    };
12010  }
12011
12012  function pathArc(ctx, element, offset, spacing, end) {
12013    var x = element.x,
12014        y = element.y,
12015        start = element.startAngle,
12016        pixelMargin = element.pixelMargin,
12017        innerR = element.innerRadius;
12018    var outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0);
12019    var innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0;
12020    var spacingOffset = 0;
12021    var alpha = end - start;
12022
12023    if (spacing) {
12024      var noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;
12025      var noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;
12026      var avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;
12027      var adjustedAngle = avNogSpacingRadius !== 0 ? alpha * avNogSpacingRadius / (avNogSpacingRadius + spacing) : alpha;
12028      spacingOffset = (alpha - adjustedAngle) / 2;
12029    }
12030
12031    var beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius;
12032    var angleOffset = (alpha - beta) / 2;
12033    var startAngle = start + angleOffset + spacingOffset;
12034    var endAngle = end - angleOffset - spacingOffset;
12035
12036    var _parseBorderRadius$ = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle),
12037        outerStart = _parseBorderRadius$.outerStart,
12038        outerEnd = _parseBorderRadius$.outerEnd,
12039        innerStart = _parseBorderRadius$.innerStart,
12040        innerEnd = _parseBorderRadius$.innerEnd;
12041
12042    var outerStartAdjustedRadius = outerRadius - outerStart;
12043    var outerEndAdjustedRadius = outerRadius - outerEnd;
12044    var outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;
12045    var outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;
12046    var innerStartAdjustedRadius = innerRadius + innerStart;
12047    var innerEndAdjustedRadius = innerRadius + innerEnd;
12048    var innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;
12049    var innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;
12050    ctx.beginPath();
12051    ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerEndAdjustedAngle);
12052
12053    if (outerEnd > 0) {
12054      var pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);
12055      ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);
12056    }
12057
12058    var p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);
12059    ctx.lineTo(p4.x, p4.y);
12060
12061    if (innerEnd > 0) {
12062      var _pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);
12063
12064      ctx.arc(_pCenter.x, _pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);
12065    }
12066
12067    ctx.arc(x, y, innerRadius, endAngle - innerEnd / innerRadius, startAngle + innerStart / innerRadius, true);
12068
12069    if (innerStart > 0) {
12070      var _pCenter2 = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);
12071
12072      ctx.arc(_pCenter2.x, _pCenter2.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);
12073    }
12074
12075    var p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);
12076    ctx.lineTo(p8.x, p8.y);
12077
12078    if (outerStart > 0) {
12079      var _pCenter3 = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);
12080
12081      ctx.arc(_pCenter3.x, _pCenter3.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);
12082    }
12083
12084    ctx.closePath();
12085  }
12086
12087  function drawArc(ctx, element, offset, spacing) {
12088    var fullCircles = element.fullCircles,
12089        startAngle = element.startAngle,
12090        circumference = element.circumference;
12091    var endAngle = element.endAngle;
12092
12093    if (fullCircles) {
12094      pathArc(ctx, element, offset, spacing, startAngle + TAU);
12095
12096      for (var i = 0; i < fullCircles; ++i) {
12097        ctx.fill();
12098      }
12099
12100      if (!isNaN(circumference)) {
12101        endAngle = startAngle + circumference % TAU;
12102
12103        if (circumference % TAU === 0) {
12104          endAngle += TAU;
12105        }
12106      }
12107    }
12108
12109    pathArc(ctx, element, offset, spacing, endAngle);
12110    ctx.fill();
12111    return endAngle;
12112  }
12113
12114  function drawFullCircleBorders(ctx, element, inner) {
12115    var x = element.x,
12116        y = element.y,
12117        startAngle = element.startAngle,
12118        pixelMargin = element.pixelMargin,
12119        fullCircles = element.fullCircles;
12120    var outerRadius = Math.max(element.outerRadius - pixelMargin, 0);
12121    var innerRadius = element.innerRadius + pixelMargin;
12122    var i;
12123
12124    if (inner) {
12125      clipArc(ctx, element, startAngle + TAU);
12126    }
12127
12128    ctx.beginPath();
12129    ctx.arc(x, y, innerRadius, startAngle + TAU, startAngle, true);
12130
12131    for (i = 0; i < fullCircles; ++i) {
12132      ctx.stroke();
12133    }
12134
12135    ctx.beginPath();
12136    ctx.arc(x, y, outerRadius, startAngle, startAngle + TAU);
12137
12138    for (i = 0; i < fullCircles; ++i) {
12139      ctx.stroke();
12140    }
12141  }
12142
12143  function drawBorder(ctx, element, offset, spacing, endAngle) {
12144    var options = element.options;
12145    var inner = options.borderAlign === 'inner';
12146
12147    if (!options.borderWidth) {
12148      return;
12149    }
12150
12151    if (inner) {
12152      ctx.lineWidth = options.borderWidth * 2;
12153      ctx.lineJoin = 'round';
12154    } else {
12155      ctx.lineWidth = options.borderWidth;
12156      ctx.lineJoin = 'bevel';
12157    }
12158
12159    if (element.fullCircles) {
12160      drawFullCircleBorders(ctx, element, inner);
12161    }
12162
12163    if (inner) {
12164      clipArc(ctx, element, endAngle);
12165    }
12166
12167    pathArc(ctx, element, offset, spacing, endAngle);
12168    ctx.stroke();
12169  }
12170
12171  var ArcElement = /*#__PURE__*/function (_Element2) {
12172    _inherits(ArcElement, _Element2);
12173
12174    var _super12 = _createSuper(ArcElement);
12175
12176    function ArcElement(cfg) {
12177      var _this7;
12178
12179      _classCallCheck(this, ArcElement);
12180
12181      _this7 = _super12.call(this);
12182      _this7.options = undefined;
12183      _this7.circumference = undefined;
12184      _this7.startAngle = undefined;
12185      _this7.endAngle = undefined;
12186      _this7.innerRadius = undefined;
12187      _this7.outerRadius = undefined;
12188      _this7.pixelMargin = 0;
12189      _this7.fullCircles = 0;
12190
12191      if (cfg) {
12192        Object.assign(_assertThisInitialized(_this7), cfg);
12193      }
12194
12195      return _this7;
12196    }
12197
12198    _createClass(ArcElement, [{
12199      key: "inRange",
12200      value: function inRange(chartX, chartY, useFinalPosition) {
12201        var point = this.getProps(['x', 'y'], useFinalPosition);
12202
12203        var _getAngleFromPoint = getAngleFromPoint(point, {
12204          x: chartX,
12205          y: chartY
12206        }),
12207            angle = _getAngleFromPoint.angle,
12208            distance = _getAngleFromPoint.distance;
12209
12210        var _this$getProps2 = this.getProps(['startAngle', 'endAngle', 'innerRadius', 'outerRadius', 'circumference'], useFinalPosition),
12211            startAngle = _this$getProps2.startAngle,
12212            endAngle = _this$getProps2.endAngle,
12213            innerRadius = _this$getProps2.innerRadius,
12214            outerRadius = _this$getProps2.outerRadius,
12215            circumference = _this$getProps2.circumference;
12216
12217        var rAdjust = this.options.spacing / 2;
12218
12219        var betweenAngles = circumference >= TAU || _angleBetween(angle, startAngle, endAngle);
12220
12221        var withinRadius = distance >= innerRadius + rAdjust && distance <= outerRadius + rAdjust;
12222        return betweenAngles && withinRadius;
12223      }
12224    }, {
12225      key: "getCenterPoint",
12226      value: function getCenterPoint(useFinalPosition) {
12227        var _this$getProps3 = this.getProps(['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius', 'circumference'], useFinalPosition),
12228            x = _this$getProps3.x,
12229            y = _this$getProps3.y,
12230            startAngle = _this$getProps3.startAngle,
12231            endAngle = _this$getProps3.endAngle,
12232            innerRadius = _this$getProps3.innerRadius,
12233            outerRadius = _this$getProps3.outerRadius;
12234
12235        var _this$options4 = this.options,
12236            offset = _this$options4.offset,
12237            spacing = _this$options4.spacing;
12238        var halfAngle = (startAngle + endAngle) / 2;
12239        var halfRadius = (innerRadius + outerRadius + spacing + offset) / 2;
12240        return {
12241          x: x + Math.cos(halfAngle) * halfRadius,
12242          y: y + Math.sin(halfAngle) * halfRadius
12243        };
12244      }
12245    }, {
12246      key: "tooltipPosition",
12247      value: function tooltipPosition(useFinalPosition) {
12248        return this.getCenterPoint(useFinalPosition);
12249      }
12250    }, {
12251      key: "draw",
12252      value: function draw(ctx) {
12253        var me = this;
12254        var options = me.options,
12255            circumference = me.circumference;
12256        var offset = (options.offset || 0) / 2;
12257        var spacing = (options.spacing || 0) / 2;
12258        me.pixelMargin = options.borderAlign === 'inner' ? 0.33 : 0;
12259        me.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0;
12260
12261        if (circumference === 0 || me.innerRadius < 0 || me.outerRadius < 0) {
12262          return;
12263        }
12264
12265        ctx.save();
12266        var radiusOffset = 0;
12267
12268        if (offset) {
12269          radiusOffset = offset / 2;
12270          var halfAngle = (me.startAngle + me.endAngle) / 2;
12271          ctx.translate(Math.cos(halfAngle) * radiusOffset, Math.sin(halfAngle) * radiusOffset);
12272
12273          if (me.circumference >= PI) {
12274            radiusOffset = offset;
12275          }
12276        }
12277
12278        ctx.fillStyle = options.backgroundColor;
12279        ctx.strokeStyle = options.borderColor;
12280        var endAngle = drawArc(ctx, me, radiusOffset, spacing);
12281        drawBorder(ctx, me, radiusOffset, spacing, endAngle);
12282        ctx.restore();
12283      }
12284    }]);
12285
12286    return ArcElement;
12287  }(Element);
12288
12289  ArcElement.id = 'arc';
12290  ArcElement.defaults = {
12291    borderAlign: 'center',
12292    borderColor: '#fff',
12293    borderRadius: 0,
12294    borderWidth: 2,
12295    offset: 0,
12296    spacing: 0,
12297    angle: undefined
12298  };
12299  ArcElement.defaultRoutes = {
12300    backgroundColor: 'backgroundColor'
12301  };
12302
12303  function setStyle(ctx, options) {
12304    var style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : options;
12305    ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle);
12306    ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash));
12307    ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset);
12308    ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);
12309    ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth);
12310    ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor);
12311  }
12312
12313  function lineTo(ctx, previous, target) {
12314    ctx.lineTo(target.x, target.y);
12315  }
12316
12317  function getLineMethod(options) {
12318    if (options.stepped) {
12319      return _steppedLineTo;
12320    }
12321
12322    if (options.tension || options.cubicInterpolationMode === 'monotone') {
12323      return _bezierCurveTo;
12324    }
12325
12326    return lineTo;
12327  }
12328
12329  function pathVars(points, segment) {
12330    var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
12331    var count = points.length;
12332    var _params$start = params.start,
12333        paramsStart = _params$start === void 0 ? 0 : _params$start,
12334        _params$end = params.end,
12335        paramsEnd = _params$end === void 0 ? count - 1 : _params$end;
12336    var segmentStart = segment.start,
12337        segmentEnd = segment.end;
12338    var start = Math.max(paramsStart, segmentStart);
12339    var end = Math.min(paramsEnd, segmentEnd);
12340    var outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;
12341    return {
12342      count: count,
12343      start: start,
12344      loop: segment.loop,
12345      ilen: end < start && !outside ? count + end - start : end - start
12346    };
12347  }
12348
12349  function pathSegment(ctx, line, segment, params) {
12350    var points = line.points,
12351        options = line.options;
12352
12353    var _pathVars = pathVars(points, segment, params),
12354        count = _pathVars.count,
12355        start = _pathVars.start,
12356        loop = _pathVars.loop,
12357        ilen = _pathVars.ilen;
12358
12359    var lineMethod = getLineMethod(options);
12360
12361    var _ref2 = params || {},
12362        _ref2$move = _ref2.move,
12363        move = _ref2$move === void 0 ? true : _ref2$move,
12364        reverse = _ref2.reverse;
12365
12366    var i, point, prev;
12367
12368    for (i = 0; i <= ilen; ++i) {
12369      point = points[(start + (reverse ? ilen - i : i)) % count];
12370
12371      if (point.skip) {
12372        continue;
12373      } else if (move) {
12374        ctx.moveTo(point.x, point.y);
12375        move = false;
12376      } else {
12377        lineMethod(ctx, prev, point, reverse, options.stepped);
12378      }
12379
12380      prev = point;
12381    }
12382
12383    if (loop) {
12384      point = points[(start + (reverse ? ilen : 0)) % count];
12385      lineMethod(ctx, prev, point, reverse, options.stepped);
12386    }
12387
12388    return !!loop;
12389  }
12390
12391  function fastPathSegment(ctx, line, segment, params) {
12392    var points = line.points;
12393
12394    var _pathVars2 = pathVars(points, segment, params),
12395        count = _pathVars2.count,
12396        start = _pathVars2.start,
12397        ilen = _pathVars2.ilen;
12398
12399    var _ref3 = params || {},
12400        _ref3$move = _ref3.move,
12401        move = _ref3$move === void 0 ? true : _ref3$move,
12402        reverse = _ref3.reverse;
12403
12404    var avgX = 0;
12405    var countX = 0;
12406    var i, point, prevX, minY, maxY, lastY;
12407
12408    var pointIndex = function pointIndex(index) {
12409      return (start + (reverse ? ilen - index : index)) % count;
12410    };
12411
12412    var drawX = function drawX() {
12413      if (minY !== maxY) {
12414        ctx.lineTo(avgX, maxY);
12415        ctx.lineTo(avgX, minY);
12416        ctx.lineTo(avgX, lastY);
12417      }
12418    };
12419
12420    if (move) {
12421      point = points[pointIndex(0)];
12422      ctx.moveTo(point.x, point.y);
12423    }
12424
12425    for (i = 0; i <= ilen; ++i) {
12426      point = points[pointIndex(i)];
12427
12428      if (point.skip) {
12429        continue;
12430      }
12431
12432      var x = point.x;
12433      var y = point.y;
12434      var truncX = x | 0;
12435
12436      if (truncX === prevX) {
12437        if (y < minY) {
12438          minY = y;
12439        } else if (y > maxY) {
12440          maxY = y;
12441        }
12442
12443        avgX = (countX * avgX + x) / ++countX;
12444      } else {
12445        drawX();
12446        ctx.lineTo(x, y);
12447        prevX = truncX;
12448        countX = 0;
12449        minY = maxY = y;
12450      }
12451
12452      lastY = y;
12453    }
12454
12455    drawX();
12456  }
12457
12458  function _getSegmentMethod(line) {
12459    var opts = line.options;
12460    var borderDash = opts.borderDash && opts.borderDash.length;
12461    var useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;
12462    return useFastPath ? fastPathSegment : pathSegment;
12463  }
12464
12465  function _getInterpolationMethod(options) {
12466    if (options.stepped) {
12467      return _steppedInterpolation;
12468    }
12469
12470    if (options.tension || options.cubicInterpolationMode === 'monotone') {
12471      return _bezierInterpolation;
12472    }
12473
12474    return _pointInLine;
12475  }
12476
12477  function strokePathWithCache(ctx, line, start, count) {
12478    var path = line._path;
12479
12480    if (!path) {
12481      path = line._path = new Path2D();
12482
12483      if (line.path(path, start, count)) {
12484        path.closePath();
12485      }
12486    }
12487
12488    setStyle(ctx, line.options);
12489    ctx.stroke(path);
12490  }
12491
12492  function strokePathDirect(ctx, line, start, count) {
12493    var segments = line.segments,
12494        options = line.options;
12495
12496    var segmentMethod = _getSegmentMethod(line);
12497
12498    var _iterator8 = _createForOfIteratorHelper(segments),
12499        _step8;
12500
12501    try {
12502      for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
12503        var segment = _step8.value;
12504        setStyle(ctx, options, segment.style);
12505        ctx.beginPath();
12506
12507        if (segmentMethod(ctx, line, segment, {
12508          start: start,
12509          end: start + count - 1
12510        })) {
12511          ctx.closePath();
12512        }
12513
12514        ctx.stroke();
12515      }
12516    } catch (err) {
12517      _iterator8.e(err);
12518    } finally {
12519      _iterator8.f();
12520    }
12521  }
12522
12523  var usePath2D = typeof Path2D === 'function';
12524
12525  function _draw(ctx, line, start, count) {
12526    if (usePath2D && line.segments.length === 1) {
12527      strokePathWithCache(ctx, line, start, count);
12528    } else {
12529      strokePathDirect(ctx, line, start, count);
12530    }
12531  }
12532
12533  var LineElement = /*#__PURE__*/function (_Element3) {
12534    _inherits(LineElement, _Element3);
12535
12536    var _super13 = _createSuper(LineElement);
12537
12538    function LineElement(cfg) {
12539      var _this8;
12540
12541      _classCallCheck(this, LineElement);
12542
12543      _this8 = _super13.call(this);
12544      _this8.animated = true;
12545      _this8.options = undefined;
12546      _this8._loop = undefined;
12547      _this8._fullLoop = undefined;
12548      _this8._path = undefined;
12549      _this8._points = undefined;
12550      _this8._segments = undefined;
12551      _this8._decimated = false;
12552      _this8._pointsUpdated = false;
12553
12554      if (cfg) {
12555        Object.assign(_assertThisInitialized(_this8), cfg);
12556      }
12557
12558      return _this8;
12559    }
12560
12561    _createClass(LineElement, [{
12562      key: "updateControlPoints",
12563      value: function updateControlPoints(chartArea, indexAxis) {
12564        var me = this;
12565        var options = me.options;
12566
12567        if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !me._pointsUpdated) {
12568          var loop = options.spanGaps ? me._loop : me._fullLoop;
12569
12570          _updateBezierControlPoints(me._points, options, chartArea, loop, indexAxis);
12571
12572          me._pointsUpdated = true;
12573        }
12574      }
12575    }, {
12576      key: "points",
12577      get: function get() {
12578        return this._points;
12579      },
12580      set: function set(points) {
12581        var me = this;
12582        me._points = points;
12583        delete me._segments;
12584        delete me._path;
12585        me._pointsUpdated = false;
12586      }
12587    }, {
12588      key: "segments",
12589      get: function get() {
12590        return this._segments || (this._segments = _computeSegments(this, this.options.segment));
12591      }
12592    }, {
12593      key: "first",
12594      value: function first() {
12595        var segments = this.segments;
12596        var points = this.points;
12597        return segments.length && points[segments[0].start];
12598      }
12599    }, {
12600      key: "last",
12601      value: function last() {
12602        var segments = this.segments;
12603        var points = this.points;
12604        var count = segments.length;
12605        return count && points[segments[count - 1].end];
12606      }
12607    }, {
12608      key: "interpolate",
12609      value: function interpolate(point, property) {
12610        var me = this;
12611        var options = me.options;
12612        var value = point[property];
12613        var points = me.points;
12614
12615        var segments = _boundSegments(me, {
12616          property: property,
12617          start: value,
12618          end: value
12619        });
12620
12621        if (!segments.length) {
12622          return;
12623        }
12624
12625        var result = [];
12626
12627        var _interpolate = _getInterpolationMethod(options);
12628
12629        var i, ilen;
12630
12631        for (i = 0, ilen = segments.length; i < ilen; ++i) {
12632          var _segments$i = segments[i],
12633              start = _segments$i.start,
12634              end = _segments$i.end;
12635          var p1 = points[start];
12636          var p2 = points[end];
12637
12638          if (p1 === p2) {
12639            result.push(p1);
12640            continue;
12641          }
12642
12643          var t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));
12644
12645          var interpolated = _interpolate(p1, p2, t, options.stepped);
12646
12647          interpolated[property] = point[property];
12648          result.push(interpolated);
12649        }
12650
12651        return result.length === 1 ? result[0] : result;
12652      }
12653    }, {
12654      key: "pathSegment",
12655      value: function pathSegment(ctx, segment, params) {
12656        var segmentMethod = _getSegmentMethod(this);
12657
12658        return segmentMethod(ctx, this, segment, params);
12659      }
12660    }, {
12661      key: "path",
12662      value: function path(ctx, start, count) {
12663        var me = this;
12664        var segments = me.segments;
12665
12666        var segmentMethod = _getSegmentMethod(me);
12667
12668        var loop = me._loop;
12669        start = start || 0;
12670        count = count || me.points.length - start;
12671
12672        var _iterator9 = _createForOfIteratorHelper(segments),
12673            _step9;
12674
12675        try {
12676          for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
12677            var segment = _step9.value;
12678            loop &= segmentMethod(ctx, me, segment, {
12679              start: start,
12680              end: start + count - 1
12681            });
12682          }
12683        } catch (err) {
12684          _iterator9.e(err);
12685        } finally {
12686          _iterator9.f();
12687        }
12688
12689        return !!loop;
12690      }
12691    }, {
12692      key: "draw",
12693      value: function draw(ctx, chartArea, start, count) {
12694        var me = this;
12695        var options = me.options || {};
12696        var points = me.points || [];
12697
12698        if (!points.length || !options.borderWidth) {
12699          return;
12700        }
12701
12702        ctx.save();
12703
12704        _draw(ctx, me, start, count);
12705
12706        ctx.restore();
12707
12708        if (me.animated) {
12709          me._pointsUpdated = false;
12710          me._path = undefined;
12711        }
12712      }
12713    }]);
12714
12715    return LineElement;
12716  }(Element);
12717
12718  LineElement.id = 'line';
12719  LineElement.defaults = {
12720    borderCapStyle: 'butt',
12721    borderDash: [],
12722    borderDashOffset: 0,
12723    borderJoinStyle: 'miter',
12724    borderWidth: 3,
12725    capBezierPoints: true,
12726    cubicInterpolationMode: 'default',
12727    fill: false,
12728    spanGaps: false,
12729    stepped: false,
12730    tension: 0
12731  };
12732  LineElement.defaultRoutes = {
12733    backgroundColor: 'backgroundColor',
12734    borderColor: 'borderColor'
12735  };
12736  LineElement.descriptors = {
12737    _scriptable: true,
12738    _indexable: function _indexable(name) {
12739      return name !== 'borderDash' && name !== 'fill';
12740    }
12741  };
12742
12743  function inRange$1(el, pos, axis, useFinalPosition) {
12744    var options = el.options;
12745
12746    var _el$getProps = el.getProps([axis], useFinalPosition),
12747        value = _el$getProps[axis];
12748
12749    return Math.abs(pos - value) < options.radius + options.hitRadius;
12750  }
12751
12752  var PointElement = /*#__PURE__*/function (_Element4) {
12753    _inherits(PointElement, _Element4);
12754
12755    var _super14 = _createSuper(PointElement);
12756
12757    function PointElement(cfg) {
12758      var _this9;
12759
12760      _classCallCheck(this, PointElement);
12761
12762      _this9 = _super14.call(this);
12763      _this9.options = undefined;
12764      _this9.parsed = undefined;
12765      _this9.skip = undefined;
12766      _this9.stop = undefined;
12767
12768      if (cfg) {
12769        Object.assign(_assertThisInitialized(_this9), cfg);
12770      }
12771
12772      return _this9;
12773    }
12774
12775    _createClass(PointElement, [{
12776      key: "inRange",
12777      value: function inRange(mouseX, mouseY, useFinalPosition) {
12778        var options = this.options;
12779
12780        var _this$getProps4 = this.getProps(['x', 'y'], useFinalPosition),
12781            x = _this$getProps4.x,
12782            y = _this$getProps4.y;
12783
12784        return Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2) < Math.pow(options.hitRadius + options.radius, 2);
12785      }
12786    }, {
12787      key: "inXRange",
12788      value: function inXRange(mouseX, useFinalPosition) {
12789        return inRange$1(this, mouseX, 'x', useFinalPosition);
12790      }
12791    }, {
12792      key: "inYRange",
12793      value: function inYRange(mouseY, useFinalPosition) {
12794        return inRange$1(this, mouseY, 'y', useFinalPosition);
12795      }
12796    }, {
12797      key: "getCenterPoint",
12798      value: function getCenterPoint(useFinalPosition) {
12799        var _this$getProps5 = this.getProps(['x', 'y'], useFinalPosition),
12800            x = _this$getProps5.x,
12801            y = _this$getProps5.y;
12802
12803        return {
12804          x: x,
12805          y: y
12806        };
12807      }
12808    }, {
12809      key: "size",
12810      value: function size(options) {
12811        options = options || this.options || {};
12812        var radius = options.radius || 0;
12813        radius = Math.max(radius, radius && options.hoverRadius || 0);
12814        var borderWidth = radius && options.borderWidth || 0;
12815        return (radius + borderWidth) * 2;
12816      }
12817    }, {
12818      key: "draw",
12819      value: function draw(ctx) {
12820        var me = this;
12821        var options = me.options;
12822
12823        if (me.skip || options.radius < 0.1) {
12824          return;
12825        }
12826
12827        ctx.strokeStyle = options.borderColor;
12828        ctx.lineWidth = options.borderWidth;
12829        ctx.fillStyle = options.backgroundColor;
12830        drawPoint(ctx, options, me.x, me.y);
12831      }
12832    }, {
12833      key: "getRange",
12834      value: function getRange() {
12835        var options = this.options || {};
12836        return options.radius + options.hitRadius;
12837      }
12838    }]);
12839
12840    return PointElement;
12841  }(Element);
12842
12843  PointElement.id = 'point';
12844  PointElement.defaults = {
12845    borderWidth: 1,
12846    hitRadius: 1,
12847    hoverBorderWidth: 1,
12848    hoverRadius: 4,
12849    pointStyle: 'circle',
12850    radius: 3,
12851    rotation: 0
12852  };
12853  PointElement.defaultRoutes = {
12854    backgroundColor: 'backgroundColor',
12855    borderColor: 'borderColor'
12856  };
12857
12858  function getBarBounds(bar, useFinalPosition) {
12859    var _bar$getProps = bar.getProps(['x', 'y', 'base', 'width', 'height'], useFinalPosition),
12860        x = _bar$getProps.x,
12861        y = _bar$getProps.y,
12862        base = _bar$getProps.base,
12863        width = _bar$getProps.width,
12864        height = _bar$getProps.height;
12865
12866    var left, right, top, bottom, half;
12867
12868    if (bar.horizontal) {
12869      half = height / 2;
12870      left = Math.min(x, base);
12871      right = Math.max(x, base);
12872      top = y - half;
12873      bottom = y + half;
12874    } else {
12875      half = width / 2;
12876      left = x - half;
12877      right = x + half;
12878      top = Math.min(y, base);
12879      bottom = Math.max(y, base);
12880    }
12881
12882    return {
12883      left: left,
12884      top: top,
12885      right: right,
12886      bottom: bottom
12887    };
12888  }
12889
12890  function parseBorderSkipped(bar) {
12891    var edge = bar.options.borderSkipped;
12892    var res = {};
12893
12894    if (!edge) {
12895      return res;
12896    }
12897
12898    edge = bar.horizontal ? parseEdge(edge, 'left', 'right', bar.base > bar.x) : parseEdge(edge, 'bottom', 'top', bar.base < bar.y);
12899    res[edge] = true;
12900    return res;
12901  }
12902
12903  function parseEdge(edge, a, b, reverse) {
12904    if (reverse) {
12905      edge = swap(edge, a, b);
12906      edge = startEnd(edge, b, a);
12907    } else {
12908      edge = startEnd(edge, a, b);
12909    }
12910
12911    return edge;
12912  }
12913
12914  function swap(orig, v1, v2) {
12915    return orig === v1 ? v2 : orig === v2 ? v1 : orig;
12916  }
12917
12918  function startEnd(v, start, end) {
12919    return v === 'start' ? start : v === 'end' ? end : v;
12920  }
12921
12922  function skipOrLimit(skip, value, min, max) {
12923    return skip ? 0 : Math.max(Math.min(value, max), min);
12924  }
12925
12926  function parseBorderWidth(bar, maxW, maxH) {
12927    var value = bar.options.borderWidth;
12928    var skip = parseBorderSkipped(bar);
12929    var o = toTRBL(value);
12930    return {
12931      t: skipOrLimit(skip.top, o.top, 0, maxH),
12932      r: skipOrLimit(skip.right, o.right, 0, maxW),
12933      b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),
12934      l: skipOrLimit(skip.left, o.left, 0, maxW)
12935    };
12936  }
12937
12938  function parseBorderRadius(bar, maxW, maxH) {
12939    var _bar$getProps2 = bar.getProps(['enableBorderRadius']),
12940        enableBorderRadius = _bar$getProps2.enableBorderRadius;
12941
12942    var value = bar.options.borderRadius;
12943    var o = toTRBLCorners(value);
12944    var maxR = Math.min(maxW, maxH);
12945    var skip = parseBorderSkipped(bar);
12946    var enableBorder = enableBorderRadius || isObject(value);
12947    return {
12948      topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),
12949      topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),
12950      bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),
12951      bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)
12952    };
12953  }
12954
12955  function boundingRects(bar) {
12956    var bounds = getBarBounds(bar);
12957    var width = bounds.right - bounds.left;
12958    var height = bounds.bottom - bounds.top;
12959    var border = parseBorderWidth(bar, width / 2, height / 2);
12960    var radius = parseBorderRadius(bar, width / 2, height / 2);
12961    return {
12962      outer: {
12963        x: bounds.left,
12964        y: bounds.top,
12965        w: width,
12966        h: height,
12967        radius: radius
12968      },
12969      inner: {
12970        x: bounds.left + border.l,
12971        y: bounds.top + border.t,
12972        w: width - border.l - border.r,
12973        h: height - border.t - border.b,
12974        radius: {
12975          topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),
12976          topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),
12977          bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),
12978          bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r))
12979        }
12980      }
12981    };
12982  }
12983
12984  function _inRange(bar, x, y, useFinalPosition) {
12985    var skipX = x === null;
12986    var skipY = y === null;
12987    var skipBoth = skipX && skipY;
12988    var bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);
12989    return bounds && (skipX || x >= bounds.left && x <= bounds.right) && (skipY || y >= bounds.top && y <= bounds.bottom);
12990  }
12991
12992  function hasRadius(radius) {
12993    return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;
12994  }
12995
12996  function addNormalRectPath(ctx, rect) {
12997    ctx.rect(rect.x, rect.y, rect.w, rect.h);
12998  }
12999
13000  var BarElement = /*#__PURE__*/function (_Element5) {
13001    _inherits(BarElement, _Element5);
13002
13003    var _super15 = _createSuper(BarElement);
13004
13005    function BarElement(cfg) {
13006      var _this10;
13007
13008      _classCallCheck(this, BarElement);
13009
13010      _this10 = _super15.call(this);
13011      _this10.options = undefined;
13012      _this10.horizontal = undefined;
13013      _this10.base = undefined;
13014      _this10.width = undefined;
13015      _this10.height = undefined;
13016
13017      if (cfg) {
13018        Object.assign(_assertThisInitialized(_this10), cfg);
13019      }
13020
13021      return _this10;
13022    }
13023
13024    _createClass(BarElement, [{
13025      key: "draw",
13026      value: function draw(ctx) {
13027        var options = this.options;
13028
13029        var _boundingRects = boundingRects(this),
13030            inner = _boundingRects.inner,
13031            outer = _boundingRects.outer;
13032
13033        var addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath;
13034        ctx.save();
13035
13036        if (outer.w !== inner.w || outer.h !== inner.h) {
13037          ctx.beginPath();
13038          addRectPath(ctx, outer);
13039          ctx.clip();
13040          addRectPath(ctx, inner);
13041          ctx.fillStyle = options.borderColor;
13042          ctx.fill('evenodd');
13043        }
13044
13045        ctx.beginPath();
13046        addRectPath(ctx, inner);
13047        ctx.fillStyle = options.backgroundColor;
13048        ctx.fill();
13049        ctx.restore();
13050      }
13051    }, {
13052      key: "inRange",
13053      value: function inRange(mouseX, mouseY, useFinalPosition) {
13054        return _inRange(this, mouseX, mouseY, useFinalPosition);
13055      }
13056    }, {
13057      key: "inXRange",
13058      value: function inXRange(mouseX, useFinalPosition) {
13059        return _inRange(this, mouseX, null, useFinalPosition);
13060      }
13061    }, {
13062      key: "inYRange",
13063      value: function inYRange(mouseY, useFinalPosition) {
13064        return _inRange(this, null, mouseY, useFinalPosition);
13065      }
13066    }, {
13067      key: "getCenterPoint",
13068      value: function getCenterPoint(useFinalPosition) {
13069        var _this$getProps6 = this.getProps(['x', 'y', 'base', 'horizontal'], useFinalPosition),
13070            x = _this$getProps6.x,
13071            y = _this$getProps6.y,
13072            base = _this$getProps6.base,
13073            horizontal = _this$getProps6.horizontal;
13074
13075        return {
13076          x: horizontal ? (x + base) / 2 : x,
13077          y: horizontal ? y : (y + base) / 2
13078        };
13079      }
13080    }, {
13081      key: "getRange",
13082      value: function getRange(axis) {
13083        return axis === 'x' ? this.width / 2 : this.height / 2;
13084      }
13085    }]);
13086
13087    return BarElement;
13088  }(Element);
13089
13090  BarElement.id = 'bar';
13091  BarElement.defaults = {
13092    borderSkipped: 'start',
13093    borderWidth: 0,
13094    borderRadius: 0,
13095    enableBorderRadius: true,
13096    pointStyle: undefined
13097  };
13098  BarElement.defaultRoutes = {
13099    backgroundColor: 'backgroundColor',
13100    borderColor: 'borderColor'
13101  };
13102  var elements = /*#__PURE__*/Object.freeze({
13103    __proto__: null,
13104    ArcElement: ArcElement,
13105    LineElement: LineElement,
13106    PointElement: PointElement,
13107    BarElement: BarElement
13108  });
13109
13110  function lttbDecimation(data, start, count, availableWidth, options) {
13111    var samples = options.samples || availableWidth;
13112
13113    if (samples >= count) {
13114      return data.slice(start, start + count);
13115    }
13116
13117    var decimated = [];
13118    var bucketWidth = (count - 2) / (samples - 2);
13119    var sampledIndex = 0;
13120    var endIndex = start + count - 1;
13121    var a = start;
13122    var i, maxAreaPoint, maxArea, area, nextA;
13123    decimated[sampledIndex++] = data[a];
13124
13125    for (i = 0; i < samples - 2; i++) {
13126      var avgX = 0;
13127      var avgY = 0;
13128      var j = void 0;
13129      var avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;
13130      var avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;
13131      var avgRangeLength = avgRangeEnd - avgRangeStart;
13132
13133      for (j = avgRangeStart; j < avgRangeEnd; j++) {
13134        avgX += data[j].x;
13135        avgY += data[j].y;
13136      }
13137
13138      avgX /= avgRangeLength;
13139      avgY /= avgRangeLength;
13140      var rangeOffs = Math.floor(i * bucketWidth) + 1 + start;
13141      var rangeTo = Math.floor((i + 1) * bucketWidth) + 1 + start;
13142      var _data$a = data[a],
13143          pointAx = _data$a.x,
13144          pointAy = _data$a.y;
13145      maxArea = area = -1;
13146
13147      for (j = rangeOffs; j < rangeTo; j++) {
13148        area = 0.5 * Math.abs((pointAx - avgX) * (data[j].y - pointAy) - (pointAx - data[j].x) * (avgY - pointAy));
13149
13150        if (area > maxArea) {
13151          maxArea = area;
13152          maxAreaPoint = data[j];
13153          nextA = j;
13154        }
13155      }
13156
13157      decimated[sampledIndex++] = maxAreaPoint;
13158      a = nextA;
13159    }
13160
13161    decimated[sampledIndex++] = data[endIndex];
13162    return decimated;
13163  }
13164
13165  function minMaxDecimation(data, start, count, availableWidth) {
13166    var avgX = 0;
13167    var countX = 0;
13168    var i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;
13169    var decimated = [];
13170    var endIndex = start + count - 1;
13171    var xMin = data[start].x;
13172    var xMax = data[endIndex].x;
13173    var dx = xMax - xMin;
13174
13175    for (i = start; i < start + count; ++i) {
13176      point = data[i];
13177      x = (point.x - xMin) / dx * availableWidth;
13178      y = point.y;
13179      var truncX = x | 0;
13180
13181      if (truncX === prevX) {
13182        if (y < minY) {
13183          minY = y;
13184          minIndex = i;
13185        } else if (y > maxY) {
13186          maxY = y;
13187          maxIndex = i;
13188        }
13189
13190        avgX = (countX * avgX + point.x) / ++countX;
13191      } else {
13192        var lastIndex = i - 1;
13193
13194        if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) {
13195          var intermediateIndex1 = Math.min(minIndex, maxIndex);
13196          var intermediateIndex2 = Math.max(minIndex, maxIndex);
13197
13198          if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {
13199            decimated.push(_objectSpread2(_objectSpread2({}, data[intermediateIndex1]), {}, {
13200              x: avgX
13201            }));
13202          }
13203
13204          if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {
13205            decimated.push(_objectSpread2(_objectSpread2({}, data[intermediateIndex2]), {}, {
13206              x: avgX
13207            }));
13208          }
13209        }
13210
13211        if (i > 0 && lastIndex !== startIndex) {
13212          decimated.push(data[lastIndex]);
13213        }
13214
13215        decimated.push(point);
13216        prevX = truncX;
13217        countX = 0;
13218        minY = maxY = y;
13219        minIndex = maxIndex = startIndex = i;
13220      }
13221    }
13222
13223    return decimated;
13224  }
13225
13226  function cleanDecimatedDataset(dataset) {
13227    if (dataset._decimated) {
13228      var data = dataset._data;
13229      delete dataset._decimated;
13230      delete dataset._data;
13231      Object.defineProperty(dataset, 'data', {
13232        value: data
13233      });
13234    }
13235  }
13236
13237  function cleanDecimatedData(chart) {
13238    chart.data.datasets.forEach(function (dataset) {
13239      cleanDecimatedDataset(dataset);
13240    });
13241  }
13242
13243  function getStartAndCountOfVisiblePointsSimplified(meta, points) {
13244    var pointCount = points.length;
13245    var start = 0;
13246    var count;
13247    var iScale = meta.iScale;
13248
13249    var _iScale$getUserBounds2 = iScale.getUserBounds(),
13250        min = _iScale$getUserBounds2.min,
13251        max = _iScale$getUserBounds2.max,
13252        minDefined = _iScale$getUserBounds2.minDefined,
13253        maxDefined = _iScale$getUserBounds2.maxDefined;
13254
13255    if (minDefined) {
13256      start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);
13257    }
13258
13259    if (maxDefined) {
13260      count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;
13261    } else {
13262      count = pointCount - start;
13263    }
13264
13265    return {
13266      start: start,
13267      count: count
13268    };
13269  }
13270
13271  var plugin_decimation = {
13272    id: 'decimation',
13273    defaults: {
13274      algorithm: 'min-max',
13275      enabled: false
13276    },
13277    beforeElementsUpdate: function beforeElementsUpdate(chart, args, options) {
13278      if (!options.enabled) {
13279        cleanDecimatedData(chart);
13280        return;
13281      }
13282
13283      var availableWidth = chart.width;
13284      chart.data.datasets.forEach(function (dataset, datasetIndex) {
13285        var _data = dataset._data,
13286            indexAxis = dataset.indexAxis;
13287        var meta = chart.getDatasetMeta(datasetIndex);
13288        var data = _data || dataset.data;
13289
13290        if (resolve([indexAxis, chart.options.indexAxis]) === 'y') {
13291          return;
13292        }
13293
13294        if (meta.type !== 'line') {
13295          return;
13296        }
13297
13298        var xAxis = chart.scales[meta.xAxisID];
13299
13300        if (xAxis.type !== 'linear' && xAxis.type !== 'time') {
13301          return;
13302        }
13303
13304        if (chart.options.parsing) {
13305          return;
13306        }
13307
13308        var _getStartAndCountOfVi2 = getStartAndCountOfVisiblePointsSimplified(meta, data),
13309            start = _getStartAndCountOfVi2.start,
13310            count = _getStartAndCountOfVi2.count;
13311
13312        if (count <= 4 * availableWidth) {
13313          cleanDecimatedDataset(dataset);
13314          return;
13315        }
13316
13317        if (isNullOrUndef(_data)) {
13318          dataset._data = data;
13319          delete dataset.data;
13320          Object.defineProperty(dataset, 'data', {
13321            configurable: true,
13322            enumerable: true,
13323            get: function get() {
13324              return this._decimated;
13325            },
13326            set: function set(d) {
13327              this._data = d;
13328            }
13329          });
13330        }
13331
13332        var decimated;
13333
13334        switch (options.algorithm) {
13335          case 'lttb':
13336            decimated = lttbDecimation(data, start, count, availableWidth, options);
13337            break;
13338
13339          case 'min-max':
13340            decimated = minMaxDecimation(data, start, count, availableWidth);
13341            break;
13342
13343          default:
13344            throw new Error("Unsupported decimation algorithm '".concat(options.algorithm, "'"));
13345        }
13346
13347        dataset._decimated = decimated;
13348      });
13349    },
13350    destroy: function destroy(chart) {
13351      cleanDecimatedData(chart);
13352    }
13353  };
13354
13355  function getLineByIndex(chart, index) {
13356    var meta = chart.getDatasetMeta(index);
13357    var visible = meta && chart.isDatasetVisible(index);
13358    return visible ? meta.dataset : null;
13359  }
13360
13361  function parseFillOption(line) {
13362    var options = line.options;
13363    var fillOption = options.fill;
13364    var fill = valueOrDefault(fillOption && fillOption.target, fillOption);
13365
13366    if (fill === undefined) {
13367      fill = !!options.backgroundColor;
13368    }
13369
13370    if (fill === false || fill === null) {
13371      return false;
13372    }
13373
13374    if (fill === true) {
13375      return 'origin';
13376    }
13377
13378    return fill;
13379  }
13380
13381  function decodeFill(line, index, count) {
13382    var fill = parseFillOption(line);
13383
13384    if (isObject(fill)) {
13385      return isNaN(fill.value) ? false : fill;
13386    }
13387
13388    var target = parseFloat(fill);
13389
13390    if (isNumberFinite(target) && Math.floor(target) === target) {
13391      if (fill[0] === '-' || fill[0] === '+') {
13392        target = index + target;
13393      }
13394
13395      if (target === index || target < 0 || target >= count) {
13396        return false;
13397      }
13398
13399      return target;
13400    }
13401
13402    return ['origin', 'start', 'end', 'stack'].indexOf(fill) >= 0 && fill;
13403  }
13404
13405  function computeLinearBoundary(source) {
13406    var _source$scale = source.scale,
13407        scale = _source$scale === void 0 ? {} : _source$scale,
13408        fill = source.fill;
13409    var target = null;
13410    var horizontal;
13411
13412    if (fill === 'start') {
13413      target = scale.bottom;
13414    } else if (fill === 'end') {
13415      target = scale.top;
13416    } else if (isObject(fill)) {
13417      target = scale.getPixelForValue(fill.value);
13418    } else if (scale.getBasePixel) {
13419      target = scale.getBasePixel();
13420    }
13421
13422    if (isNumberFinite(target)) {
13423      horizontal = scale.isHorizontal();
13424      return {
13425        x: horizontal ? target : null,
13426        y: horizontal ? null : target
13427      };
13428    }
13429
13430    return null;
13431  }
13432
13433  var simpleArc = /*#__PURE__*/function () {
13434    function simpleArc(opts) {
13435      _classCallCheck(this, simpleArc);
13436
13437      this.x = opts.x;
13438      this.y = opts.y;
13439      this.radius = opts.radius;
13440    }
13441
13442    _createClass(simpleArc, [{
13443      key: "pathSegment",
13444      value: function pathSegment(ctx, bounds, opts) {
13445        var x = this.x,
13446            y = this.y,
13447            radius = this.radius;
13448        bounds = bounds || {
13449          start: 0,
13450          end: TAU
13451        };
13452        ctx.arc(x, y, radius, bounds.end, bounds.start, true);
13453        return !opts.bounds;
13454      }
13455    }, {
13456      key: "interpolate",
13457      value: function interpolate(point) {
13458        var x = this.x,
13459            y = this.y,
13460            radius = this.radius;
13461        var angle = point.angle;
13462        return {
13463          x: x + Math.cos(angle) * radius,
13464          y: y + Math.sin(angle) * radius,
13465          angle: angle
13466        };
13467      }
13468    }]);
13469
13470    return simpleArc;
13471  }();
13472
13473  function computeCircularBoundary(source) {
13474    var scale = source.scale,
13475        fill = source.fill;
13476    var options = scale.options;
13477    var length = scale.getLabels().length;
13478    var target = [];
13479    var start = options.reverse ? scale.max : scale.min;
13480    var end = options.reverse ? scale.min : scale.max;
13481    var i, center, value;
13482
13483    if (fill === 'start') {
13484      value = start;
13485    } else if (fill === 'end') {
13486      value = end;
13487    } else if (isObject(fill)) {
13488      value = fill.value;
13489    } else {
13490      value = scale.getBaseValue();
13491    }
13492
13493    if (options.grid.circular) {
13494      center = scale.getPointPositionForValue(0, start);
13495      return new simpleArc({
13496        x: center.x,
13497        y: center.y,
13498        radius: scale.getDistanceFromCenterForValue(value)
13499      });
13500    }
13501
13502    for (i = 0; i < length; ++i) {
13503      target.push(scale.getPointPositionForValue(i, value));
13504    }
13505
13506    return target;
13507  }
13508
13509  function computeBoundary(source) {
13510    var scale = source.scale || {};
13511
13512    if (scale.getPointPositionForValue) {
13513      return computeCircularBoundary(source);
13514    }
13515
13516    return computeLinearBoundary(source);
13517  }
13518
13519  function findSegmentEnd(start, end, points) {
13520    for (; end > start; end--) {
13521      var point = points[end];
13522
13523      if (!isNaN(point.x) && !isNaN(point.y)) {
13524        break;
13525      }
13526    }
13527
13528    return end;
13529  }
13530
13531  function pointsFromSegments(boundary, line) {
13532    var _ref4 = boundary || {},
13533        _ref4$x = _ref4.x,
13534        x = _ref4$x === void 0 ? null : _ref4$x,
13535        _ref4$y = _ref4.y,
13536        y = _ref4$y === void 0 ? null : _ref4$y;
13537
13538    var linePoints = line.points;
13539    var points = [];
13540    line.segments.forEach(function (_ref5) {
13541      var start = _ref5.start,
13542          end = _ref5.end;
13543      end = findSegmentEnd(start, end, linePoints);
13544      var first = linePoints[start];
13545      var last = linePoints[end];
13546
13547      if (y !== null) {
13548        points.push({
13549          x: first.x,
13550          y: y
13551        });
13552        points.push({
13553          x: last.x,
13554          y: y
13555        });
13556      } else if (x !== null) {
13557        points.push({
13558          x: x,
13559          y: first.y
13560        });
13561        points.push({
13562          x: x,
13563          y: last.y
13564        });
13565      }
13566    });
13567    return points;
13568  }
13569
13570  function buildStackLine(source) {
13571    var chart = source.chart,
13572        scale = source.scale,
13573        index = source.index,
13574        line = source.line;
13575    var points = [];
13576    var segments = line.segments;
13577    var sourcePoints = line.points;
13578    var linesBelow = getLinesBelow(chart, index);
13579    linesBelow.push(createBoundaryLine({
13580      x: null,
13581      y: scale.bottom
13582    }, line));
13583
13584    for (var i = 0; i < segments.length; i++) {
13585      var segment = segments[i];
13586
13587      for (var j = segment.start; j <= segment.end; j++) {
13588        addPointsBelow(points, sourcePoints[j], linesBelow);
13589      }
13590    }
13591
13592    return new LineElement({
13593      points: points,
13594      options: {}
13595    });
13596  }
13597
13598  var isLineAndNotInHideAnimation = function isLineAndNotInHideAnimation(meta) {
13599    return meta.type === 'line' && !meta.hidden;
13600  };
13601
13602  function getLinesBelow(chart, index) {
13603    var below = [];
13604    var metas = chart.getSortedVisibleDatasetMetas();
13605
13606    for (var i = 0; i < metas.length; i++) {
13607      var meta = metas[i];
13608
13609      if (meta.index === index) {
13610        break;
13611      }
13612
13613      if (isLineAndNotInHideAnimation(meta)) {
13614        below.unshift(meta.dataset);
13615      }
13616    }
13617
13618    return below;
13619  }
13620
13621  function addPointsBelow(points, sourcePoint, linesBelow) {
13622    var postponed = [];
13623
13624    for (var j = 0; j < linesBelow.length; j++) {
13625      var line = linesBelow[j];
13626
13627      var _findPoint = findPoint(line, sourcePoint, 'x'),
13628          first = _findPoint.first,
13629          last = _findPoint.last,
13630          point = _findPoint.point;
13631
13632      if (!point || first && last) {
13633        continue;
13634      }
13635
13636      if (first) {
13637        postponed.unshift(point);
13638      } else {
13639        points.push(point);
13640
13641        if (!last) {
13642          break;
13643        }
13644      }
13645    }
13646
13647    points.push.apply(points, postponed);
13648  }
13649
13650  function findPoint(line, sourcePoint, property) {
13651    var point = line.interpolate(sourcePoint, property);
13652
13653    if (!point) {
13654      return {};
13655    }
13656
13657    var pointValue = point[property];
13658    var segments = line.segments;
13659    var linePoints = line.points;
13660    var first = false;
13661    var last = false;
13662
13663    for (var i = 0; i < segments.length; i++) {
13664      var segment = segments[i];
13665      var firstValue = linePoints[segment.start][property];
13666      var lastValue = linePoints[segment.end][property];
13667
13668      if (pointValue >= firstValue && pointValue <= lastValue) {
13669        first = pointValue === firstValue;
13670        last = pointValue === lastValue;
13671        break;
13672      }
13673    }
13674
13675    return {
13676      first: first,
13677      last: last,
13678      point: point
13679    };
13680  }
13681
13682  function getTarget(source) {
13683    var chart = source.chart,
13684        fill = source.fill,
13685        line = source.line;
13686
13687    if (isNumberFinite(fill)) {
13688      return getLineByIndex(chart, fill);
13689    }
13690
13691    if (fill === 'stack') {
13692      return buildStackLine(source);
13693    }
13694
13695    var boundary = computeBoundary(source);
13696
13697    if (boundary instanceof simpleArc) {
13698      return boundary;
13699    }
13700
13701    return createBoundaryLine(boundary, line);
13702  }
13703
13704  function createBoundaryLine(boundary, line) {
13705    var points = [];
13706    var _loop = false;
13707
13708    if (isArray(boundary)) {
13709      _loop = true;
13710      points = boundary;
13711    } else {
13712      points = pointsFromSegments(boundary, line);
13713    }
13714
13715    return points.length ? new LineElement({
13716      points: points,
13717      options: {
13718        tension: 0
13719      },
13720      _loop: _loop,
13721      _fullLoop: _loop
13722    }) : null;
13723  }
13724
13725  function resolveTarget(sources, index, propagate) {
13726    var source = sources[index];
13727    var fill = source.fill;
13728    var visited = [index];
13729    var target;
13730
13731    if (!propagate) {
13732      return fill;
13733    }
13734
13735    while (fill !== false && visited.indexOf(fill) === -1) {
13736      if (!isNumberFinite(fill)) {
13737        return fill;
13738      }
13739
13740      target = sources[fill];
13741
13742      if (!target) {
13743        return false;
13744      }
13745
13746      if (target.visible) {
13747        return fill;
13748      }
13749
13750      visited.push(fill);
13751      fill = target.fill;
13752    }
13753
13754    return false;
13755  }
13756
13757  function _clip(ctx, target, clipY) {
13758    ctx.beginPath();
13759    target.path(ctx);
13760    ctx.lineTo(target.last().x, clipY);
13761    ctx.lineTo(target.first().x, clipY);
13762    ctx.closePath();
13763    ctx.clip();
13764  }
13765
13766  function getBounds(property, first, last, loop) {
13767    if (loop) {
13768      return;
13769    }
13770
13771    var start = first[property];
13772    var end = last[property];
13773
13774    if (property === 'angle') {
13775      start = _normalizeAngle(start);
13776      end = _normalizeAngle(end);
13777    }
13778
13779    return {
13780      property: property,
13781      start: start,
13782      end: end
13783    };
13784  }
13785
13786  function _getEdge(a, b, prop, fn) {
13787    if (a && b) {
13788      return fn(a[prop], b[prop]);
13789    }
13790
13791    return a ? a[prop] : b ? b[prop] : 0;
13792  }
13793
13794  function _segments(line, target, property) {
13795    var segments = line.segments;
13796    var points = line.points;
13797    var tpoints = target.points;
13798    var parts = [];
13799
13800    var _iterator10 = _createForOfIteratorHelper(segments),
13801        _step10;
13802
13803    try {
13804      for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
13805        var segment = _step10.value;
13806        var start = segment.start,
13807            end = segment.end;
13808        end = findSegmentEnd(start, end, points);
13809        var bounds = getBounds(property, points[start], points[end], segment.loop);
13810
13811        if (!target.segments) {
13812          parts.push({
13813            source: segment,
13814            target: bounds,
13815            start: points[start],
13816            end: points[end]
13817          });
13818          continue;
13819        }
13820
13821        var targetSegments = _boundSegments(target, bounds);
13822
13823        var _iterator11 = _createForOfIteratorHelper(targetSegments),
13824            _step11;
13825
13826        try {
13827          for (_iterator11.s();
13827 !(_step11 = _iterator11.n()).done;) {
13828            var tgt = _step11.value;
13829            var subBounds = getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);
13830
13831            var fillSources = _boundSegment(segment, points, subBounds);
13832
13833            var _iterator12 = _createForOfIteratorHelper(fillSources),
13834                _step12;
13835
13836            try {
13837              for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
13838                var fillSource = _step12.value;
13839                parts.push({
13840                  source: fillSource,
13841                  target: tgt,
13842                  start: _defineProperty({}, property, _getEdge(bounds, subBounds, 'start', Math.max)),
13843                  end: _defineProperty({}, property, _getEdge(bounds, subBounds, 'end', Math.min))
13844                });
13845              }
13846            } catch (err) {
13847              _iterator12.e(err);
13848            } finally {
13849              _iterator12.f();
13850            }
13851          }
13852        } catch (err) {
13853          _iterator11.e(err);
13854        } finally {
13855          _iterator11.f();
13856        }
13857      }
13858    } catch (err) {
13859      _iterator10.e(err);
13860    } finally {
13861      _iterator10.f();
13862    }
13863
13864    return parts;
13865  }
13866
13867  function clipBounds(ctx, scale, bounds) {
13868    var _scale$chart$chartAre = scale.chart.chartArea,
13869        top = _scale$chart$chartAre.top,
13870        bottom = _scale$chart$chartAre.bottom;
13871
13872    var _ref6 = bounds || {},
13873        property = _ref6.property,
13874        start = _ref6.start,
13875        end = _ref6.end;
13876
13877    if (property === 'x') {
13878      ctx.beginPath();
13879      ctx.rect(start, top, end - start, bottom - top);
13880      ctx.clip();
13881    }
13882  }
13883
13884  function interpolatedLineTo(ctx, target, point, property) {
13885    var interpolatedPoint = target.interpolate(point, property);
13886
13887    if (interpolatedPoint) {
13888      ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);
13889    }
13890  }
13891
13892  function _fill(ctx, cfg) {
13893    var line = cfg.line,
13894        target = cfg.target,
13895        property = cfg.property,
13896        color = cfg.color,
13897        scale = cfg.scale;
13898
13899    var segments = _segments(line, target, property);
13900
13901    var _iterator13 = _createForOfIteratorHelper(segments),
13902        _step13;
13903
13904    try {
13905      for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
13906        var _step13$value = _step13.value,
13907            src = _step13$value.source,
13908            tgt = _step13$value.target,
13909            start = _step13$value.start,
13910            end = _step13$value.end;
13911        var _src$style = src.style;
13912        _src$style = _src$style === void 0 ? {} : _src$style;
13913        var _src$style$background = _src$style.backgroundColor,
13914            backgroundColor = _src$style$background === void 0 ? color : _src$style$background;
13915        ctx.save();
13916        ctx.fillStyle = backgroundColor;
13917        clipBounds(ctx, scale, getBounds(property, start, end));
13918        ctx.beginPath();
13919        var lineLoop = !!line.pathSegment(ctx, src);
13920
13921        if (lineLoop) {
13922          ctx.closePath();
13923        } else {
13924          interpolatedLineTo(ctx, target, end, property);
13925        }
13926
13927        var targetLoop = !!target.pathSegment(ctx, tgt, {
13928          move: lineLoop,
13929          reverse: true
13930        });
13931        var loop = lineLoop && targetLoop;
13932
13933        if (!loop) {
13934          interpolatedLineTo(ctx, target, start, property);
13935        }
13936
13937        ctx.closePath();
13938        ctx.fill(loop ? 'evenodd' : 'nonzero');
13939        ctx.restore();
13940      }
13941    } catch (err) {
13942      _iterator13.e(err);
13943    } finally {
13944      _iterator13.f();
13945    }
13946  }
13947
13948  function doFill(ctx, cfg) {
13949    var line = cfg.line,
13950        target = cfg.target,
13951        above = cfg.above,
13952        below = cfg.below,
13953        area = cfg.area,
13954        scale = cfg.scale;
13955    var property = line._loop ? 'angle' : cfg.axis;
13956    ctx.save();
13957
13958    if (property === 'x' && below !== above) {
13959      _clip(ctx, target, area.top);
13960
13961      _fill(ctx, {
13962        line: line,
13963        target: target,
13964        color: above,
13965        scale: scale,
13966        property: property
13967      });
13968
13969      ctx.restore();
13970      ctx.save();
13971
13972      _clip(ctx, target, area.bottom);
13973    }
13974
13975    _fill(ctx, {
13976      line: line,
13977      target: target,
13978      color: below,
13979      scale: scale,
13980      property: property
13981    });
13982
13983    ctx.restore();
13984  }
13985
13986  function drawfill(ctx, source, area) {
13987    var target = getTarget(source);
13988    var line = source.line,
13989        scale = source.scale,
13990        axis = source.axis;
13991    var lineOpts = line.options;
13992    var fillOption = lineOpts.fill;
13993    var color = lineOpts.backgroundColor;
13994
13995    var _ref7 = fillOption || {},
13996        _ref7$above = _ref7.above,
13997        above = _ref7$above === void 0 ? color : _ref7$above,
13998        _ref7$below = _ref7.below,
13999        below = _ref7$below === void 0 ? color : _ref7$below;
14000
14001    if (target && line.points.length) {
14002      clipArea(ctx, area);
14003      doFill(ctx, {
14004        line: line,
14005        target: target,
14006        above: above,
14007        below: below,
14008        area: area,
14009        scale: scale,
14010        axis: axis
14011      });
14012      unclipArea(ctx);
14013    }
14014  }
14015
14016  var plugin_filler = {
14017    id: 'filler',
14018    afterDatasetsUpdate: function afterDatasetsUpdate(chart, _args, options) {
14019      var count = (chart.data.datasets || []).length;
14020      var sources = [];
14021      var meta, i, line, source;
14022
14023      for (i = 0; i < count; ++i) {
14024        meta = chart.getDatasetMeta(i);
14025        line = meta.dataset;
14026        source = null;
14027
14028        if (line && line.options && line instanceof LineElement) {
14029          source = {
14030            visible: chart.isDatasetVisible(i),
14031            index: i,
14032            fill: decodeFill(line, i, count),
14033            chart: chart,
14034            axis: meta.controller.options.indexAxis,
14035            scale: meta.vScale,
14036            line: line
14037          };
14038        }
14039
14040        meta.$filler = source;
14041        sources.push(source);
14042      }
14043
14044      for (i = 0; i < count; ++i) {
14045        source = sources[i];
14046
14047        if (!source || source.fill === false) {
14048          continue;
14049        }
14050
14051        source.fill = resolveTarget(sources, i, options.propagate);
14052      }
14053    },
14054    beforeDraw: function beforeDraw(chart, _args, options) {
14055      var draw = options.drawTime === 'beforeDraw';
14056      var metasets = chart.getSortedVisibleDatasetMetas();
14057      var area = chart.chartArea;
14058
14059      for (var i = metasets.length - 1; i >= 0; --i) {
14060        var source = metasets[i].$filler;
14061
14062        if (!source) {
14063          continue;
14064        }
14065
14066        source.line.updateControlPoints(area, source.axis);
14067
14068        if (draw) {
14069          drawfill(chart.ctx, source, area);
14070        }
14071      }
14072    },
14073    beforeDatasetsDraw: function beforeDatasetsDraw(chart, _args, options) {
14074      if (options.drawTime !== 'beforeDatasetsDraw') {
14075        return;
14076      }
14077
14078      var metasets = chart.getSortedVisibleDatasetMetas();
14079
14080      for (var i = metasets.length - 1; i >= 0; --i) {
14081        var source = metasets[i].$filler;
14082
14083        if (source) {
14084          drawfill(chart.ctx, source, chart.chartArea);
14085        }
14086      }
14087    },
14088    beforeDatasetDraw: function beforeDatasetDraw(chart, args, options) {
14089      var source = args.meta.$filler;
14090
14091      if (!source || source.fill === false || options.drawTime !== 'beforeDatasetDraw') {
14092        return;
14093      }
14094
14095      drawfill(chart.ctx, source, chart.chartArea);
14096    },
14097    defaults: {
14098      propagate: true,
14099      drawTime: 'beforeDatasetDraw'
14100    }
14101  };
14102
14103  var getBoxSize = function getBoxSize(labelOpts, fontSize) {
14104    var _labelOpts$boxHeight = labelOpts.boxHeight,
14105        boxHeight = _labelOpts$boxHeight === void 0 ? fontSize : _labelOpts$boxHeight,
14106        _labelOpts$boxWidth = labelOpts.boxWidth,
14107        boxWidth = _labelOpts$boxWidth === void 0 ? fontSize : _labelOpts$boxWidth;
14108
14109    if (labelOpts.usePointStyle) {
14110      boxHeight = Math.min(boxHeight, fontSize);
14111      boxWidth = Math.min(boxWidth, fontSize);
14112    }
14113
14114    return {
14115      boxWidth: boxWidth,
14116      boxHeight: boxHeight,
14117      itemHeight: Math.max(fontSize, boxHeight)
14118    };
14119  };
14120
14121  var itemsEqual = function itemsEqual(a, b) {
14122    return a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;
14123  };
14124
14125  var Legend = /*#__PURE__*/function (_Element6) {
14126    _inherits(Legend, _Element6);
14127
14128    var _super16 = _createSuper(Legend);
14129
14130    function Legend(config) {
14131      var _this11;
14132
14133      _classCallCheck(this, Legend);
14134
14135      _this11 = _super16.call(this);
14136      _this11._added = false;
14137      _this11.legendHitBoxes = [];
14138      _this11._hoveredItem = null;
14139      _this11.doughnutMode = false;
14140      _this11.chart = config.chart;
14141      _this11.options = config.options;
14142      _this11.ctx = config.ctx;
14143      _this11.legendItems = undefined;
14144      _this11.columnSizes = undefined;
14145      _this11.lineWidths = undefined;
14146      _this11.maxHeight = undefined;
14147      _this11.maxWidth = undefined;
14148      _this11.top = undefined;
14149      _this11.bottom = undefined;
14150      _this11.left = undefined;
14151      _this11.right = undefined;
14152      _this11.height = undefined;
14153      _this11.width = undefined;
14154      _this11._margins = undefined;
14155      _this11.position = undefined;
14156      _this11.weight = undefined;
14157      _this11.fullSize = undefined;
14158      return _this11;
14159    }
14160
14161    _createClass(Legend, [{
14162      key: "update",
14163      value: function update(maxWidth, maxHeight, margins) {
14164        var me = this;
14165        me.maxWidth = maxWidth;
14166        me.maxHeight = maxHeight;
14167        me._margins = margins;
14168        me.setDimensions();
14169        me.buildLabels();
14170        me.fit();
14171      }
14172    }, {
14173      key: "setDimensions",
14174      value: function setDimensions() {
14175        var me = this;
14176
14177        if (me.isHorizontal()) {
14178          me.width = me.maxWidth;
14179          me.left = me._margins.left;
14180          me.right = me.width;
14181        } else {
14182          me.height = me.maxHeight;
14183          me.top = me._margins.top;
14184          me.bottom = me.height;
14185        }
14186      }
14187    }, {
14188      key: "buildLabels",
14189      value: function buildLabels() {
14190        var me = this;
14191        var labelOpts = me.options.labels || {};
14192        var legendItems = callback(labelOpts.generateLabels, [me.chart], me) || [];
14193
14194        if (labelOpts.filter) {
14195          legendItems = legendItems.filter(function (item) {
14196            return labelOpts.filter(item, me.chart.data);
14197          });
14198        }
14199
14200        if (labelOpts.sort) {
14201          legendItems = legendItems.sort(function (a, b) {
14202            return labelOpts.sort(a, b, me.chart.data);
14203          });
14204        }
14205
14206        if (me.options.reverse) {
14207          legendItems.reverse();
14208        }
14209
14210        me.legendItems = legendItems;
14211      }
14212    }, {
14213      key: "fit",
14214      value: function fit() {
14215        var me = this;
14216        var options = me.options,
14217            ctx = me.ctx;
14218
14219        if (!options.display) {
14220          me.width = me.height = 0;
14221          return;
14222        }
14223
14224        var labelOpts = options.labels;
14225        var labelFont = toFont(labelOpts.font);
14226        var fontSize = labelFont.size;
14227
14228        var titleHeight = me._computeTitleHeight();
14229
14230        var _getBoxSize = getBoxSize(labelOpts, fontSize),
14231            boxWidth = _getBoxSize.boxWidth,
14232            itemHeight = _getBoxSize.itemHeight;
14233
14234        var width, height;
14235        ctx.font = labelFont.string;
14236
14237        if (me.isHorizontal()) {
14238          width = me.maxWidth;
14239          height = me._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;
14240        } else {
14241          height = me.maxHeight;
14242          width = me._fitCols(titleHeight, fontSize, boxWidth, itemHeight) + 10;
14243        }
14244
14245        me.width = Math.min(width, options.maxWidth || me.maxWidth);
14246        me.height = Math.min(height, options.maxHeight || me.maxHeight);
14247      }
14248    }, {
14249      key: "_fitRows",
14250      value: function _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {
14251        var me = this;
14252        var ctx = me.ctx,
14253            maxWidth = me.maxWidth,
14254            padding = me.options.labels.padding;
14255        var hitboxes = me.legendHitBoxes = [];
14256        var lineWidths = me.lineWidths = [0];
14257        var lineHeight = itemHeight + padding;
14258        var totalHeight = titleHeight;
14259        ctx.textAlign = 'left';
14260        ctx.textBaseline = 'middle';
14261        var row = -1;
14262        var top = -lineHeight;
14263        me.legendItems.forEach(function (legendItem, i) {
14264          var itemWidth = boxWidth + fontSize / 2 + ctx.measureText(legendItem.text).width;
14265
14266          if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {
14267            totalHeight += lineHeight;
14268            lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
14269            top += lineHeight;
14270            row++;
14271          }
14272
14273          hitboxes[i] = {
14274            left: 0,
14275            top: top,
14276            row: row,
14277            width: itemWidth,
14278            height: itemHeight
14279          };
14280          lineWidths[lineWidths.length - 1] += itemWidth + padding;
14281        });
14282        return totalHeight;
14283      }
14284    }, {
14285      key: "_fitCols",
14286      value: function _fitCols(titleHeight, fontSize, boxWidth, itemHeight) {
14287        var me = this;
14288        var ctx = me.ctx,
14289            maxHeight = me.maxHeight,
14290            padding = me.options.labels.padding;
14291        var hitboxes = me.legendHitBoxes = [];
14292        var columnSizes = me.columnSizes = [];
14293        var heightLimit = maxHeight - titleHeight;
14294        var totalWidth = padding;
14295        var currentColWidth = 0;
14296        var currentColHeight = 0;
14297        var left = 0;
14298        var col = 0;
14299        me.legendItems.forEach(function (legendItem, i) {
14300          var itemWidth = boxWidth + fontSize / 2 + ctx.measureText(legendItem.text).width;
14301
14302          if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) {
14303            totalWidth += currentColWidth + padding;
14304            columnSizes.push({
14305              width: currentColWidth,
14306              height: currentColHeight
14307            });
14308            left += currentColWidth + padding;
14309            col++;
14310            currentColWidth = currentColHeight = 0;
14311          }
14312
14313          hitboxes[i] = {
14314            left: left,
14315            top: currentColHeight,
14316            col: col,
14317            width: itemWidth,
14318            height: itemHeight
14319          };
14320          currentColWidth = Math.max(currentColWidth, itemWidth);
14321          currentColHeight += itemHeight + padding;
14322        });
14323        totalWidth += currentColWidth;
14324        columnSizes.push({
14325          width: currentColWidth,
14326          height: currentColHeight
14327        });
14328        return totalWidth;
14329      }
14330    }, {
14331      key: "adjustHitBoxes",
14332      value: function adjustHitBoxes() {
14333        var me = this;
14334
14335        if (!me.options.display) {
14336          return;
14337        }
14338
14339        var titleHeight = me._computeTitleHeight();
14340
14341        var hitboxes = me.legendHitBoxes,
14342            _me$options6 = me.options,
14343            align = _me$options6.align,
14344            padding = _me$options6.labels.padding,
14345            rtl = _me$options6.rtl;
14346
14347        if (this.isHorizontal()) {
14348          var row = 0;
14349
14350          var left = _alignStartEnd(align, me.left + padding, me.right - me.lineWidths[row]);
14351
14352          var _iterator14 = _createForOfIteratorHelper(hitboxes),
14353              _step14;
14354
14355          try {
14356            for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
14357              var hitbox = _step14.value;
14358
14359              if (row !== hitbox.row) {
14360                row = hitbox.row;
14361                left = _alignStartEnd(align, me.left + padding, me.right - me.lineWidths[row]);
14362              }
14363
14364              hitbox.top += me.top + titleHeight + padding;
14365              hitbox.left = left;
14366              left += hitbox.width + padding;
14367            }
14368          } catch (err) {
14369            _iterator14.e(err);
14370          } finally {
14371            _iterator14.f();
14372          }
14373
14374          if (rtl) {
14375            var boxMap = hitboxes.reduce(function (map, box) {
14376              map[box.row] = map[box.row] || [];
14377              map[box.row].push(box);
14378              return map;
14379            }, {});
14380            var newBoxes = [];
14381            Object.keys(boxMap).forEach(function (key) {
14382              boxMap[key].reverse();
14383              newBoxes.push.apply(newBoxes, _toConsumableArray(boxMap[key]));
14384            });
14385            me.legendHitBoxes = newBoxes;
14386          }
14387        } else {
14388          var col = 0;
14389
14390          var top = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - me.columnSizes[col].height);
14391
14392          var _iterator15 = _createForOfIteratorHelper(hitboxes),
14393              _step15;
14394
14395          try {
14396            for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
14397              var _hitbox = _step15.value;
14398
14399              if (_hitbox.col !== col) {
14400                col = _hitbox.col;
14401                top = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - me.columnSizes[col].height);
14402              }
14403
14404              _hitbox.top = top;
14405              _hitbox.left += me.left + padding;
14406              top += _hitbox.height + padding;
14407            }
14408          } catch (err) {
14409            _iterator15.e(err);
14410          } finally {
14411            _iterator15.f();
14412          }
14413        }
14414      }
14415    }, {
14416      key: "isHorizontal",
14417      value: function isHorizontal() {
14418        return this.options.position === 'top' || this.options.position === 'bottom';
14419      }
14420    }, {
14421      key: "draw",
14422      value: function draw() {
14423        var me = this;
14424
14425        if (me.options.display) {
14426          var ctx = me.ctx;
14427          clipArea(ctx, me);
14428
14429          me._draw();
14430
14431          unclipArea(ctx);
14432        }
14433      }
14434    }, {
14435      key: "_draw",
14436      value: function _draw() {
14437        var me = this;
14438        var opts = me.options,
14439            columnSizes = me.columnSizes,
14440            lineWidths = me.lineWidths,
14441            ctx = me.ctx;
14442        var align = opts.align,
14443            labelOpts = opts.labels;
14444        var defaultColor = defaults.color;
14445        var rtlHelper = getRtlAdapter(opts.rtl, me.left, me.width);
14446        var labelFont = toFont(labelOpts.font);
14447        var fontColor = labelOpts.color,
14448            padding = labelOpts.padding;
14449        var fontSize = labelFont.size;
14450        var halfFontSize = fontSize / 2;
14451        var cursor;
14452        me.drawTitle();
14453        ctx.textAlign = rtlHelper.textAlign('left');
14454        ctx.textBaseline = 'middle';
14455        ctx.lineWidth = 0.5;
14456        ctx.font = labelFont.string;
14457
14458        var _getBoxSize2 = getBoxSize(labelOpts, fontSize),
14459            boxWidth = _getBoxSize2.boxWidth,
14460            boxHeight = _getBoxSize2.boxHeight,
14461            itemHeight = _getBoxSize2.itemHeight;
14462
14463        var drawLegendBox = function drawLegendBox(x, y, legendItem) {
14464          if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {
14465            return;
14466          }
14467
14468          ctx.save();
14469          var lineWidth = valueOrDefault(legendItem.lineWidth, 1);
14470          ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);
14471          ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt');
14472          ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0);
14473          ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter');
14474          ctx.lineWidth = lineWidth;
14475          ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor);
14476          ctx.setLineDash(valueOrDefault(legendItem.lineDash, []));
14477
14478          if (labelOpts.usePointStyle) {
14479            var drawOptions = {
14480              radius: boxWidth * Math.SQRT2 / 2,
14481              pointStyle: legendItem.pointStyle,
14482              rotation: legendItem.rotation,
14483              borderWidth: lineWidth
14484            };
14485            var centerX = rtlHelper.xPlus(x, boxWidth / 2);
14486            var centerY = y + halfFontSize;
14487            drawPoint(ctx, drawOptions, centerX, centerY);
14488          } else {
14489            var yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);
14490            var xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);
14491            var borderRadius = toTRBLCorners(legendItem.borderRadius);
14492            ctx.beginPath();
14493
14494            if (Object.values(borderRadius).some(function (v) {
14495              return v !== 0;
14496            })) {
14497              addRoundedRectPath(ctx, {
14498                x: xBoxLeft,
14499                y: yBoxTop,
14500                w: boxWidth,
14501                h: boxHeight,
14502                radius: borderRadius
14503              });
14504            } else {
14505              ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);
14506            }
14507
14508            ctx.fill();
14509
14510            if (lineWidth !== 0) {
14511              ctx.stroke();
14512            }
14513          }
14514
14515          ctx.restore();
14516        };
14517
14518        var fillText = function fillText(x, y, legendItem) {
14519          renderText(ctx, legendItem.text, x, y + itemHeight / 2, labelFont, {
14520            strikethrough: legendItem.hidden,
14521            textAlign: rtlHelper.textAlign(legendItem.textAlign)
14522          });
14523        };
14524
14525        var isHorizontal = me.isHorizontal();
14526
14527        var titleHeight = this._computeTitleHeight();
14528
14529        if (isHorizontal) {
14530          cursor = {
14531            x: _alignStartEnd(align, me.left + padding, me.right - lineWidths[0]),
14532            y: me.top + padding + titleHeight,
14533            line: 0
14534          };
14535        } else {
14536          cursor = {
14537            x: me.left + padding,
14538            y: _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - columnSizes[0].height),
14539            line: 0
14540          };
14541        }
14542
14543        overrideTextDirection(me.ctx, opts.textDirection);
14544        var lineHeight = itemHeight + padding;
14545        me.legendItems.forEach(function (legendItem, i) {
14546          ctx.strokeStyle = legendItem.fontColor || fontColor;
14547          ctx.fillStyle = legendItem.fontColor || fontColor;
14548          var textWidth = ctx.measureText(legendItem.text).width;
14549          var textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));
14550          var width = boxWidth + halfFontSize + textWidth;
14551          var x = cursor.x;
14552          var y = cursor.y;
14553          rtlHelper.setWidth(me.width);
14554
14555          if (isHorizontal) {
14556            if (i > 0 && x + width + padding > me.right) {
14557              y = cursor.y += lineHeight;
14558              cursor.line++;
14559              x = cursor.x = _alignStartEnd(align, me.left + padding, me.right - lineWidths[cursor.line]);
14560            }
14561          } else if (i > 0 && y + lineHeight > me.bottom) {
14562            x = cursor.x = x + columnSizes[cursor.line].width + padding;
14563            cursor.line++;
14564            y = cursor.y = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - columnSizes[cursor.line].height);
14565          }
14566
14567          var realX = rtlHelper.x(x);
14568          drawLegendBox(realX, y, legendItem);
14569          x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : me.right, opts.rtl);
14570          fillText(rtlHelper.x(x), y, legendItem);
14571
14572          if (isHorizontal) {
14573            cursor.x += width + padding;
14574          } else {
14575            cursor.y += lineHeight;
14576          }
14577        });
14578        restoreTextDirection(me.ctx, opts.textDirection);
14579      }
14580    }, {
14581      key: "drawTitle",
14582      value: function drawTitle() {
14583        var me = this;
14584        var opts = me.options;
14585        var titleOpts = opts.title;
14586        var titleFont = toFont(titleOpts.font);
14587        var titlePadding = toPadding(titleOpts.padding);
14588
14589        if (!titleOpts.display) {
14590          return;
14591        }
14592
14593        var rtlHelper = getRtlAdapter(opts.rtl, me.left, me.width);
14594        var ctx = me.ctx;
14595        var position = titleOpts.position;
14596        var halfFontSize = titleFont.size / 2;
14597        var topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;
14598        var y;
14599        var left = me.left;
14600        var maxWidth = me.width;
14601
14602        if (this.isHorizontal()) {
14603          maxWidth = Math.max.apply(Math, _toConsumableArray(me.lineWidths));
14604          y = me.top + topPaddingPlusHalfFontSize;
14605          left = _alignStartEnd(opts.align, left, me.right - maxWidth);
14606        } else {
14607          var maxHeight = me.columnSizes.reduce(function (acc, size) {
14608            return Math.max(acc, size.height);
14609          }, 0);
14610          y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, me.top, me.bottom - maxHeight - opts.labels.padding - me._computeTitleHeight());
14611        }
14612
14613        var x = _alignStartEnd(position, left, left + maxWidth);
14614
14615        ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position));
14616        ctx.textBaseline = 'middle';
14617        ctx.strokeStyle = titleOpts.color;
14618        ctx.fillStyle = titleOpts.color;
14619        ctx.font = titleFont.string;
14620        renderText(ctx, titleOpts.text, x, y, titleFont);
14621      }
14622    }, {
14623      key: "_computeTitleHeight",
14624      value: function _computeTitleHeight() {
14625        var titleOpts = this.options.title;
14626        var titleFont = toFont(titleOpts.font);
14627        var titlePadding = toPadding(titleOpts.padding);
14628        return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
14629      }
14630    }, {
14631      key: "_getLegendItemAt",
14632      value: function _getLegendItemAt(x, y) {
14633        var me = this;
14634        var i, hitBox, lh;
14635
14636        if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
14637          lh = me.legendHitBoxes;
14638
14639          for (i = 0; i < lh.length; ++i) {
14640            hitBox = lh[i];
14641
14642            if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
14643              return me.legendItems[i];
14644            }
14645          }
14646        }
14647
14648        return null;
14649      }
14650    }, {
14651      key: "handleEvent",
14652      value: function handleEvent(e) {
14653        var me = this;
14654        var opts = me.options;
14655
14656        if (!isListened(e.type, opts)) {
14657          return;
14658        }
14659
14660        var hoveredItem = me._getLegendItemAt(e.x, e.y);
14661
14662        if (e.type === 'mousemove') {
14663          var previous = me._hoveredItem;
14664          var sameItem = itemsEqual(previous, hoveredItem);
14665
14666          if (previous && !sameItem) {
14667            callback(opts.onLeave, [e, previous, me], me);
14668          }
14669
14670          me._hoveredItem = hoveredItem;
14671
14672          if (hoveredItem && !sameItem) {
14673            callback(opts.onHover, [e, hoveredItem, me], me);
14674          }
14675        } else if (hoveredItem) {
14676          callback(opts.onClick, [e, hoveredItem, me], me);
14677        }
14678      }
14679    }]);
14680
14681    return Legend;
14682  }(Element);
14683
14684  function isListened(type, opts) {
14685    if (type === 'mousemove' && (opts.onHover || opts.onLeave)) {
14686      return true;
14687    }
14688
14689    if (opts.onClick && (type === 'click' || type === 'mouseup')) {
14690      return true;
14691    }
14692
14693    return false;
14694  }
14695
14696  var plugin_legend = {
14697    id: 'legend',
14698    _element: Legend,
14699    start: function start(chart, _args, options) {
14700      var legend = chart.legend = new Legend({
14701        ctx: chart.ctx,
14702        options: options,
14703        chart: chart
14704      });
14705      layouts.configure(chart, legend, options);
14706      layouts.addBox(chart, legend);
14707    },
14708    stop: function stop(chart) {
14709      layouts.removeBox(chart, chart.legend);
14710      delete chart.legend;
14711    },
14712    beforeUpdate: function beforeUpdate(chart, _args, options) {
14713      var legend = chart.legend;
14714      layouts.configure(chart, legend, options);
14715      legend.options = options;
14716    },
14717    afterUpdate: function afterUpdate(chart) {
14718      var legend = chart.legend;
14719      legend.buildLabels();
14720      legend.adjustHitBoxes();
14721    },
14722    afterEvent: function afterEvent(chart, args) {
14723      if (!args.replay) {
14724        chart.legend.handleEvent(args.event);
14725      }
14726    },
14727    defaults: {
14728      display: true,
14729      position: 'top',
14730      align: 'center',
14731      fullSize: true,
14732      reverse: false,
14733      weight: 1000,
14734      onClick: function onClick(e, legendItem, legend) {
14735        var index = legendItem.datasetIndex;
14736        var ci = legend.chart;
14737
14738        if (ci.isDatasetVisible(index)) {
14739          ci.hide(index);
14740          legendItem.hidden = true;
14741        } else {
14742          ci.show(index);
14743          legendItem.hidden = false;
14744        }
14745      },
14746      onHover: null,
14747      onLeave: null,
14748      labels: {
14749        color: function color(ctx) {
14750          return ctx.chart.options.color;
14751        },
14752        boxWidth: 40,
14753        padding: 10,
14754        generateLabels: function generateLabels(chart) {
14755          var datasets = chart.data.datasets;
14756          var _chart$legend$options = chart.legend.options.labels,
14757              usePointStyle = _chart$legend$options.usePointStyle,
14758              pointStyle = _chart$legend$options.pointStyle,
14759              textAlign = _chart$legend$options.textAlign,
14760              color = _chart$legend$options.color;
14761          return chart._getSortedDatasetMetas().map(function (meta) {
14762            var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
14763            var borderWidth = toPadding(style.borderWidth);
14764            return {
14765              text: datasets[meta.index].label,
14766              fillStyle: style.backgroundColor,
14767              fontColor: color,
14768              hidden: !meta.visible,
14769              lineCap: style.borderCapStyle,
14770              lineDash: style.borderDash,
14771              lineDashOffset: style.borderDashOffset,
14772              lineJoin: style.borderJoinStyle,
14773              lineWidth: (borderWidth.width + borderWidth.height) / 4,
14774              strokeStyle: style.borderColor,
14775              pointStyle: pointStyle || style.pointStyle,
14776              rotation: style.rotation,
14777              textAlign: textAlign || style.textAlign,
14778              borderRadius: 0,
14779              datasetIndex: meta.index
14780            };
14781          }, this);
14782        }
14783      },
14784      title: {
14785        color: function color(ctx) {
14786          return ctx.chart.options.color;
14787        },
14788        display: false,
14789        position: 'center',
14790        text: ''
14791      }
14792    },
14793    descriptors: {
14794      _scriptable: function _scriptable(name) {
14795        return !name.startsWith('on');
14796      },
14797      labels: {
14798        _scriptable: function _scriptable(name) {
14799          return !['generateLabels', 'filter', 'sort'].includes(name);
14800        }
14801      }
14802    }
14803  };
14804
14805  var Title = /*#__PURE__*/function (_Element7) {
14806    _inherits(Title, _Element7);
14807
14808    var _super17 = _createSuper(Title);
14809
14810    function Title(config) {
14811      var _this12;
14812
14813      _classCallCheck(this, Title);
14814
14815      _this12 = _super17.call(this);
14816      _this12.chart = config.chart;
14817      _this12.options = config.options;
14818      _this12.ctx = config.ctx;
14819      _this12._padding = undefined;
14820      _this12.top = undefined;
14821      _this12.bottom = undefined;
14822      _this12.left = undefined;
14823      _this12.right = undefined;
14824      _this12.width = undefined;
14825      _this12.height = undefined;
14826      _this12.position = undefined;
14827      _this12.weight = undefined;
14828      _this12.fullSize = undefined;
14829      return _this12;
14830    }
14831
14832    _createClass(Title, [{
14833      key: "update",
14834      value: function update(maxWidth, maxHeight) {
14835        var me = this;
14836        var opts = me.options;
14837        me.left = 0;
14838        me.top = 0;
14839
14840        if (!opts.display) {
14841          me.width = me.height = me.right = me.bottom = 0;
14842          return;
14843        }
14844
14845        me.width = me.right = maxWidth;
14846        me.height = me.bottom = maxHeight;
14847        var lineCount = isArray(opts.text) ? opts.text.length : 1;
14848        me._padding = toPadding(opts.padding);
14849
14850        var textSize = lineCount * toFont(opts.font).lineHeight + me._padding.height;
14851
14852        if (me.isHorizontal()) {
14853          me.height = textSize;
14854        } else {
14855          me.width = textSize;
14856        }
14857      }
14858    }, {
14859      key: "isHorizontal",
14860      value: function isHorizontal() {
14861        var pos = this.options.position;
14862        return pos === 'top' || pos === 'bottom';
14863      }
14864    }, {
14865      key: "_drawArgs",
14866      value: function _drawArgs(offset) {
14867        var top = this.top,
14868            left = this.left,
14869            bottom = this.bottom,
14870            right = this.right,
14871            options = this.options;
14872        var align = options.align;
14873        var rotation = 0;
14874        var maxWidth, titleX, titleY;
14875
14876        if (this.isHorizontal()) {
14877          titleX = _alignStartEnd(align, left, right);
14878          titleY = top + offset;
14879          maxWidth = right - left;
14880        } else {
14881          if (options.position === 'left') {
14882            titleX = left + offset;
14883            titleY = _alignStartEnd(align, bottom, top);
14884            rotation = PI * -0.5;
14885          } else {
14886            titleX = right - offset;
14887            titleY = _alignStartEnd(align, top, bottom);
14888            rotation = PI * 0.5;
14889          }
14890
14891          maxWidth = bottom - top;
14892        }
14893
14894        return {
14895          titleX: titleX,
14896          titleY: titleY,
14897          maxWidth: maxWidth,
14898          rotation: rotation
14899        };
14900      }
14901    }, {
14902      key: "draw",
14903      value: function draw() {
14904        var me = this;
14905        var ctx = me.ctx;
14906        var opts = me.options;
14907
14908        if (!opts.display) {
14909          return;
14910        }
14911
14912        var fontOpts = toFont(opts.font);
14913        var lineHeight = fontOpts.lineHeight;
14914        var offset = lineHeight / 2 + me._padding.top;
14915
14916        var _me$_drawArgs = me._drawArgs(offset),
14917            titleX = _me$_drawArgs.titleX,
14918            titleY = _me$_drawArgs.titleY,
14919            maxWidth = _me$_drawArgs.maxWidth,
14920            rotation = _me$_drawArgs.rotation;
14921
14922        renderText(ctx, opts.text, 0, 0, fontOpts, {
14923          color: opts.color,
14924          maxWidth: maxWidth,
14925          rotation: rotation,
14926          textAlign: _toLeftRightCenter(opts.align),
14927          textBaseline: 'middle',
14928          translation: [titleX, titleY]
14929        });
14930      }
14931    }]);
14932
14933    return Title;
14934  }(Element);
14935
14936  function createTitle(chart, titleOpts) {
14937    var title = new Title({
14938      ctx: chart.ctx,
14939      options: titleOpts,
14940      chart: chart
14941    });
14942    layouts.configure(chart, title, titleOpts);
14943    layouts.addBox(chart, title);
14944    chart.titleBlock = title;
14945  }
14946
14947  var plugin_title = {
14948    id: 'title',
14949    _element: Title,
14950    start: function start(chart, _args, options) {
14951      createTitle(chart, options);
14952    },
14953    stop: function stop(chart) {
14954      var titleBlock = chart.titleBlock;
14955      layouts.removeBox(chart, titleBlock);
14956      delete chart.titleBlock;
14957    },
14958    beforeUpdate: function beforeUpdate(chart, _args, options) {
14959      var title = chart.titleBlock;
14960      layouts.configure(chart, title, options);
14961      title.options = options;
14962    },
14963    defaults: {
14964      align: 'center',
14965      display: false,
14966      font: {
14967        weight: 'bold'
14968      },
14969      fullSize: true,
14970      padding: 10,
14971      position: 'top',
14972      text: '',
14973      weight: 2000
14974    },
14975    defaultRoutes: {
14976      color: 'color'
14977    },
14978    descriptors: {
14979      _scriptable: true,
14980      _indexable: false
14981    }
14982  };
14983  var map = new WeakMap();
14984  var plugin_subtitle = {
14985    id: 'subtitle',
14986    start: function start(chart, _args, options) {
14987      var title = new Title({
14988        ctx: chart.ctx,
14989        options: options,
14990        chart: chart
14991      });
14992      layouts.configure(chart, title, options);
14993      layouts.addBox(chart, title);
14994      map.set(chart, title);
14995    },
14996    stop: function stop(chart) {
14997      layouts.removeBox(chart, map.get(chart));
14998      map.delete(chart);
14999    },
15000    beforeUpdate: function beforeUpdate(chart, _args, options) {
15001      var title = map.get(chart);
15002      layouts.configure(chart, title, options);
15003      title.options = options;
15004    },
15005    defaults: {
15006      align: 'center',
15007      display: false,
15008      font: {
15009        weight: 'normal'
15010      },
15011      fullSize: true,
15012      padding: 0,
15013      position: 'top',
15014      text: '',
15015      weight: 1500
15016    },
15017    defaultRoutes: {
15018      color: 'color'
15019    },
15020    descriptors: {
15021      _scriptable: true,
15022      _indexable: false
15023    }
15024  };
15025  var positioners = {
15026    average: function average(items) {
15027      if (!items.length) {
15028        return false;
15029      }
15030
15031      var i, len;
15032      var x = 0;
15033      var y = 0;
15034      var count = 0;
15035
15036      for (i = 0, len = items.length; i < len; ++i) {
15037        var el = items[i].element;
15038
15039        if (el && el.hasValue()) {
15040          var pos = el.tooltipPosition();
15041          x += pos.x;
15042          y += pos.y;
15043          ++count;
15044        }
15045      }
15046
15047      return {
15048        x: x / count,
15049        y: y / count
15050      };
15051    },
15052    nearest: function nearest(items, eventPosition) {
15053      if (!items.length) {
15054        return false;
15055      }
15056
15057      var x = eventPosition.x;
15058      var y = eventPosition.y;
15059      var minDistance = Number.POSITIVE_INFINITY;
15060      var i, len, nearestElement;
15061
15062      for (i = 0, len = items.length; i < len; ++i) {
15063        var el = items[i].element;
15064
15065        if (el && el.hasValue()) {
15066          var center = el.getCenterPoint();
15067          var d = distanceBetweenPoints(eventPosition, center);
15068
15069          if (d < minDistance) {
15070            minDistance = d;
15071            nearestElement = el;
15072          }
15073        }
15074      }
15075
15076      if (nearestElement) {
15077        var tp = nearestElement.tooltipPosition();
15078        x = tp.x;
15079        y = tp.y;
15080      }
15081
15082      return {
15083        x: x,
15084        y: y
15085      };
15086    }
15087  };
15088
15089  function pushOrConcat(base, toPush) {
15090    if (toPush) {
15091      if (isArray(toPush)) {
15092        Array.prototype.push.apply(base, toPush);
15093      } else {
15094        base.push(toPush);
15095      }
15096    }
15097
15098    return base;
15099  }
15100
15101  function splitNewlines(str) {
15102    if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
15103      return str.split('\n');
15104    }
15105
15106    return str;
15107  }
15108
15109  function createTooltipItem(chart, item) {
15110    var element = item.element,
15111        datasetIndex = item.datasetIndex,
15112        index = item.index;
15113    var controller = chart.getDatasetMeta(datasetIndex).controller;
15114
15115    var _controller$getLabelA = controller.getLabelAndValue(index),
15116        label = _controller$getLabelA.label,
15117        value = _controller$getLabelA.value;
15118
15119    return {
15120      chart: chart,
15121      label: label,
15122      parsed: controller.getParsed(index),
15123      raw: chart.data.datasets[datasetIndex].data[index],
15124      formattedValue: value,
15125      dataset: controller.getDataset(),
15126      dataIndex: index,
15127      datasetIndex: datasetIndex,
15128      element: element
15129    };
15130  }
15131
15132  function getTooltipSize(tooltip, options) {
15133    var ctx = tooltip._chart.ctx;
15134    var body = tooltip.body,
15135        footer = tooltip.footer,
15136        title = tooltip.title;
15137    var boxWidth = options.boxWidth,
15138        boxHeight = options.boxHeight;
15139    var bodyFont = toFont(options.bodyFont);
15140    var titleFont = toFont(options.titleFont);
15141    var footerFont = toFont(options.footerFont);
15142    var titleLineCount = title.length;
15143    var footerLineCount = footer.length;
15144    var bodyLineItemCount = body.length;
15145    var padding = toPadding(options.padding);
15146    var height = padding.height;
15147    var width = 0;
15148    var combinedBodyLength = body.reduce(function (count, bodyItem) {
15149      return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
15150    }, 0);
15151    combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;
15152
15153    if (titleLineCount) {
15154      height += titleLineCount * titleFont.lineHeight + (titleLineCount - 1) * options.titleSpacing + options.titleMarginBottom;
15155    }
15156
15157    if (combinedBodyLength) {
15158      var bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;
15159      height += bodyLineItemCount * bodyLineHeight + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight + (combinedBodyLength - 1) * options.bodySpacing;
15160    }
15161
15162    if (footerLineCount) {
15163      height += options.footerMarginTop + footerLineCount * footerFont.lineHeight + (footerLineCount - 1) * options.footerSpacing;
15164    }
15165
15166    var widthPadding = 0;
15167
15168    var maxLineWidth = function maxLineWidth(line) {
15169      width = Math.max(width, ctx.measureText(line).width + widthPadding);
15170    };
15171
15172    ctx.save();
15173    ctx.font = titleFont.string;
15174    each(tooltip.title, maxLineWidth);
15175    ctx.font = bodyFont.string;
15176    each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);
15177    widthPadding = options.displayColors ? boxWidth + 2 : 0;
15178    each(body, function (bodyItem) {
15179      each(bodyItem.before, maxLineWidth);
15180      each(bodyItem.lines, maxLineWidth);
15181      each(bodyItem.after, maxLineWidth);
15182    });
15183    widthPadding = 0;
15184    ctx.font = footerFont.string;
15185    each(tooltip.footer, maxLineWidth);
15186    ctx.restore();
15187    width += padding.width;
15188    return {
15189      width: width,
15190      height: height
15191    };
15192  }
15193
15194  function determineYAlign(chart, size) {
15195    var y = size.y,
15196        height = size.height;
15197
15198    if (y < height / 2) {
15199      return 'top';
15200    } else if (y > chart.height - height / 2) {
15201      return 'bottom';
15202    }
15203
15204    return 'center';
15205  }
15206
15207  function doesNotFitWithAlign(xAlign, chart, options, size) {
15208    var x = size.x,
15209        width = size.width;
15210    var caret = options.caretSize + options.caretPadding;
15211
15212    if (xAlign === 'left' && x + width + caret > chart.width) {
15213      return true;
15214    }
15215
15216    if (xAlign === 'right' && x - width - caret < 0) {
15217      return true;
15218    }
15219  }
15220
15221  function determineXAlign(chart, options, size, yAlign) {
15222    var x = size.x,
15223        width = size.width;
15224    var chartWidth = chart.width,
15225        _chart$chartArea = chart.chartArea,
15226        left = _chart$chartArea.left,
15227        right = _chart$chartArea.right;
15228    var xAlign = 'center';
15229
15230    if (yAlign === 'center') {
15231      xAlign = x <= (left + right) / 2 ? 'left' : 'right';
15232    } else if (x <= width / 2) {
15233      xAlign = 'left';
15234    } else if (x >= chartWidth - width / 2) {
15235      xAlign = 'right';
15236    }
15237
15238    if (doesNotFitWithAlign(xAlign, chart, options, size)) {
15239      xAlign = 'center';
15240    }
15241
15242    return xAlign;
15243  }
15244
15245  function determineAlignment(chart, options, size) {
15246    var yAlign = options.yAlign || determineYAlign(chart, size);
15247    return {
15248      xAlign: options.xAlign || determineXAlign(chart, options, size, yAlign),
15249      yAlign: yAlign
15250    };
15251  }
15252
15253  function alignX(size, xAlign) {
15254    var x = size.x,
15255        width = size.width;
15256
15257    if (xAlign === 'right') {
15258      x -= width;
15259    } else if (xAlign === 'center') {
15260      x -= width / 2;
15261    }
15262
15263    return x;
15264  }
15265
15266  function alignY(size, yAlign, paddingAndSize) {
15267    var y = size.y,
15268        height = size.height;
15269
15270    if (yAlign === 'top') {
15271      y += paddingAndSize;
15272    } else if (yAlign === 'bottom') {
15273      y -= height + paddingAndSize;
15274    } else {
15275      y -= height / 2;
15276    }
15277
15278    return y;
15279  }
15280
15281  function getBackgroundPoint(options, size, alignment, chart) {
15282    var caretSize = options.caretSize,
15283        caretPadding = options.caretPadding,
15284        cornerRadius = options.cornerRadius;
15285    var xAlign = alignment.xAlign,
15286        yAlign = alignment.yAlign;
15287    var paddingAndSize = caretSize + caretPadding;
15288    var radiusAndPadding = cornerRadius + caretPadding;
15289    var x = alignX(size, xAlign);
15290    var y = alignY(size, yAlign, paddingAndSize);
15291
15292    if (yAlign === 'center') {
15293      if (xAlign === 'left') {
15294        x += paddingAndSize;
15295      } else if (xAlign === 'right') {
15296        x -= paddingAndSize;
15297      }
15298    } else if (xAlign === 'left') {
15299      x -= radiusAndPadding;
15300    } else if (xAlign === 'right') {
15301      x += radiusAndPadding;
15302    }
15303
15304    return {
15305      x: _limitValue(x, 0, chart.width - size.width),
15306      y: _limitValue(y, 0, chart.height - size.height)
15307    };
15308  }
15309
15310  function getAlignedX(tooltip, align, options) {
15311    var padding = toPadding(options.padding);
15312    return align === 'center' ? tooltip.x + tooltip.width / 2 : align === 'right' ? tooltip.x + tooltip.width - padding.right : tooltip.x + padding.left;
15313  }
15314
15315  function getBeforeAfterBodyLines(callback) {
15316    return pushOrConcat([], splitNewlines(callback));
15317  }
15318
15319  function createTooltipContext(parent, tooltip, tooltipItems) {
15320    return Object.assign(Object.create(parent), {
15321      tooltip: tooltip,
15322      tooltipItems: tooltipItems,
15323      type: 'tooltip'
15324    });
15325  }
15326
15327  function overrideCallbacks(callbacks, context) {
15328    var override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;
15329    return override ? callbacks.override(override) : callbacks;
15330  }
15331
15332  var Tooltip = /*#__PURE__*/function (_Element8) {
15333    _inherits(Tooltip, _Element8);
15334
15335    var _super18 = _createSuper(Tooltip);
15336
15337    function Tooltip(config) {
15338      var _this13;
15339
15340      _classCallCheck(this, Tooltip);
15341
15342      _this13 = _super18.call(this);
15343      _this13.opacity = 0;
15344      _this13._active = [];
15345      _this13._chart = config._chart;
15346      _this13._eventPosition = undefined;
15347      _this13._size = undefined;
15348      _this13._cachedAnimations = undefined;
15349      _this13._tooltipItems = [];
15350      _this13.$animations = undefined;
15351      _this13.$context = undefined;
15352      _this13.options = config.options;
15353      _this13.dataPoints = undefined;
15354      _this13.title = undefined;
15355      _this13.beforeBody = undefined;
15356      _this13.body = undefined;
15357      _this13.afterBody = undefined;
15358      _this13.footer = undefined;
15359      _this13.xAlign = undefined;
15360      _this13.yAlign = undefined;
15361      _this13.x = undefined;
15362      _this13.y = undefined;
15363      _this13.height = undefined;
15364      _this13.width = undefined;
15365      _this13.caretX = undefined;
15366      _this13.caretY = undefined;
15367      _this13.labelColors = undefined;
15368      _this13.labelPointStyles = undefined;
15369      _this13.labelTextColors = undefined;
15370      return _this13;
15371    }
15372
15373    _createClass(Tooltip, [{
15374      key: "initialize",
15375      value: function initialize(options) {
15376        this.options = options;
15377        this._cachedAnimations = undefined;
15378        this.$context = undefined;
15379      }
15380    }, {
15381      key: "_resolveAnimations",
15382      value: function _resolveAnimations() {
15383        var me = this;
15384        var cached = me._cachedAnimations;
15385
15386        if (cached) {
15387          return cached;
15388        }
15389
15390        var chart = me._chart;
15391        var options = me.options.setContext(me.getContext());
15392        var opts = options.enabled && chart.options.animation && options.animations;
15393        var animations = new Animations(me._chart, opts);
15394
15395        if (opts._cacheable) {
15396          me._cachedAnimations = Object.freeze(animations);
15397        }
15398
15399        return animations;
15400      }
15401    }, {
15402      key: "getContext",
15403      value: function getContext() {
15404        var me = this;
15405        return me.$context || (me.$context = createTooltipContext(me._chart.getContext(), me, me._tooltipItems));
15406      }
15407    }, {
15408      key: "getTitle",
15409      value: function getTitle(context, options) {
15410        var me = this;
15411        var callbacks = options.callbacks;
15412        var beforeTitle = callbacks.beforeTitle.apply(me, [context]);
15413        var title = callbacks.title.apply(me, [context]);
15414        var afterTitle = callbacks.afterTitle.apply(me, [context]);
15415        var lines = [];
15416        lines = pushOrConcat(lines, splitNewlines(beforeTitle));
15417        lines = pushOrConcat(lines, splitNewlines(title));
15418        lines = pushOrConcat(lines, splitNewlines(afterTitle));
15419        return lines;
15420      }
15421    }, {
15422      key: "getBeforeBody",
15423      value: function getBeforeBody(tooltipItems, options) {
15424        return getBeforeAfterBodyLines(options.callbacks.beforeBody.apply(this, [tooltipItems]));
15425      }
15426    }, {
15427      key: "getBody",
15428      value: function getBody(tooltipItems, options) {
15429        var me = this;
15430        var callbacks = options.callbacks;
15431        var bodyItems = [];
15432        each(tooltipItems, function (context) {
15433          var bodyItem = {
15434            before: [],
15435            lines: [],
15436            after: []
15437          };
15438          var scoped = overrideCallbacks(callbacks, context);
15439          pushOrConcat(bodyItem.before, splitNewlines(scoped.beforeLabel.call(me, context)));
15440          pushOrConcat(bodyItem.lines, scoped.label.call(me, context));
15441          pushOrConcat(bodyItem.after, splitNewlines(scoped.afterLabel.call(me, context)));
15442          bodyItems.push(bodyItem);
15443        });
15444        return bodyItems;
15445      }
15446    }, {
15447      key: "getAfterBody",
15448      value: function getAfterBody(tooltipItems, options) {
15449        return getBeforeAfterBodyLines(options.callbacks.afterBody.apply(this, [tooltipItems]));
15450      }
15451    }, {
15452      key: "getFooter",
15453      value: function getFooter(tooltipItems, options) {
15454        var me = this;
15455        var callbacks = options.callbacks;
15456        var beforeFooter = callbacks.beforeFooter.apply(me, [tooltipItems]);
15457        var footer = callbacks.footer.apply(me, [tooltipItems]);
15458        var afterFooter = callbacks.afterFooter.apply(me, [tooltipItems]);
15459        var lines = [];
15460        lines = pushOrConcat(lines, splitNewlines(beforeFooter));
15461        lines = pushOrConcat(lines, splitNewlines(footer));
15462        lines = pushOrConcat(lines, splitNewlines(afterFooter));
15463        return lines;
15464      }
15465    }, {
15466      key: "_createItems",
15467      value: function _createItems(options) {
15468        var me = this;
15469        var active = me._active;
15470        var data = me._chart.data;
15471        var labelColors = [];
15472        var labelPointStyles = [];
15473        var labelTextColors = [];
15474        var tooltipItems = [];
15475        var i, len;
15476
15477        for (i = 0, len = active.length; i < len; ++i) {
15478          tooltipItems.push(createTooltipItem(me._chart, active[i]));
15479        }
15480
15481        if (options.filter) {
15482          tooltipItems = tooltipItems.filter(function (element, index, array) {
15483            return options.filter(element, index, array, data);
15484          });
15485        }
15486
15487        if (options.itemSort) {
15488          tooltipItems = tooltipItems.sort(function (a, b) {
15489            return options.itemSort(a, b, data);
15490          });
15491        }
15492
15493        each(tooltipItems, function (context) {
15494          var scoped = overrideCallbacks(options.callbacks, context);
15495          labelColors.push(scoped.labelColor.call(me, context));
15496          labelPointStyles.push(scoped.labelPointStyle.call(me, context));
15497          labelTextColors.push(scoped.labelTextColor.call(me, context));
15498        });
15499        me.labelColors = labelColors;
15500        me.labelPointStyles = labelPointStyles;
15501        me.labelTextColors = labelTextColors;
15502        me.dataPoints = tooltipItems;
15503        return tooltipItems;
15504      }
15505    }, {
15506      key: "update",
15507      value: function update(changed, replay) {
15508        var me = this;
15509        var options = me.options.setContext(me.getContext());
15510        var active = me._active;
15511        var properties;
15512        var tooltipItems = [];
15513
15514        if (!active.length) {
15515          if (me.opacity !== 0) {
15516            properties = {
15517              opacity: 0
15518            };
15519          }
15520        } else {
15521          var position = positioners[options.position].call(me, active, me._eventPosition);
15522          tooltipItems = me._createItems(options);
15523          me.title = me.getTitle(tooltipItems, options);
15524          me.beforeBody = me.getBeforeBody(tooltipItems, options);
15525          me.body = me.getBody(tooltipItems, options);
15526          me.afterBody = me.getAfterBody(tooltipItems, options);
15527          me.footer = me.getFooter(tooltipItems, options);
15528          var size = me._size = getTooltipSize(me, options);
15529          var positionAndSize = Object.assign({}, position, size);
15530          var alignment = determineAlignment(me._chart, options, positionAndSize);
15531          var backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, me._chart);
15532          me.xAlign = alignment.xAlign;
15533          me.yAlign = alignment.yAlign;
15534          properties = {
15535            opacity: 1,
15536            x: backgroundPoint.x,
15537            y: backgroundPoint.y,
15538            width: size.width,
15539            height: size.height,
15540            caretX: position.x,
15541            caretY: position.y
15542          };
15543        }
15544
15545        me._tooltipItems = tooltipItems;
15546        me.$context = undefined;
15547
15548        if (properties) {
15549          me._resolveAnimations().update(me, properties);
15550        }
15551
15552        if (changed && options.external) {
15553          options.external.call(me, {
15554            chart: me._chart,
15555            tooltip: me,
15556            replay: replay
15557          });
15558        }
15559      }
15560    }, {
15561      key: "drawCaret",
15562      value: function drawCaret(tooltipPoint, ctx, size, options) {
15563        var caretPosition = this.getCaretPosition(tooltipPoint, size, options);
15564        ctx.lineTo(caretPosition.x1, caretPosition.y1);
15565        ctx.lineTo(caretPosition.x2, caretPosition.y2);
15566        ctx.lineTo(caretPosition.x3, caretPosition.y3);
15567      }
15568    }, {
15569      key: "getCaretPosition",
15570      value: function getCaretPosition(tooltipPoint, size, options) {
15571        var xAlign = this.xAlign,
15572            yAlign = this.yAlign;
15573        var cornerRadius = options.cornerRadius,
15574            caretSize = options.caretSize;
15575        var ptX = tooltipPoint.x,
15576            ptY = tooltipPoint.y;
15577        var width = size.width,
15578            height = size.height;
15579        var x1, x2, x3, y1, y2, y3;
15580
15581        if (yAlign === 'center') {
15582          y2 = ptY + height / 2;
15583
15584          if (xAlign === 'left') {
15585            x1 = ptX;
15586            x2 = x1 - caretSize;
15587            y1 = y2 + caretSize;
15588            y3 = y2 - caretSize;
15589          } else {
15590            x1 = ptX + width;
15591            x2 = x1 + caretSize;
15592            y1 = y2 - caretSize;
15593            y3 = y2 + caretSize;
15594          }
15595
15596          x3 = x1;
15597        } else {
15598          if (xAlign === 'left') {
15599            x2 = ptX + cornerRadius + caretSize;
15600          } else if (xAlign === 'right') {
15601            x2 = ptX + width - cornerRadius - caretSize;
15602          } else {
15603            x2 = this.caretX;
15604          }
15605
15606          if (yAlign === 'top') {
15607            y1 = ptY;
15608            y2 = y1 - caretSize;
15609            x1 = x2 - caretSize;
15610            x3 = x2 + caretSize;
15611          } else {
15612            y1 = ptY + height;
15613            y2 = y1 + caretSize;
15614            x1 = x2 + caretSize;
15615            x3 = x2 - caretSize;
15616          }
15617
15618          y3 = y1;
15619        }
15620
15621        return {
15622          x1: x1,
15623          x2: x2,
15624          x3: x3,
15625          y1: y1,
15626          y2: y2,
15627          y3: y3
15628        };
15629      }
15630    }, {
15631      key: "drawTitle",
15632      value: function drawTitle(pt, ctx, options) {
15633        var me = this;
15634        var title = me.title;
15635        var length = title.length;
15636        var titleFont, titleSpacing, i;
15637
15638        if (length) {
15639          var rtlHelper = getRtlAdapter(options.rtl, me.x, me.width);
15640          pt.x = getAlignedX(me, options.titleAlign, options);
15641          ctx.textAlign = rtlHelper.textAlign(options.titleAlign);
15642          ctx.textBaseline = 'middle';
15643          titleFont = toFont(options.titleFont);
15644          titleSpacing = options.titleSpacing;
15645          ctx.fillStyle = options.titleColor;
15646          ctx.font = titleFont.string;
15647
15648          for (i = 0; i < length; ++i) {
15649            ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);
15650            pt.y += titleFont.lineHeight + titleSpacing;
15651
15652            if (i + 1 === length) {
15653              pt.y += options.titleMarginBottom - titleSpacing;
15654            }
15655          }
15656        }
15657      }
15658    }, {
15659      key: "_drawColorBox",
15660      value: function _drawColorBox(ctx, pt, i, rtlHelper, options) {
15661        var me = this;
15662        var labelColors = me.labelColors[i];
15663        var labelPointStyle = me.labelPointStyles[i];
15664        var boxHeight = options.boxHeight,
15665            boxWidth = options.boxWidth;
15666        var bodyFont = toFont(options.bodyFont);
15667        var colorX = getAlignedX(me, 'left', options);
15668        var rtlColorX = rtlHelper.x(colorX);
15669        var yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;
15670        var colorY = pt.y + yOffSet;
15671
15672        if (options.usePointStyle) {
15673          var drawOptions = {
15674            radius: Math.min(boxWidth, boxHeight) / 2,
15675            pointStyle: labelPointStyle.pointStyle,
15676            rotation: labelPointStyle.rotation,
15677            borderWidth: 1
15678          };
15679          var centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;
15680          var centerY = colorY + boxHeight / 2;
15681          ctx.strokeStyle = options.multiKeyBackground;
15682          ctx.fillStyle = options.multiKeyBackground;
15683          drawPoint(ctx, drawOptions, centerX, centerY);
15684          ctx.strokeStyle = labelColors.borderColor;
15685          ctx.fillStyle = labelColors.backgroundColor;
15686          drawPoint(ctx, drawOptions, centerX, centerY);
15687        } else {
15688          ctx.lineWidth = labelColors.borderWidth || 1;
15689          ctx.strokeStyle = labelColors.borderColor;
15690          ctx.setLineDash(labelColors.borderDash || []);
15691          ctx.lineDashOffset = labelColors.borderDashOffset || 0;
15692          var outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth);
15693          var innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2);
15694          var borderRadius = toTRBLCorners(labelColors.borderRadius);
15695
15696          if (Object.values(borderRadius).some(function (v) {
15697            return v !== 0;
15698          })) {
15699            ctx.beginPath();
15700            ctx.fillStyle = options.multiKeyBackground;
15701            addRoundedRectPath(ctx, {
15702              x: outerX,
15703              y: colorY,
15704              w: boxWidth,
15705              h: boxHeight,
15706              radius: borderRadius
15707            });
15708            ctx.fill();
15709            ctx.stroke();
15710            ctx.fillStyle = labelColors.backgroundColor;
15711            ctx.beginPath();
15712            addRoundedRectPath(ctx, {
15713              x: innerX,
15714              y: colorY + 1,
15715              w: boxWidth - 2,
15716              h: boxHeight - 2,
15717              radius: borderRadius
15718            });
15719            ctx.fill();
15720          } else {
15721            ctx.fillStyle = options.multiKeyBackground;
15722            ctx.fillRect(outerX, colorY, boxWidth, boxHeight);
15723            ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);
15724            ctx.fillStyle = labelColors.backgroundColor;
15725            ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);
15726          }
15727        }
15728
15729        ctx.fillStyle = me.labelTextColors[i];
15730      }
15731    }, {
15732      key: "drawBody",
15733      value: function drawBody(pt, ctx, options) {
15734        var me = this;
15735        var body = me.body;
15736        var bodySpacing = options.bodySpacing,
15737            bodyAlign = options.bodyAlign,
15738            displayColors = options.displayColors,
15739            boxHeight = options.boxHeight,
15740            boxWidth = options.boxWidth;
15741        var bodyFont = toFont(options.bodyFont);
15742        var bodyLineHeight = bodyFont.lineHeight;
15743        var xLinePadding = 0;
15744        var rtlHelper = getRtlAdapter(options.rtl, me.x, me.width);
15745
15746        var fillLineOfText = function fillLineOfText(line) {
15747          ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);
15748          pt.y += bodyLineHeight + bodySpacing;
15749        };
15750
15751        var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
15752        var bodyItem, textColor, lines, i, j, ilen, jlen;
15753        ctx.textAlign = bodyAlign;
15754        ctx.textBaseline = 'middle';
15755        ctx.font = bodyFont.string;
15756        pt.x = getAlignedX(me, bodyAlignForCalculation, options);
15757        ctx.fillStyle = options.bodyColor;
15758        each(me.beforeBody, fillLineOfText);
15759        xLinePadding = displayColors && bodyAlignForCalculation !== 'right' ? bodyAlign === 'center' ? boxWidth / 2 + 1 : boxWidth + 2 : 0;
15760
15761        for (i = 0, ilen = body.length; i < ilen; ++i) {
15762          bodyItem = body[i];
15763          textColor = me.labelTextColors[i];
15764          ctx.fillStyle = textColor;
15765          each(bodyItem.before, fillLineOfText);
15766          lines = bodyItem.lines;
15767
15768          if (displayColors && lines.length) {
15769            me._drawColorBox(ctx, pt, i, rtlHelper, options);
15770
15771            bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);
15772          }
15773
15774          for (j = 0, jlen = lines.length; j < jlen; ++j) {
15775            fillLineOfText(lines[j]);
15776            bodyLineHeight = bodyFont.lineHeight;
15777          }
15778
15779          each(bodyItem.after, fillLineOfText);
15780        }
15781
15782        xLinePadding = 0;
15783        bodyLineHeight = bodyFont.lineHeight;
15784        each(me.afterBody, fillLineOfText);
15785        pt.y -= bodySpacing;
15786      }
15787    }, {
15788      key: "drawFooter",
15789      value: function drawFooter(pt, ctx, options) {
15790        var me = this;
15791        var footer = me.footer;
15792        var length = footer.length;
15793        var footerFont, i;
15794
15795        if (length) {
15796          var rtlHelper = getRtlAdapter(options.rtl, me.x, me.width);
15797          pt.x = getAlignedX(me, options.footerAlign, options);
15798          pt.y += options.footerMarginTop;
15799          ctx.textAlign = rtlHelper.textAlign(options.footerAlign);
15800          ctx.textBaseline = 'middle';
15801          footerFont = toFont(options.footerFont);
15802          ctx.fillStyle = options.footerColor;
15803          ctx.font = footerFont.string;
15804
15805          for (i = 0; i < length; ++i) {
15806            ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);
15807            pt.y += footerFont.lineHeight + options.footerSpacing;
15808          }
15809        }
15810      }
15811    }, {
15812      key: "drawBackground",
15813      value: function drawBackground(pt, ctx, tooltipSize, options) {
15814        var xAlign = this.xAlign,
15815            yAlign = this.yAlign;
15816        var x = pt.x,
15817            y = pt.y;
15818        var width = tooltipSize.width,
15819            height = tooltipSize.height;
15820        var radius = options.cornerRadius;
15821        ctx.fillStyle = options.backgroundColor;
15822        ctx.strokeStyle = options.borderColor;
15823        ctx.lineWidth = options.borderWidth;
15824        ctx.beginPath();
15825        ctx.moveTo(x + radius, y);
15826
15827        if (yAlign === 'top') {
15828          this.drawCaret(pt, ctx, tooltipSize, options);
15829        }
15830
15831        ctx.lineTo(x + width - radius, y);
15832        ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
15833
15834        if (yAlign === 'center' && xAlign === 'right') {
15835          this.drawCaret(pt, ctx, tooltipSize, options);
15836        }
15837
15838        ctx.lineTo(x + width, y + height - radius);
15839        ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
15840
15841        if (yAlign === 'bottom') {
15842          this.drawCaret(pt, ctx, tooltipSize, options);
15843        }
15844
15845        ctx.lineTo(x + radius, y + height);
15846        ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
15847
15848        if (yAlign === 'center' && xAlign === 'left') {
15849          this.drawCaret(pt, ctx, tooltipSize, options);
15850        }
15851
15852        ctx.lineTo(x, y + radius);
15853        ctx.quadraticCurveTo(x, y, x + radius, y);
15854        ctx.closePath();
15855        ctx.fill();
15856
15857        if (options.borderWidth > 0) {
15858          ctx.stroke();
15859        }
15860      }
15861    }, {
15862      key: "_updateAnimationTarget",
15863      value: function _updateAnimationTarget(options) {
15864        var me = this;
15865        var chart = me._chart;
15866        var anims = me.$animations;
15867        var animX = anims && anims.x;
15868        var animY = anims && anims.y;
15869
15870        if (animX || animY) {
15871          var position = positioners[options.position].call(me, me._active, me._eventPosition);
15872
15873          if (!position) {
15874            return;
15875          }
15876
15877          var size = me._size = getTooltipSize(me, options);
15878          var positionAndSize = Object.assign({}, position, me._size);
15879          var alignment = determineAlignment(chart, options, positionAndSize);
15880          var point = getBackgroundPoint(options, positionAndSize, alignment, chart);
15881
15882          if (animX._to !== point.x || animY._to !== point.y) {
15883            me.xAlign = alignment.xAlign;
15884            me.yAlign = alignment.yAlign;
15885            me.width = size.width;
15886            me.height = size.height;
15887            me.caretX = position.x;
15888            me.caretY = position.y;
15889
15890            me._resolveAnimations().update(me, point);
15891          }
15892        }
15893      }
15894    }, {
15895      key: "draw",
15896      value: function draw(ctx) {
15897        var me = this;
15898        var options = me.options.setContext(me.getContext());
15899        var opacity = me.opacity;
15900
15901        if (!opacity) {
15902          return;
15903        }
15904
15905        me._updateAnimationTarget(options);
15906
15907        var tooltipSize = {
15908          width: me.width,
15909          height: me.height
15910        };
15911        var pt = {
15912          x: me.x,
15913          y: me.y
15914        };
15915        opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
15916        var padding = toPadding(options.padding);
15917        var hasTooltipContent = me.title.length || me.beforeBody.length || me.body.length || me.afterBody.length || me.footer.length;
15918
15919        if (options.enabled && hasTooltipContent) {
15920          ctx.save();
15921          ctx.globalAlpha = opacity;
15922          me.drawBackground(pt, ctx, tooltipSize, options);
15923          overrideTextDirection(ctx, options.textDirection);
15924          pt.y += padding.top;
15925          me.drawTitle(pt, ctx, options);
15926          me.drawBody(pt, ctx, options);
15927          me.drawFooter(pt, ctx, options);
15928          restoreTextDirection(ctx, options.textDirection);
15929          ctx.restore();
15930        }
15931      }
15932    }, {
15933      key: "getActiveElements",
15934      value: function getActiveElements() {
15935        return this._active || [];
15936      }
15937    }, {
15938      key: "setActiveElements",
15939      value: function setActiveElements(activeElements, eventPosition) {
15940        var me = this;
15941        var lastActive = me._active;
15942        var active = activeElements.map(function (_ref8) {
15943          var datasetIndex = _ref8.datasetIndex,
15944              index = _ref8.index;
15945
15946          var meta = me._chart.getDatasetMeta(datasetIndex);
15947
15948          if (!meta) {
15949            throw new Error('Cannot find a dataset at index ' + datasetIndex);
15950          }
15951
15952          return {
15953            datasetIndex: datasetIndex,
15954            element: meta.data[index],
15955            index: index
15956          };
15957        });
15958        var changed = !_elementsEqual(lastActive, active);
15959
15960        var positionChanged = me._positionChanged(active, eventPosition);
15961
15962        if (changed || positionChanged) {
15963          me._active = active;
15964          me._eventPosition = eventPosition;
15965          me.update(true);
15966        }
15967      }
15968    }, {
15969      key: "handleEvent",
15970      value: function handleEvent(e, replay) {
15971        var me = this;
15972        var options = me.options;
15973        var lastActive = me._active || [];
15974        var changed = false;
15975        var active = [];
15976
15977        if (e.type !== 'mouseout') {
15978          active = me._chart.getElementsAtEventForMode(e, options.mode, options, replay);
15979
15980          if (options.reverse) {
15981            active.reverse();
15982          }
15983        }
15984
15985        var positionChanged = me._positionChanged(active, e);
15986
15987        changed = replay || !_elementsEqual(active, lastActive) || positionChanged;
15988
15989        if (changed) {
15990          me._active = active;
15991
15992          if (options.enabled || options.external) {
15993            me._eventPosition = {
15994              x: e.x,
15995              y: e.y
15996            };
15997            me.update(true, replay);
15998          }
15999        }
16000
16001        return changed;
16002      }
16003    }, {
16004      key: "_positionChanged",
16005      value: function _positionChanged(active, e) {
16006        var caretX = this.caretX,
16007            caretY = this.caretY,
16008            options = this.options;
16009        var position = positioners[options.position].call(this, active, e);
16010        return position !== false && (caretX !== position.x || caretY !== position.y);
16011      }
16012    }]);
16013
16014    return Tooltip;
16015  }(Element);
16016
16017  Tooltip.positioners = positioners;
16018  var plugin_tooltip = {
16019    id: 'tooltip',
16020    _element: Tooltip,
16021    positioners: positioners,
16022    afterInit: function afterInit(chart, _args, options) {
16023      if (options) {
16024        chart.tooltip = new Tooltip({
16025          _chart: chart,
16026          options: options
16027        });
16028      }
16029    },
16030    beforeUpdate: function beforeUpdate(chart, _args, options) {
16031      if (chart.tooltip) {
16032        chart.tooltip.initialize(options);
16033      }
16034    },
16035    reset: function reset(chart, _args, options) {
16036      if (chart.tooltip) {
16037        chart.tooltip.initialize(options);
16038      }
16039    },
16040    afterDraw: function afterDraw(chart) {
16041      var tooltip = chart.tooltip;
16042      var args = {
16043        tooltip: tooltip
16044      };
16045
16046      if (chart.notifyPlugins('beforeTooltipDraw', args) === false) {
16047        return;
16048      }
16049
16050      if (tooltip) {
16051        tooltip.draw(chart.ctx);
16052      }
16053
16054      chart.notifyPlugins('afterTooltipDraw', args);
16055    },
16056    afterEvent: function afterEvent(chart, args) {
16057      if (chart.tooltip) {
16058        var useFinalPosition = args.replay;
16059
16060        if (chart.tooltip.handleEvent(args.event, useFinalPosition)) {
16061          args.changed = true;
16062        }
16063      }
16064    },
16065    defaults: {
16066      enabled: true,
16067      external: null,
16068      position: 'average',
16069      backgroundColor: 'rgba(0,0,0,0.8)',
16070      titleColor: '#fff',
16071      titleFont: {
16072        weight: 'bold'
16073      },
16074      titleSpacing: 2,
16075      titleMarginBottom: 6,
16076      titleAlign: 'left',
16077      bodyColor: '#fff',
16078      bodySpacing: 2,
16079      bodyFont: {},
16080      bodyAlign: 'left',
16081      footerColor: '#fff',
16082      footerSpacing: 2,
16083      footerMarginTop: 6,
16084      footerFont: {
16085        weight: 'bold'
16086      },
16087      footerAlign: 'left',
16088      padding: 6,
16089      caretPadding: 2,
16090      caretSize: 5,
16091      cornerRadius: 6,
16092      boxHeight: function boxHeight(ctx, opts) {
16093        return opts.bodyFont.size;
16094      },
16095      boxWidth: function boxWidth(ctx, opts) {
16096        return opts.bodyFont.size;
16097      },
16098      multiKeyBackground: '#fff',
16099      displayColors: true,
16100      borderColor: 'rgba(0,0,0,0)',
16101      borderWidth: 0,
16102      animation: {
16103        duration: 400,
16104        easing: 'easeOutQuart'
16105      },
16106      animations: {
16107        numbers: {
16108          type: 'number',
16109          properties: ['x', 'y', 'width', 'height', 'caretX', 'caretY']
16110        },
16111        opacity: {
16112          easing: 'linear',
16113          duration: 200
16114        }
16115      },
16116      callbacks: {
16117        beforeTitle: noop,
16118        title: function title(tooltipItems) {
16119          if (tooltipItems.length > 0) {
16120            var item = tooltipItems[0];
16121            var labels = item.chart.data.labels;
16122            var labelCount = labels ? labels.length : 0;
16123
16124            if (this && this.options && this.options.mode === 'dataset') {
16125              return item.dataset.label || '';
16126            } else if (item.label) {
16127              return item.label;
16128            } else if (labelCount > 0 && item.dataIndex < labelCount) {
16129              return labels[item.dataIndex];
16130            }
16131          }
16132
16133          return '';
16134        },
16135        afterTitle: noop,
16136        beforeBody: noop,
16137        beforeLabel: noop,
16138        label: function label(tooltipItem) {
16139          if (this && this.options && this.options.mode === 'dataset') {
16140            return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;
16141          }
16142
16143          var label = tooltipItem.dataset.label || '';
16144
16145          if (label) {
16146            label += ': ';
16147          }
16148
16149          var value = tooltipItem.formattedValue;
16150
16151          if (!isNullOrUndef(value)) {
16152            label += value;
16153          }
16154
16155          return label;
16156        },
16157        labelColor: function labelColor(tooltipItem) {
16158          var meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
16159          var options = meta.controller.getStyle(tooltipItem.dataIndex);
16160          return {
16161            borderColor: options.borderColor,
16162            backgroundColor: options.backgroundColor,
16163            borderWidth: options.borderWidth,
16164            borderDash: options.borderDash,
16165            borderDashOffset: options.borderDashOffset,
16166            borderRadius: 0
16167          };
16168        },
16169        labelTextColor: function labelTextColor() {
16170          return this.options.bodyColor;
16171        },
16172        labelPointStyle: function labelPointStyle(tooltipItem) {
16173          var meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
16174          var options = meta.controller.getStyle(tooltipItem.dataIndex);
16175          return {
16176            pointStyle: options.pointStyle,
16177            rotation: options.rotation
16178          };
16179        },
16180        afterLabel: noop,
16181        afterBody: noop,
16182        beforeFooter: noop,
16183        footer: noop,
16184        afterFooter: noop
16185      }
16186    },
16187    defaultRoutes: {
16188      bodyFont: 'font',
16189      footerFont: 'font',
16190      titleFont: 'font'
16191    },
16192    descriptors: {
16193      _scriptable: function _scriptable(name) {
16194        return name !== 'filter' && name !== 'itemSort' && name !== 'external';
16195      },
16196      _indexable: false,
16197      callbacks: {
16198        _scriptable: false,
16199        _indexable: false
16200      },
16201      animation: {
16202        _fallback: false
16203      },
16204      animations: {
16205        _fallback: 'animation'
16206      }
16207    },
16208    additionalOptionScopes: ['interaction']
16209  };
16210  var plugins = /*#__PURE__*/Object.freeze({
16211    __proto__: null,
16212    Decimation: plugin_decimation,
16213    Filler: plugin_filler,
16214    Legend: plugin_legend,
16215    SubTitle: plugin_subtitle,
16216    Title: plugin_title,
16217    Tooltip: plugin_tooltip
16218  });
16219
16220  var addIfString = function addIfString(labels, raw, index) {
16221    return typeof raw === 'string' ? labels.push(raw) - 1 : isNaN(raw) ? null : index;
16222  };
16223
16224  function findOrAddLabel(labels, raw, index) {
16225    var first = labels.indexOf(raw);
16226
16227    if (first === -1) {
16228      return addIfString(labels, raw, index);
16229    }
16230
16231    var last = labels.lastIndexOf(raw);
16232    return first !== last ? index : first;
16233  }
16234
16235  var validIndex = function validIndex(index, max) {
16236    return index === null ? null : _limitValue(Math.round(index), 0, max);
16237  };
16238
16239  var CategoryScale = /*#__PURE__*/function (_Scale) {
16240    _inherits(CategoryScale, _Scale);
16241
16242    var _super19 = _createSuper(CategoryScale);
16243
16244    function CategoryScale(cfg) {
16245      var _this14;
16246
16247      _classCallCheck(this, CategoryScale);
16248
16249      _this14 = _super19.call(this, cfg);
16250      _this14._startValue = undefined;
16251      _this14._valueRange = 0;
16252      return _this14;
16253    }
16254
16255    _createClass(CategoryScale, [{
16256      key: "parse",
16257      value: function parse(raw, index) {
16258        if (isNullOrUndef(raw)) {
16259          return null;
16260        }
16261
16262        var labels = this.getLabels();
16263        index = isFinite(index) && labels[index] === raw ? index : findOrAddLabel(labels, raw, valueOrDefault(index, raw));
16264        return validIndex(index, labels.length - 1);
16265      }
16266    }, {
16267      key: "determineDataLimits",
16268      value: function determineDataLimits() {
16269        var me = this;
16270
16271        var _me$getUserBounds2 = me.getUserBounds(),
16272            minDefined = _me$getUserBounds2.minDefined,
16273            maxDefined = _me$getUserBounds2.maxDefined;
16274
16275        var _me$getMinMax = me.getMinMax(true),
16276            min = _me$getMinMax.min,
16277            max = _me$getMinMax.max;
16278
16279        if (me.options.bounds === 'ticks') {
16280          if (!minDefined) {
16281            min = 0;
16282          }
16283
16284          if (!maxDefined) {
16285            max = me.getLabels().length - 1;
16286          }
16287        }
16288
16289        me.min = min;
16290        me.max = max;
16291      }
16292    }, {
16293      key: "buildTicks",
16294      value: function buildTicks() {
16295        var me = this;
16296        var min = me.min;
16297        var max = me.max;
16298        var offset = me.options.offset;
16299        var ticks = [];
16300        var labels = me.getLabels();
16301        labels = min === 0 && max === labels.length - 1 ? labels : labels.slice(min, max + 1);
16302        me._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);
16303        me._startValue = me.min - (offset ? 0.5 : 0);
16304
16305        for (var value = min; value <= max; value++) {
16306          ticks.push({
16307            value: value
16308          });
16309        }
16310
16311        return ticks;
16312      }
16313    }, {
16314      key: "getLabelForValue",
16315      value: function getLabelForValue(value) {
16316        var me = this;
16317        var labels = me.getLabels();
16318
16319        if (value >= 0 && value < labels.length) {
16320          return labels[value];
16321        }
16322
16323        return value;
16324      }
16325    }, {
16326      key: "configure",
16327      value: function configure() {
16328        var me = this;
16329
16330        _get(_getPrototypeOf(CategoryScale.prototype), "configure", this).call(this);
16331
16332        if (!me.isHorizontal()) {
16333          me._reversePixels = !me._reversePixels;
16334        }
16335      }
16336    }, {
16337      key: "getPixelForValue",
16338      value: function getPixelForValue(value) {
16339        var me = this;
16340
16341        if (typeof value !== 'number') {
16342          value = me.parse(value);
16343        }
16344
16345        return value === null ? NaN : me.getPixelForDecimal((value - me._startValue) / me._valueRange);
16346      }
16347    }, {
16348      key: "getPixelForTick",
16349      value: function getPixelForTick(index) {
16350        var me = this;
16351        var ticks = me.ticks;
16352
16353        if (index < 0 || index > ticks.length - 1) {
16354          return null;
16355        }
16356
16357        return me.getPixelForValue(ticks[index].value);
16358      }
16359    }, {
16360      key: "getValueForPixel",
16361      value: function getValueForPixel(pixel) {
16362        var me = this;
16363        return Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
16364      }
16365    }, {
16366      key: "getBasePixel",
16367      value: function getBasePixel() {
16368        return this.bottom;
16369      }
16370    }]);
16371
16372    return CategoryScale;
16373  }(Scale);
16374
16375  CategoryScale.id = 'category';
16376  CategoryScale.defaults = {
16377    ticks: {
16378      callback: CategoryScale.prototype.getLabelForValue
16379    }
16380  };
16381
16382  function generateTicks$1(generationOptions, dataRange) {
16383    var ticks = [];
16384    var MIN_SPACING = 1e-14;
16385    var bounds = generationOptions.bounds,
16386        step = generationOptions.step,
16387        min = generationOptions.min,
16388        max = generationOptions.max,
16389        precision = generationOptions.precision,
16390        count = generationOptions.count,
16391        maxTicks = generationOptions.maxTicks,
16392        maxDigits = generationOptions.maxDigits,
16393        includeBounds = generationOptions.includeBounds;
16394    var unit = step || 1;
16395    var maxSpaces = maxTicks - 1;
16396    var rmin = dataRange.min,
16397        rmax = dataRange.max;
16398    var minDefined = !isNullOrUndef(min);
16399    var maxDefined = !isNullOrUndef(max);
16400    var countDefined = !isNullOrUndef(count);
16401    var minSpacing = (rmax - rmin) / (maxDigits + 1);
16402    var spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit;
16403    var factor, niceMin, niceMax, numSpaces;
16404
16405    if (spacing < MIN_SPACING && !minDefined && !maxDefined) {
16406      return [{
16407        value: rmin
16408      }, {
16409        value: rmax
16410      }];
16411    }
16412
vendor: 4,384 bytes, lines 16413-16565
16413    numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
16414
16415    if (numSpaces > maxSpaces) {
16416      spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit;
16417    }
16418
16419    if (!isNullOrUndef(precision)) {
16420      factor = Math.pow(10, precision);
16421      spacing = Math.ceil(spacing * factor) / factor;
16422    }
16423
16424    if (bounds === 'ticks') {
16425      niceMin = Math.floor(rmin / spacing) * spacing;
16426      niceMax = Math.ceil(rmax / spacing) * spacing;
16427    } else {
16428      niceMin = rmin;
16429      niceMax = rmax;
16430    }
16431
16432    if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) {
16433      numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks));
16434      spacing = (max - min) / numSpaces;
16435      niceMin = min;
16436      niceMax = max;
16437    } else if (countDefined) {
16438      niceMin = minDefined ? min : niceMin;
16439      niceMax = maxDefined ? max : niceMax;
16440      numSpaces = count - 1;
16441      spacing = (niceMax - niceMin) / numSpaces;
16442    } else {
16443      numSpaces = (niceMax - niceMin) / spacing;
16444
16445      if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
16446        numSpaces = Math.round(numSpaces);
16447      } else {
16448        numSpaces = Math.ceil(numSpaces);
16449      }
16450    }
16451
16452    var decimalPlaces = Math.max(_decimalPlaces(spacing), _decimalPlaces(niceMin));
16453    factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision);
16454    niceMin = Math.round(niceMin * factor) / factor;
16455    niceMax = Math.round(niceMax * factor) / factor;
16456    var j = 0;
16457
16458    if (minDefined) {
16459      if (includeBounds && niceMin !== min) {
16460        ticks.push({
16461          value: min
16462        });
16463
16464        if (niceMin < min) {
16465          j++;
16466        }
16467
16468        if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) {
16469          j++;
16470        }
16471      } else if (niceMin < min) {
16472        j++;
16473      }
16474    }
16475
16476    for (; j < numSpaces; ++j) {
16477      ticks.push({
16478        value: Math.round((niceMin + j * spacing) * factor) / factor
16479      });
16480    }
16481
16482    if (maxDefined && includeBounds && niceMax !== max) {
16483      if (almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) {
16484        ticks[ticks.length - 1].value = max;
16485      } else {
16486        ticks.push({
16487          value: max
16488        });
16489      }
16490    } else if (!maxDefined || niceMax === max) {
16491      ticks.push({
16492        value: niceMax
16493      });
16494    }
16495
16496    return ticks;
16497  }
16498
16499  function relativeLabelSize(value, minSpacing, _ref9) {
16500    var horizontal = _ref9.horizontal,
16501        minRotation = _ref9.minRotation;
16502    var rad = toRadians(minRotation);
16503    var ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001;
16504    var length = 0.75 * minSpacing * ('' + value).length;
16505    return Math.min(minSpacing / ratio, length);
16506  }
16507
16508  var LinearScaleBase = /*#__PURE__*/function (_Scale2) {
16509    _inherits(LinearScaleBase, _Scale2);
16510
16511    var _super20 = _createSuper(LinearScaleBase);
16512
16513    function LinearScaleBase(cfg) {
16514      var _this15;
16515
16516      _classCallCheck(this, LinearScaleBase);
16517
16518      _this15 = _super20.call(this, cfg);
16519      _this15.start = undefined;
16520      _this15.end = undefined;
16521      _this15._startValue = undefined;
16522      _this15._endValue = undefined;
16523      _this15._valueRange = 0;
16524      return _this15;
16525    }
16526
16527    _createClass(LinearScaleBase, [{
16528      key: "parse",
16529      value: function parse(raw, index) {
16530        if (isNullOrUndef(raw)) {
16531          return null;
16532        }
16533
16534        if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {
16535          return null;
16536        }
16537
16538        return +raw;
16539      }
16540    }, {
16541      key: "handleTickRangeOptions",
16542      value: function handleTickRangeOptions() {
16543        var me = this;
16544        var beginAtZero = me.options.beginAtZero;
16545
16546        var _me$getUserBounds3 = me.getUserBounds(),
16547            minDefined = _me$getUserBounds3.minDefined,
16548            maxDefined = _me$getUserBounds3.maxDefined;
16549
16550        var min = me.min,
16551            max = me.max;
16552
16553        var setMin = function setMin(v) {
16554          return min = minDefined ? min : v;
16555        };
16556
16557        var setMax = function setMax(v) {
16558          return max = maxDefined ? max : v;
16559        };
16560
16561        if (beginAtZero) {
16562          var minSign = sign(min);
16563          var maxSign = sign(max);
16564
16565          if (minSign < 0 && maxSign < 0) {
16566            setMax(0);
16567          } else if (minSign > 0 && maxSign > 0) {
16568            setMin(0);
16569          }
16570        }
16571
16572        if (min === max) {
16573          setMax(max + 1);
16574
16575          if (!beginAtZero) {
16576            setMin(min - 1);
16577          }
16578        }
16579
16580        me.min = min;
16581        me.max = max;
16582      }
16583    }, {
16584      key: "getTickLimit",
16585      value: function getTickLimit() {
16586        var me = this;
16587        var tickOpts = me.options.ticks;
16588        var maxTicksLimit = tickOpts.maxTicksLimit,
16589            stepSize = tickOpts.stepSize;
16590        var maxTicks;
16591
16592        if (stepSize) {
16593          maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
16594        } else {
16595          maxTicks = me.computeTickLimit();
16596          maxTicksLimit = maxTicksLimit || 11;
16597        }
16598
16599        if (maxTicksLimit) {
16600          maxTicks = Math.min(maxTicksLimit, maxTicks);
16601        }
16602
16603        return maxTicks;
16604      }
16605    }, {
16606      key: "computeTickLimit",
16607      value: function computeTickLimit() {
16608        return Number.POSITIVE_INFINITY;
16609      }
16610    }, {
16611      key: "buildTicks",
16612      value: function buildTicks() {
16613        var me = this;
16614        var opts = me.options;
16615        var tickOpts = opts.ticks;
16616        var maxTicks = me.getTickLimit();
16617        maxTicks = Math.max(2, maxTicks);
16618        var numericGeneratorOptions = {
16619          maxTicks: maxTicks,
16620          bounds: opts.bounds,
16621          min: opts.min,
16622          max: opts.max,
16623          precision: tickOpts.precision,
16624          step: tickOpts.stepSize,
16625          count: tickOpts.count,
16626          maxDigits: me._maxDigits(),
16627          horizontal: me.isHorizontal(),
16628          minRotation: tickOpts.minRotation || 0,
16629          includeBounds: tickOpts.includeBounds !== false
16630        };
16631        var dataRange = me._range || me;
16632        var ticks = generateTicks$1(numericGeneratorOptions, dataRange);
16633
16634        if (opts.bounds === 'ticks') {
16635          _setMinAndMaxByKey(ticks, me, 'value');
16636        }
16637
16638        if (opts.reverse) {
16639          ticks.reverse();
16640          me.start = me.max;
16641          me.end = me.min;
16642        } else {
16643          me.start = me.min;
16644          me.end = me.max;
16645        }
16646
16647        return ticks;
16648      }
16649    }, {
16650      key: "configure",
16651      value: function configure() {
16652        var me = this;
16653        var ticks = me.ticks;
16654        var start = me.min;
16655        var end = me.max;
16656
16657        _get(_getPrototypeOf(LinearScaleBase.prototype), "configure", this).call(this);
16658
16659        if (me.options.offset && ticks.length) {
16660          var offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
16661          start -= offset;
16662          end += offset;
16663        }
16664
16665        me._startValue = start;
16666        me._endValue = end;
16667        me._valueRange = end - start;
16668      }
16669    }, {
16670      key: "getLabelForValue",
16671      value: function getLabelForValue(value) {
16672        return formatNumber(value, this.chart.options.locale);
16673      }
16674    }]);
16675
16676    return LinearScaleBase;
16677  }(Scale);
16678
16679  var LinearScale = /*#__PURE__*/function (_LinearScaleBase) {
16680    _inherits(LinearScale, _LinearScaleBase);
16681
16682    var _super21 = _createSuper(LinearScale);
16683
16684    function LinearScale() {
16685      _classCallCheck(this, LinearScale);
16686
16687      return _super21.apply(this, arguments);
16688    }
16689
16690    _createClass(LinearScale, [{
16691      key: "determineDataLimits",
16692      value: function determineDataLimits() {
16693        var me = this;
16694
16695        var _me$getMinMax2 = me.getMinMax(true),
16696            min = _me$getMinMax2.min,
16697            max = _me$getMinMax2.max;
16698
16699        me.min = isNumberFinite(min) ? min : 0;
16700        me.max = isNumberFinite(max) ? max : 1;
16701        me.handleTickRangeOptions();
16702      }
16703    }, {
16704      key: "computeTickLimit",
16705      value: function computeTickLimit() {
16706        var me = this;
16707        var horizontal = me.isHorizontal();
16708        var length = horizontal ? me.width : me.height;
16709        var minRotation = toRadians(me.options.ticks.minRotation);
16710        var ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001;
16711
16712        var tickFont = me._resolveTickFontOptions(0);
16713
16714        return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio));
16715      }
16716    }, {
16717      key: "getPixelForValue",
16718      value: function getPixelForValue(value) {
16719        return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
16720      }
16721    }, {
16722      key: "getValueForPixel",
16723      value: function getValueForPixel(pixel) {
16724        return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
16725      }
16726    }]);
16727
16728    return LinearScale;
16729  }(LinearScaleBase);
16730
16731  LinearScale.id = 'linear';
16732  LinearScale.defaults = {
16733    ticks: {
16734      callback: Ticks.formatters.numeric
16735    }
16736  };
16737
16738  function isMajor(tickVal) {
16739    var remain = tickVal / Math.pow(10, Math.floor(log10(tickVal)));
16740    return remain === 1;
16741  }
16742
16743  function generateTicks(generationOptions, dataRange) {
16744    var endExp = Math.floor(log10(dataRange.max));
16745    var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
16746    var ticks = [];
16747    var tickVal = finiteOrDefault(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
16748    var exp = Math.floor(log10(tickVal));
16749    var significand = Math.floor(tickVal / Math.pow(10, exp));
16750    var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
16751
16752    do {
16753      ticks.push({
16754        value: tickVal,
16755        major: isMajor(tickVal)
16756      });
16757      ++significand;
16758
16759      if (significand === 10) {
16760        significand = 1;
16761        ++exp;
16762        precision = exp >= 0 ? 1 : precision;
16763      }
16764
16765      tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
16766    } while (exp < endExp || exp === endExp && significand < endSignificand);
16767
16768    var lastTick = finiteOrDefault(generationOptions.max, tickVal);
16769    ticks.push({
16770      value: lastTick,
16771      major: isMajor(tickVal)
16772    });
16773    return ticks;
16774  }
16775
16776  var LogarithmicScale = /*#__PURE__*/function (_Scale3) {
16777    _inherits(LogarithmicScale, _Scale3);
16778
16779    var _super22 = _createSuper(LogarithmicScale);
16780
16781    function LogarithmicScale(cfg) {
16782      var _this16;
16783
16784      _classCallCheck(this, LogarithmicScale);
16785
16786      _this16 = _super22.call(this, cfg);
16787      _this16.start = undefined;
16788      _this16.end = undefined;
16789      _this16._startValue = undefined;
16790      _this16._valueRange = 0;
16791      return _this16;
16792    }
16793
16794    _createClass(LogarithmicScale, [{
16795      key: "parse",
16796      value: function parse(raw, index) {
16797        var value = LinearScaleBase.prototype.parse.apply(this, [raw, index]);
16798
16799        if (value === 0) {
16800          this._zero = true;
16801          return undefined;
16802        }
16803
16804        return isNumberFinite(value) && value > 0 ? value : null;
16805      }
16806    }, {
16807      key: "determineDataLimits",
16808      value: function determineDataLimits() {
16809        var me = this;
16810
16811        var _me$getMinMax3 = me.getMinMax(true),
16812            min = _me$getMinMax3.min,
16813            max = _me$getMinMax3.max;
16814
16815        me.min = isNumberFinite(min) ? Math.max(0, min) : null;
16816        me.max = isNumberFinite(max) ? Math.max(0, max) : null;
16817
16818        if (me.options.beginAtZero) {
16819          me._zero = true;
16820        }
16821
16822        me.handleTickRangeOptions();
16823      }
16824    }, {
16825      key: "handleTickRangeOptions",
16826      value: function handleTickRangeOptions() {
16827        var me = this;
16828
16829        var _me$getUserBounds4 = me.getUserBounds(),
16830            minDefined = _me$getUserBounds4.minDefined,
16831            maxDefined = _me$getUserBounds4.maxDefined;
16832
16833        var min = me.min;
16834        var max = me.max;
16835
16836        var setMin = function setMin(v) {
16837          return min = minDefined ? min : v;
16838        };
16839
16840        var setMax = function setMax(v) {
16841          return max = maxDefined ? max : v;
16842        };
16843
16844        var exp = function exp(v, m) {
16845          return Math.pow(10, Math.floor(log10(v)) + m);
16846        };
16847
16848        if (min === max) {
16849          if (min <= 0) {
16850            setMin(1);
16851            setMax(10);
16852          } else {
16853            setMin(exp(min, -1));
16854            setMax(exp(max, +1));
16855          }
16856        }
16857
16858        if (min <= 0) {
16859          setMin(exp(max, -1));
16860        }
16861
16862        if (max <= 0) {
16863          setMax(exp(min, +1));
16864        }
16865
16866        if (me._zero && me.min !== me._suggestedMin && min === exp(me.min, 0)) {
16867          setMin(exp(min, -1));
16868        }
16869
16870        me.min = min;
16871        me.max = max;
16872      }
16873    }, {
16874      key: "buildTicks",
16875      value: function buildTicks() {
16876        var me = this;
16877        var opts = me.options;
16878        var generationOptions = {
16879          min: me._userMin,
16880          max: me._userMax
16881        };
16882        var ticks = generateTicks(generationOptions, me);
16883
16884        if (opts.bounds === 'ticks') {
16885          _setMinAndMaxByKey(ticks, me, 'value');
16886        }
16887
16888        if (opts.reverse) {
16889          ticks.reverse();
16890          me.start = me.max;
16891          me.end = me.min;
16892        } else {
16893          me.start = me.min;
16894          me.end = me.max;
16895        }
16896
16897        return ticks;
16898      }
16899    }, {
16900      key: "getLabelForValue",
16901      value: function getLabelForValue(value) {
16902        return value === undefined ? '0' : formatNumber(value, this.chart.options.locale);
16903      }
16904    }, {
16905      key: "configure",
16906      value: function configure() {
16907        var me = this;
16908        var start = me.min;
16909
16910        _get(_getPrototypeOf(LogarithmicScale.prototype), "configure", this).call(this);
16911
16912        me._startValue = log10(start);
16913        me._valueRange = log10(me.max) - log10(start);
16914      }
16915    }, {
16916      key: "getPixelForValue",
16917      value: function getPixelForValue(value) {
16918        var me = this;
16919
16920        if (value === undefined || value === 0) {
16921          value = me.min;
16922        }
16923
16924        if (value === null || isNaN(value)) {
16925          return NaN;
16926        }
16927
16928        return me.getPixelForDecimal(value === me.min ? 0 : (log10(value) - me._startValue) / me._valueRange);
16929      }
16930    }, {
16931      key: "getValueForPixel",
16932      value: function getValueForPixel(pixel) {
16933        var me = this;
16934        var decimal = me.getDecimalForPixel(pixel);
16935        return Math.pow(10, me._startValue + decimal * me._valueRange);
16936      }
16937    }]);
16938
16939    return LogarithmicScale;
16940  }(Scale);
16941
16942  LogarithmicScale.id = 'logarithmic';
16943  LogarithmicScale.defaults = {
16944    ticks: {
16945      callback: Ticks.formatters.logarithmic,
16946      major: {
16947        enabled: true
16948      }
16949    }
16950  };
16951
16952  function getTickBackdropHeight(opts) {
16953    var tickOpts = opts.ticks;
16954
16955    if (tickOpts.display && opts.display) {
16956      var padding = toPadding(tickOpts.backdropPadding);
16957      return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height;
16958    }
16959
16960    return 0;
16961  }
16962
16963  function measureLabelSize(ctx, font, label) {
16964    label = isArray(label) ? label : [label];
16965    return {
16966      w: _longestText(ctx, font.string, label),
16967      h: label.length * font.lineHeight
16968    };
16969  }
16970
16971  function determineLimits(angle, pos, size, min, max) {
16972    if (angle === min || angle === max) {
16973      return {
16974        start: pos - size / 2,
16975        end: pos + size / 2
16976      };
16977    } else if (angle < min || angle > max) {
16978      return {
16979        start: pos - size,
16980        end: pos
16981      };
16982    }
16983
16984    return {
16985      start: pos,
16986      end: pos + size
16987    };
16988  }
16989
16990  function fitWithPointLabels(scale) {
16991    var furthestLimits = {
16992      l: 0,
16993      r: scale.width,
16994      t: 0,
16995      b: scale.height - scale.paddingTop
16996    };
16997    var furthestAngles = {};
16998    var labelSizes = [];
16999    var padding = [];
17000    var valueCount = scale.getLabels().length;
17001
17002    for (var i = 0; i < valueCount; i++) {
17003      var opts = scale.options.pointLabels.setContext(scale.getContext(i));
17004      padding[i] = opts.padding;
17005      var pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i]);
17006      var plFont = toFont(opts.font);
17007      var textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]);
17008      labelSizes[i] = textSize;
17009      var angleRadians = scale.getIndexAngle(i);
17010      var angle = toDegrees(angleRadians);
17011      var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
17012      var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
17013
17014      if (hLimits.start < furthestLimits.l) {
17015        furthestLimits.l = hLimits.start;
17016        furthestAngles.l = angleRadians;
17017      }
17018
17019      if (hLimits.end > furthestLimits.r) {
17020        furthestLimits.r = hLimits.end;
17021        furthestAngles.r = angleRadians;
17022      }
17023
17024      if (vLimits.start < furthestLimits.t) {
17025        furthestLimits.t = vLimits.start;
17026        furthestAngles.t = angleRadians;
17027      }
17028
17029      if (vLimits.end > furthestLimits.b) {
17030        furthestLimits.b = vLimits.end;
17031        furthestAngles.b = angleRadians;
17032      }
17033    }
17034
17035    scale._setReductions(scale.drawingArea, furthestLimits, furthestAngles);
17036
17037    scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding);
17038  }
17039
17040  function buildPointLabelItems(scale, labelSizes, padding) {
17041    var items = [];
17042    var valueCount = scale.getLabels().length;
17043    var opts = scale.options;
17044    var tickBackdropHeight = getTickBackdropHeight(opts);
17045    var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
17046
17047    for (var i = 0; i < valueCount; i++) {
17048      var extra = i === 0 ? tickBackdropHeight / 2 : 0;
17049      var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + padding[i]);
17050      var angle = toDegrees(scale.getIndexAngle(i));
17051      var size = labelSizes[i];
17052      var y = yForAngle(pointLabelPosition.y, size.h, angle);
17053      var textAlign = getTextAlignForAngle(angle);
17054      var left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign);
17055      items.push({
17056        x: pointLabelPosition.x,
17057        y: y,
17058        textAlign: textAlign,
17059        left: left,
17060        top: y,
17061        right: left + size.w,
17062        bottom: y + size.h
17063      });
17064    }
17065
17066    return items;
17067  }
17068
17069  function getTextAlignForAngle(angle) {
17070    if (angle === 0 || angle === 180) {
17071      return 'center';
17072    } else if (angle < 180) {
17073      return 'left';
17074    }
17075
17076    return 'right';
17077  }
17078
17079  function leftForTextAlign(x, w, align) {
17080    if (align === 'right') {
17081      x -= w;
17082    } else if (align === 'center') {
17083      x -= w / 2;
17084    }
17085
17086    return x;
17087  }
17088
17089  function yForAngle(y, h, angle) {
17090    if (angle === 90 || angle === 270) {
17091      y -= h / 2;
17092    } else if (angle > 270 || angle < 90) {
17093      y -= h;
17094    }
17095
17096    return y;
17097  }
17098
17099  function drawPointLabels(scale, labelCount) {
17100    var ctx = scale.ctx,
17101        pointLabels = scale.options.pointLabels;
17102
17103    for (var i = labelCount - 1; i >= 0; i--) {
17104      var optsAtIndex = pointLabels.setContext(scale.getContext(i));
17105      var plFont = toFont(optsAtIndex.font);
17106      var _scale$_pointLabelIte = scale._pointLabelItems[i],
17107          x = _scale$_pointLabelIte.x,
17108          y = _scale$_pointLabelIte.y,
17109          textAlign = _scale$_pointLabelIte.textAlign,
17110          left = _scale$_pointLabelIte.left,
17111          top = _scale$_pointLabelIte.top,
17112          right = _scale$_pointLabelIte.right,
17113          bottom = _scale$_pointLabelIte.bottom;
17114      var backdropColor = optsAtIndex.backdropColor;
17115
17116      if (!isNullOrUndef(backdropColor)) {
17117        var padding = toPadding(optsAtIndex.backdropPadding);
17118        ctx.fillStyle = backdropColor;
17119        ctx.fillRect(left - padding.left, top - padding.top, right - left + padding.width, bottom - top + padding.height);
17120      }
17121
17122      renderText(ctx, scale._pointLabels[i], x, y + plFont.lineHeight / 2, plFont, {
17123        color: optsAtIndex.color,
17124        textAlign: textAlign,
17125        textBaseline: 'middle'
17126      });
17127    }
17128  }
17129
17130  function pathRadiusLine(scale, radius, circular, labelCount) {
17131    var ctx = scale.ctx;
17132
17133    if (circular) {
17134      ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU);
17135    } else {
17136      var pointPosition = scale.getPointPosition(0, radius);
17137      ctx.moveTo(pointPosition.x, pointPosition.y);
17138
17139      for (var i = 1; i < labelCount; i++) {
17140        pointPosition = scale.getPointPosition(i, radius);
17141        ctx.lineTo(pointPosition.x, pointPosition.y);
17142      }
17143    }
17144  }
17145
17146  function drawRadiusLine(scale, gridLineOpts, radius, labelCount) {
17147    var ctx = scale.ctx;
17148    var circular = gridLineOpts.circular;
17149    var color = gridLineOpts.color,
17150        lineWidth = gridLineOpts.lineWidth;
17151
17152    if (!circular && !labelCount || !color || !lineWidth || radius < 0) {
17153      return;
17154    }
17155
17156    ctx.save();
17157    ctx.strokeStyle = color;
17158    ctx.lineWidth = lineWidth;
17159    ctx.setLineDash(gridLineOpts.borderDash);
17160    ctx.lineDashOffset = gridLineOpts.borderDashOffset;
17161    ctx.beginPath();
17162    pathRadiusLine(scale, radius, circular, labelCount);
17163    ctx.closePath();
17164    ctx.stroke();
17165    ctx.restore();
17166  }
17167
17168  function numberOrZero(param) {
17169    return isNumber(param) ? param : 0;
17170  }
17171
17172  var RadialLinearScale = /*#__PURE__*/function (_LinearScaleBase2) {
17173    _inherits(RadialLinearScale, _LinearScaleBase2);
17174
17175    var _super23 = _createSuper(RadialLinearScale);
17176
17177    function RadialLinearScale(cfg) {
17178      var _this17;
17179
17180      _classCallCheck(this, RadialLinearScale);
17181
17182      _this17 = _super23.call(this, cfg);
17183      _this17.xCenter = undefined;
17184      _this17.yCenter = undefined;
17185      _this17.drawingArea = undefined;
17186      _this17._pointLabels = [];
17187      _this17._pointLabelItems = [];
17188      return _this17;
17189    }
17190
17191    _createClass(RadialLinearScale, [{
17192      key: "setDimensions",
17193      value: function setDimensions() {
17194        var me = this;
17195        me.width = me.maxWidth;
17196        me.height = me.maxHeight;
17197        me.paddingTop = getTickBackdropHeight(me.options) / 2;
17198        me.xCenter = Math.floor(me.width / 2);
17199        me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
17200        me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
17201      }
17202    }, {
17203      key: "determineDataLimits",
17204      value: function determineDataLimits() {
17205        var me = this;
17206
17207        var _me$getMinMax4 = me.getMinMax(false),
17208            min = _me$getMinMax4.min,
17209            max = _me$getMinMax4.max;
17210
17211        me.min = isNumberFinite(min) && !isNaN(min) ? min : 0;
17212        me.max = isNumberFinite(max) && !isNaN(max) ? max : 0;
17213        me.handleTickRangeOptions();
17214      }
17215    }, {
17216      key: "computeTickLimit",
17217      value: function computeTickLimit() {
17218        return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
17219      }
17220    }, {
17221      key: "generateTickLabels",
17222      value: function generateTickLabels(ticks) {
17223        var me = this;
17224        LinearScaleBase.prototype.generateTickLabels.call(me, ticks);
17225        me._pointLabels = me.getLabels().map(function (value, index) {
17226          var label = callback(me.options.pointLabels.callback, [value, index], me);
17227          return label || label === 0 ? label : '';
17228        });
17229      }
17230    }, {
17231      key: "fit",
17232      value: function fit() {
17233        var me = this;
17234        var opts = me.options;
17235
17236        if (opts.display && opts.pointLabels.display) {
17237          fitWithPointLabels(me);
17238        } else {
17239          me.setCenterPoint(0, 0, 0, 0);
17240        }
17241      }
17242    }, {
17243      key: "_setReductions",
17244      value: function _setReductions(largestPossibleRadius, furthestLimits, furthestAngles) {
17245        var me = this;
17246        var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
17247        var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
17248        var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
17249        var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
17250        radiusReductionLeft = numberOrZero(radiusReductionLeft);
17251        radiusReductionRight = numberOrZero(radiusReductionRight);
17252        radiusReductionTop = numberOrZero(radiusReductionTop);
17253        radiusReductionBottom = numberOrZero(radiusReductionBottom);
17254        me.drawingArea = Math.max(largestPossibleRadius / 2, Math.min(Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2), Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2)));
17255        me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
17256      }
17257    }, {
17258      key: "setCenterPoint",
17259      value: function setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {
17260        var me = this;
17261        var maxRight = me.width - rightMovement - me.drawingArea;
17262        var maxLeft = leftMovement + me.drawingArea;
17263        var maxTop = topMovement + me.drawingArea;
17264        var maxBottom = me.height - me.paddingTop - bottomMovement - me.drawingArea;
17265        me.xCenter = Math.floor((maxLeft + maxRight) / 2 + me.left);
17266        me.yCenter = Math.floor((maxTop + maxBottom) / 2 + me.top + me.paddingTop);
17267      }
17268    }, {
17269      key: "getIndexAngle",
17270      value: function getIndexAngle(index) {
17271        var angleMultiplier = TAU / this.getLabels().length;
17272        var startAngle = this.options.startAngle || 0;
17273        return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));
17274      }
17275    }, {
17276      key: "getDistanceFromCenterForValue",
17277      value: function getDistanceFromCenterForValue(value) {
17278        var me = this;
17279
17280        if (isNullOrUndef(value)) {
17281          return NaN;
17282        }
17283
17284        var scalingFactor = me.drawingArea / (me.max - me.min);
17285
17286        if (me.options.reverse) {
17287          return (me.max - value) * scalingFactor;
17288        }
17289
17290        return (value - me.min) * scalingFactor;
17291      }
17292    }, {
17293      key: "getValueForDistanceFromCenter",
17294      value: function getValueForDistanceFromCenter(distance) {
17295        if (isNullOrUndef(distance)) {
17296          return NaN;
17297        }
17298
17299        var me = this;
17300        var scaledDistance = distance / (me.drawingArea / (me.max - me.min));
17301        return me.options.reverse ? me.max - scaledDistance : me.min + scaledDistance;
17302      }
17303    }, {
17304      key: "getPointPosition",
17305      value: function getPointPosition(index, distanceFromCenter) {
17306        var me = this;
17307        var angle = me.getIndexAngle(index) - HALF_PI;
17308        return {
17309          x: Math.cos(angle) * distanceFromCenter + me.xCenter,
17310          y: Math.sin(angle) * distanceFromCenter + me.yCenter,
17311          angle: angle
17312        };
17313      }
17314    }, {
17315      key: "getPointPositionForValue",
17316      value: function getPointPositionForValue(index, value) {
17317        return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
17318      }
17319    }, {
17320      key: "getBasePosition",
17321      value: function getBasePosition(index) {
17322        return this.getPointPositionForValue(index || 0, this.getBaseValue());
17323      }
17324    }, {
17325      key: "getPointLabelPosition",
17326      value: function getPointLabelPosition(index) {
17327        var _this$_pointLabelItem = this._pointLabelItems[index],
17328            left = _this$_pointLabelItem.left,
17329            top = _this$_pointLabelItem.top,
17330            right = _this$_pointLabelItem.right,
17331            bottom = _this$_pointLabelItem.bottom;
17332        return {
17333          left: left,
17334          top: top,
17335          right: right,
17336          bottom: bottom
17337        };
17338      }
17339    }, {
17340      key: "drawBackground",
17341      value: function drawBackground() {
17342        var me = this;
17343        var _me$options7 = me.options,
17344            backgroundColor = _me$options7.backgroundColor,
17345            circular = _me$options7.grid.circular;
17346
17347        if (backgroundColor) {
17348          var ctx = me.ctx;
17349          ctx.save();
17350          ctx.beginPath();
17351          pathRadiusLine(me, me.getDistanceFromCenterForValue(me._endValue), circular, me.getLabels().length);
17352          ctx.closePath();
17353          ctx.fillStyle = backgroundColor;
17354          ctx.fill();
17355          ctx.restore();
17356        }
17357      }
17358    }, {
17359      key: "drawGrid",
17360      value: function drawGrid() {
17361        var me = this;
17362        var ctx = me.ctx;
17363        var opts = me.options;
17364        var angleLines = opts.angleLines,
17365            grid = opts.grid;
17366        var labelCount = me.getLabels().length;
17367        var i, offset, position;
17368
17369        if (opts.pointLabels.display) {
17370          drawPointLabels(me, labelCount);
17371        }
17372
17373        if (grid.display) {
17374          me.ticks.forEach(function (tick, index) {
17375            if (index !== 0) {
17376              offset = me.getDistanceFromCenterForValue(tick.value);
17377              var optsAtIndex = grid.setContext(me.getContext(index - 1));
17378              drawRadiusLine(me, optsAtIndex, offset, labelCount);
17379            }
17380          });
17381        }
17382
17383        if (angleLines.display) {
17384          ctx.save();
17385
17386          for (i = me.getLabels().length - 1; i >= 0; i--) {
17387            var optsAtIndex = angleLines.setContext(me.getContext(i));
17388            var color = optsAtIndex.color,
17389                lineWidth = optsAtIndex.lineWidth;
17390
17391            if (!lineWidth || !color) {
17392              continue;
17393            }
17394
17395            ctx.lineWidth = lineWidth;
17396            ctx.strokeStyle = color;
17397            ctx.setLineDash(optsAtIndex.borderDash);
17398            ctx.lineDashOffset = optsAtIndex.borderDashOffset;
17399            offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
17400            position = me.getPointPosition(i, offset);
17401            ctx.beginPath();
17402            ctx.moveTo(me.xCenter, me.yCenter);
17403            ctx.lineTo(position.x, position.y);
17404            ctx.stroke();
17405          }
17406
17407          ctx.restore();
17408        }
17409      }
17410    }, {
17411      key: "drawBorder",
17412      value: function drawBorder() {}
17413    }, {
17414      key: "drawLabels",
17415      value: function drawLabels() {
17416        var me = this;
17417        var ctx = me.ctx;
17418        var opts = me.options;
17419        var tickOpts = opts.ticks;
17420
17421        if (!tickOpts.display) {
17422          return;
17423        }
17424
17425        var startAngle = me.getIndexAngle(0);
17426        var offset, width;
17427        ctx.save();
17428        ctx.translate(me.xCenter, me.yCenter);
17429        ctx.rotate(startAngle);
17430        ctx.textAlign = 'center';
17431        ctx.textBaseline = 'middle';
17432        me.ticks.forEach(function (tick, index) {
17433          if (index === 0 && !opts.reverse) {
17434            return;
17435          }
17436
17437          var optsAtIndex = tickOpts.setContext(me.getContext(index));
17438          var tickFont = toFont(optsAtIndex.font);
17439          offset = me.getDistanceFromCenterForValue(me.ticks[index].value);
17440
17441          if (optsAtIndex.showLabelBackdrop) {
17442            ctx.font = tickFont.string;
17443            width = ctx.measureText(tick.label).width;
17444            ctx.fillStyle = optsAtIndex.backdropColor;
17445            var padding = toPadding(optsAtIndex.backdropPadding);
17446            ctx.fillRect(-width / 2 - padding.left, -offset - tickFont.size / 2 - padding.top, width + padding.width, tickFont.size + padding.height);
17447          }
17448
17449          renderText(ctx, tick.label, 0, -offset, tickFont, {
17450            color: optsAtIndex.color
17451          });
17452        });
17453        ctx.restore();
17454      }
17455    }, {
17456      key: "drawTitle",
17457      value: function drawTitle() {}
17458    }]);
17459
17460    return RadialLinearScale;
17461  }(LinearScaleBase);
17462
17463  RadialLinearScale.id = 'radialLinear';
17464  RadialLinearScale.defaults = {
17465    display: true,
17466    animate: true,
17467    position: 'chartArea',
17468    angleLines: {
17469      display: true,
17470      lineWidth: 1,
17471      borderDash: [],
17472      borderDashOffset: 0.0
17473    },
17474    grid: {
17475      circular: false
17476    },
17477    startAngle: 0,
17478    ticks: {
17479      showLabelBackdrop: true,
17480      callback: Ticks.formatters.numeric
17481    },
17482    pointLabels: {
17483      backdropColor: undefined,
17484      backdropPadding: 2,
17485      display: true,
17486      font: {
17487        size: 10
17488      },
17489      callback: function callback(label) {
17490        return label;
17491      },
17492      padding: 5
17493    }
17494  };
17495  RadialLinearScale.defaultRoutes = {
17496    'angleLines.color': 'borderColor',
17497    'pointLabels.color': 'color',
17498    'ticks.color': 'color'
17499  };
17500  RadialLinearScale.descriptors = {
17501    angleLines: {
17502      _fallback: 'grid'
17503    }
17504  };
17505  var INTERVALS = {
17506    millisecond: {
17507      common: true,
17508      size: 1,
17509      steps: 1000
17510    },
17511    second: {
17512      common: true,
17513      size: 1000,
17514      steps: 60
17515    },
17516    minute: {
17517      common: true,
17518      size: 60000,
17519      steps: 60
17520    },
17521    hour: {
17522      common: true,
17523      size: 3600000,
17524      steps: 24
17525    },
17526    day: {
17527      common: true,
17528      size: 86400000,
17529      steps: 30
17530    },
17531    week: {
17532      common: false,
17533      size: 604800000,
17534      steps: 4
17535    },
17536    month: {
17537      common: true,
17538      size: 2.628e9,
17539      steps: 12
17540    },
17541    quarter: {
17542      common: false,
17543      size: 7.884e9,
17544      steps: 4
17545    },
17546    year: {
17547      common: true,
17548      size: 3.154e10
17549    }
17550  };
17551  var UNITS = Object.keys(INTERVALS);
17552
17553  function sorter(a, b) {
17554    return a - b;
17555  }
17556
17557  function _parse(scale, input) {
17558    if (isNullOrUndef(input)) {
17559      return null;
17560    }
17561
17562    var adapter = scale._adapter;
17563    var _scale$_parseOpts = scale._parseOpts,
17564        parser = _scale$_parseOpts.parser,
17565        round = _scale$_parseOpts.round,
17566        isoWeekday = _scale$_parseOpts.isoWeekday;
17567    var value = input;
17568
17569    if (typeof parser === 'function') {
17570      value = parser(value);
17571    }
17572
17573    if (!isNumberFinite(value)) {
17574      value = typeof parser === 'string' ? adapter.parse(value, parser) : adapter.parse(value);
17575    }
17576
17577    if (value === null) {
17578      return null;
17579    }
17580
17581    if (round) {
17582      value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true) ? adapter.startOf(value, 'isoWeek', isoWeekday) : adapter.startOf(value, round);
17583    }
17584
17585    return +value;
17586  }
17587
17588  function determineUnitForAutoTicks(minUnit, min, max, capacity) {
17589    var ilen = UNITS.length;
17590
17591    for (var i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
17592      var interval = INTERVALS[UNITS[i]];
17593      var factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;
17594
17595      if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
17596        return UNITS[i];
17597      }
17598    }
17599
17600    return UNITS[ilen - 1];
17601  }
17602
17603  function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
17604    for (var i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
17605      var unit = UNITS[i];
17606
17607      if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
17608        return unit;
17609      }
17610    }
17611
17612    return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
17613  }
17614
17615  function determineMajorUnit(unit) {
17616    for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
17617      if (INTERVALS[UNITS[i]].common) {
17618        return UNITS[i];
17619      }
17620    }
17621  }
17622
17623  function addTick(ticks, time, timestamps) {
17624    if (!timestamps) {
17625      ticks[time] = true;
17626    } else if (timestamps.length) {
17627      var _lookup2 = _lookup(timestamps, time),
17628          lo = _lookup2.lo,
17629          hi = _lookup2.hi;
17630
17631      var timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];
17632      ticks[timestamp] = true;
17633    }
17634  }
17635
17636  function setMajorTicks(scale, ticks, map, majorUnit) {
17637    var adapter = scale._adapter;
17638    var first = +adapter.startOf(ticks[0].value, majorUnit);
17639    var last = ticks[ticks.length - 1].value;
17640    var major, index;
17641
17642    for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
17643      index = map[major];
17644
17645      if (index >= 0) {
17646        ticks[index].major = true;
17647      }
17648    }
17649
17650    return ticks;
17651  }
17652
17653  function ticksFromTimestamps(scale, values, majorUnit) {
17654    var ticks = [];
17655    var map = {};
17656    var ilen = values.length;
17657    var i, value;
17658
17659    for (i = 0; i < ilen; ++i) {
17660      value = values[i];
17661      map[value] = i;
17662      ticks.push({
17663        value: value,
17664        major: false
17665      });
17666    }
17667
17668    return ilen === 0 || !majorUnit ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
17669  }
17670
17671  var TimeScale = /*#__PURE__*/function (_Scale4) {
17672    _inherits(TimeScale, _Scale4);
17673
17674    var _super24 = _createSuper(TimeScale);
17675
17676    function TimeScale(props) {
17677      var _this18;
17678
17679      _classCallCheck(this, TimeScale);
17680
17681      _this18 = _super24.call(this, props);
17682      _this18._cache = {
17683        data: [],
17684        labels: [],
17685        all: []
17686      };
17687      _this18._unit = 'day';
17688      _this18._majorUnit = undefined;
17689      _this18._offsets = {};
17690      _this18._normalized = false;
17691      _this18._parseOpts = undefined;
17692      return _this18;
17693    }
17694
17695    _createClass(TimeScale, [{
17696      key: "init",
17697      value: function init(scaleOpts, opts) {
17698        var time = scaleOpts.time || (scaleOpts.time = {});
17699        var adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);
17700        mergeIf(time.displayFormats, adapter.formats());
17701        this._parseOpts = {
17702          parser: time.parser,
17703          round: time.round,
17704          isoWeekday: time.isoWeekday
17705        };
17706
17707        _get(_getPrototypeOf(TimeScale.prototype), "init", this).call(this, scaleOpts);
17708
17709        this._normalized = opts.normalized;
17710      }
17711    }, {
17712      key: "parse",
17713      value: function parse(raw, index) {
17714        if (raw === undefined) {
17715          return null;
17716        }
17717
17718        return _parse(this, raw);
17719      }
17720    }, {
17721      key: "beforeLayout",
17722      value: function beforeLayout() {
17723        _get(_getPrototypeOf(TimeScale.prototype), "beforeLayout", this).call(this);
17724
17725        this._cache = {
17726          data: [],
17727          labels: [],
17728          all: []
17729        };
17730      }
17731    }, {
17732      key: "determineDataLimits",
17733      value: function determineDataLimits() {
17734        var me = this;
17735        var options = me.options;
17736        var adapter = me._adapter;
17737        var unit = options.time.unit || 'day';
17738
17739        var _me$getUserBounds5 = me.getUserBounds(),
17740            min = _me$getUserBounds5.min,
17741            max = _me$getUserBounds5.max,
17742            minDefined = _me$getUserBounds5.minDefined,
17743            maxDefined = _me$getUserBounds5.maxDefined;
17744
17745        function _applyBounds(bounds) {
17746          if (!minDefined && !isNaN(bounds.min)) {
17747            min = Math.min(min, bounds.min);
17748          }
17749
17750          if (!maxDefined && !isNaN(bounds.max)) {
17751            max = Math.max(max, bounds.max);
17752          }
17753        }
17754
17755        if (!minDefined || !maxDefined) {
17756          _applyBounds(me._getLabelBounds());
17757
17758          if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {
17759            _applyBounds(me.getMinMax(false));
17760          }
17761        }
17762
17763        min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);
17764        max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;
17765        me.min = Math.min(min, max - 1);
17766        me.max = Math.max(min + 1, max);
17767      }
17768    }, {
17769      key: "_getLabelBounds",
17770      value: function _getLabelBounds() {
17771        var arr = this.getLabelTimestamps();
17772        var min = Number.POSITIVE_INFINITY;
17773        var max = Number.NEGATIVE_INFINITY;
17774
17775        if (arr.length) {
17776          min = arr[0];
17777          max = arr[arr.length - 1];
17778        }
17779
17780        return {
17781          min: min,
17782          max: max
17783        };
17784      }
17785    }, {
17786      key: "buildTicks",
17787      value: function buildTicks() {
17788        var me = this;
17789        var options = me.options;
17790        var timeOpts = options.time;
17791        var tickOpts = options.ticks;
17792        var timestamps = tickOpts.source === 'labels' ? me.getLabelTimestamps() : me._generate();
17793
17794        if (options.bounds === 'ticks' && timestamps.length) {
17795          me.min = me._userMin || timestamps[0];
17796          me.max = me._userMax || timestamps[timestamps.length - 1];
17797        }
17798
17799        var min = me.min;
17800        var max = me.max;
17801
17802        var ticks = _filterBetween(timestamps, min, max);
17803
17804        me._unit = timeOpts.unit || (tickOpts.autoSkip ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, me._getLabelCapacity(min)) : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
17805        me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined : determineMajorUnit(me._unit);
17806        me.initOffsets(timestamps);
17807
17808        if (options.reverse) {
17809          ticks.reverse();
17810        }
17811
17812        return ticksFromTimestamps(me, ticks, me._majorUnit);
17813      }
17814    }, {
17815      key: "initOffsets",
17816      value: function initOffsets(timestamps) {
17817        var me = this;
17818        var start = 0;
17819        var end = 0;
17820        var first, last;
17821
17822        if (me.options.offset && timestamps.length) {
17823          first = me.getDecimalForValue(timestamps[0]);
17824
17825          if (timestamps.length === 1) {
17826            start = 1 - first;
17827          } else {
17828            start = (me.getDecimalForValue(timestamps[1]) - first) / 2;
17829          }
17830
17831          last = me.getDecimalForValue(timestamps[timestamps.length - 1]);
17832
17833          if (timestamps.length === 1) {
17834            end = last;
17835          } else {
17836            end = (last - me.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;
17837          }
17838        }
17839
17840        var limit = timestamps.length < 3 ? 0.5 : 0.25;
17841        start = _limitValue(start, 0, limit);
17842        end = _limitValue(end, 0, limit);
17843        me._offsets = {
17844          start: start,
17845          end: end,
17846          factor: 1 / (start + 1 + end)
17847        };
17848      }
17849    }, {
17850      key: "_generate",
17851      value: function _generate() {
17852        var me = this;
17853        var adapter = me._adapter;
17854        var min = me.min;
17855        var max = me.max;
17856        var options = me.options;
17857        var timeOpts = options.time;
17858        var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, me._getLabelCapacity(min));
17859        var stepSize = valueOrDefault(timeOpts.stepSize, 1);
17860        var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
17861        var hasWeekday = isNumber(weekday) || weekday === true;
17862        var ticks = {};
17863        var first = min;
17864        var time, count;
17865
17866        if (hasWeekday) {
17867          first = +adapter.startOf(first, 'isoWeek', weekday);
17868        }
17869
17870        first = +adapter.startOf(first, hasWeekday ? 'day' : minor);
17871
17872        if (adapter.diff(max, min, minor) > 100000 * stepSize) {
17873          throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);
17874        }
17875
17876        var timestamps = options.ticks.source === 'data' && me.getDataTimestamps();
17877
17878        for (time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++) {
17879          addTick(ticks, time, timestamps);
17880        }
17881
17882        if (time === max || options.bounds === 'ticks' || count === 1) {
17883          addTick(ticks, time, timestamps);
17884        }
17885
17886        return Object.keys(ticks).sort(function (a, b) {
17887          return a - b;
17888        }).map(function (x) {
17889          return +x;
17890        });
17891      }
17892    }, {
17893      key: "getLabelForValue",
17894      value: function getLabelForValue(value) {
17895        var me = this;
17896        var adapter = me._adapter;
17897        var timeOpts = me.options.time;
17898
17899        if (timeOpts.tooltipFormat) {
17900          return adapter.format(value, timeOpts.tooltipFormat);
17901        }
17902
17903        return adapter.format(value, timeOpts.displayFormats.datetime);
17904      }
17905    }, {
17906      key: "_tickFormatFunction",
17907      value: function _tickFormatFunction(time, index, ticks, format) {
17908        var me = this;
17909        var options = me.options;
17910        var formats = options.time.displayFormats;
17911        var unit = me._unit;
17912        var majorUnit = me._majorUnit;
17913        var minorFormat = unit && formats[unit];
17914        var majorFormat = majorUnit && formats[majorUnit];
17915        var tick = ticks[index];
17916        var major = majorUnit && majorFormat && tick && tick.major;
17917
17918        var label = me._adapter.format(time, format || (major ? majorFormat : minorFormat));
17919
17920        var formatter = options.ticks.callback;
17921        return formatter ? callback(formatter, [label, index, ticks], me) : label;
17922      }
17923    }, {
17924      key: "generateTickLabels",
17925      value: function generateTickLabels(ticks) {
17926        var i, ilen, tick;
17927
17928        for (i = 0, ilen = ticks.length; i < ilen; ++i) {
17929          tick = ticks[i];
17930          tick.label = this._tickFormatFunction(tick.value, i, ticks);
17931        }
17932      }
17933    }, {
17934      key: "getDecimalForValue",
17935      value: function getDecimalForValue(value) {
17936        var me = this;
17937        return value === null ? NaN : (value - me.min) / (me.max - me.min);
17938      }
17939    }, {
17940      key: "getPixelForValue",
17941      value: function getPixelForValue(value) {
17942        var me = this;
17943        var offsets = me._offsets;
17944        var pos = me.getDecimalForValue(value);
17945        return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
17946      }
17947    }, {
17948      key: "getValueForPixel",
17949      value: function getValueForPixel(pixel) {
17950        var me = this;
17951        var offsets = me._offsets;
17952        var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
17953        return me.min + pos * (me.max - me.min);
17954      }
17955    }, {
17956      key: "_getLabelSize",
17957      value: function _getLabelSize(label) {
17958        var me = this;
17959        var ticksOpts = me.options.ticks;
17960        var tickLabelWidth = me.ctx.measureText(label).width;
17961        var angle = toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
17962        var cosRotation = Math.cos(angle);
17963        var sinRotation = Math.sin(angle);
17964
17965        var tickFontSize = me._resolveTickFontOptions(0).size;
17966
17967        return {
17968          w: tickLabelWidth * cosRotation + tickFontSize * sinRotation,
17969          h: tickLabelWidth * sinRotation + tickFontSize * cosRotation
17970        };
17971      }
17972    }, {
17973      key: "_getLabelCapacity",
17974      value: function _getLabelCapacity(exampleTime) {
17975        var me = this;
17976        var timeOpts = me.options.time;
17977        var displayFormats = timeOpts.displayFormats;
17978        var format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
17979
17980        var exampleLabel = me._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
17981
17982        var size = me._getLabelSize(exampleLabel);
17983
17984        var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h) - 1;
17985        return capacity > 0 ? capacity : 1;
17986      }
17987    }, {
17988      key: "getDataTimestamps",
17989      value: function getDataTimestamps() {
17990        var me = this;
17991        var timestamps = me._cache.data || [];
17992        var i, ilen;
17993
17994        if (timestamps.length) {
17995          return timestamps;
17996        }
17997
17998        var metas = me.getMatchingVisibleMetas();
17999
18000        if (me._normalized && metas.length) {
18001          return me._cache.data = metas[0].controller.getAllParsedValues(me);
18002        }
18003
18004        for (i = 0, ilen = metas.length; i < ilen; ++i) {
18005          timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(me));
18006        }
18007
18008        return me._cache.data = me.normalize(timestamps);
18009      }
18010    }, {
18011      key: "getLabelTimestamps",
18012      value: function getLabelTimestamps() {
18013        var me = this;
18014        var timestamps = me._cache.labels || [];
18015        var i, ilen;
18016
18017        if (timestamps.length) {
18018          return timestamps;
18019        }
18020
18021        var labels = me.getLabels();
18022
18023        for (i = 0, ilen = labels.length; i < ilen; ++i) {
18024          timestamps.push(_parse(me, labels[i]));
18025        }
18026
18027        return me._cache.labels = me._normalized ? timestamps : me.normalize(timestamps);
18028      }
18029    }, {
18030      key: "normalize",
18031      value: function normalize(values) {
18032        return _arrayUnique(values.sort(sorter));
18033      }
18034    }]);
18035
18036    return TimeScale;
18037  }(Scale);
18038
18039  TimeScale.id = 'time';
18040  TimeScale.defaults = {
18041    bounds: 'data',
18042    adapters: {},
18043    time: {
18044      parser: false,
18045      unit: false,
18046      round: false,
18047      isoWeekday: false,
18048      minUnit: 'millisecond',
18049      displayFormats: {}
18050    },
18051    ticks: {
18052      source: 'auto',
18053      major: {
18054        enabled: false
18055      }
18056    }
18057  };
18058
18059  function interpolate(table, val, reverse) {
18060    var lo = 0;
18061    var hi = table.length - 1;
18062    var prevSource, nextSource, prevTarget, nextTarget;
18063
18064    if (reverse) {
18065      if (val >= table[lo].pos && val <= table[hi].pos) {
18066        var _lookupByKey2 = _lookupByKey(table, 'pos', val);
18067
18068        lo = _lookupByKey2.lo;
18069        hi = _lookupByKey2.hi;
18070      }
18071
18072      var _table$lo = table[lo];
18073      prevSource = _table$lo.pos;
18074      prevTarget = _table$lo.time;
18075      var _table$hi = table[hi];
18076      nextSource = _table$hi.pos;
18077      nextTarget = _table$hi.time;
18078    } else {
18079      if (val >= table[lo].time && val <= table[hi].time) {
18080        var _lookupByKey3 = _lookupByKey(table, 'time', val);
18081
18082        lo = _lookupByKey3.lo;
18083        hi = _lookupByKey3.hi;
18084      }
18085
18086      var _table$lo2 = table[lo];
18087      prevSource = _table$lo2.time;
18088      prevTarget = _table$lo2.pos;
18089      var _table$hi2 = table[hi];
18090      nextSource = _table$hi2.time;
18091      nextTarget = _table$hi2.pos;
18092    }
18093
18094    var span = nextSource - prevSource;
18095    return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;
18096  }
18097
18098  var TimeSeriesScale = /*#__PURE__*/function (_TimeScale) {
18099    _inherits(TimeSeriesScale, _TimeScale);
18100
18101    var _super25 = _createSuper(TimeSeriesScale);
18102
18103    function TimeSeriesScale(props) {
18104      var _this19;
18105
18106      _classCallCheck(this, TimeSeriesScale);
18107
18108      _this19 = _super25.call(this, props);
18109      _this19._table = [];
18110      _this19._minPos = undefined;
18111      _this19._tableRange = undefined;
18112      return _this19;
18113    }
18114
18115    _createClass(TimeSeriesScale, [{
18116      key: "initOffsets",
18117      value: function initOffsets() {
18118        var me = this;
18119
18120        var timestamps = me._getTimestampsForTable();
18121
18122        var table = me._table = me.buildLookupTable(timestamps);
18123        me._minPos = interpolate(table, me.min);
18124        me._tableRange = interpolate(table, me.max) - me._minPos;
18125
18126        _get(_getPrototypeOf(TimeSeriesScale.prototype), "initOffsets", this).call(this, timestamps);
18127      }
18128    }, {
18129      key: "buildLookupTable",
18130      value: function buildLookupTable(timestamps) {
18131        var min = this.min,
18132            max = this.max;
18133        var items = [];
18134        var table = [];
18135        var i, ilen, prev, curr, next;
18136
18137        for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
18138          curr = timestamps[i];
18139
18140          if (curr >= min && curr <= max) {
18141            items.push(curr);
18142          }
18143        }
18144
18145        if (items.length < 2) {
18146          return [{
18147            time: min,
18148            pos: 0
18149          }, {
18150            time: max,
18151            pos: 1
18152          }];
18153        }
18154
18155        for (i = 0, ilen = items.length; i < ilen; ++i) {
18156          next = items[i + 1];
18157          prev = items[i - 1];
18158          curr = items[i];
18159
18160          if (Math.round((next + prev) / 2) !== curr) {
18161            table.push({
18162              time: curr,
18163              pos: i / (ilen - 1)
18164            });
18165          }
18166        }
18167
18168        return table;
18169      }
18170    }, {
18171      key: "_getTimestampsForTable",
18172      value: function _getTimestampsForTable() {
18173        var me = this;
18174        var timestamps = me._cache.all || [];
18175
18176        if (timestamps.length) {
18177          return timestamps;
18178        }
18179
18180        var data = me.getDataTimestamps();
18181        var label = me.getLabelTimestamps();
18182
18183        if (data.length && label.length) {
18184          timestamps = me.normalize(data.concat(label));
18185        } else {
18186          timestamps = data.length ? data : label;
18187        }
18188
18189        timestamps = me._cache.all = timestamps;
18190        return timestamps;
18191      }
18192    }, {
18193      key: "getDecimalForValue",
18194      value: function getDecimalForValue(value) {
18195        return (interpolate(this._table, value) - this._minPos) / this._tableRange;
18196      }
18197    }, {
18198      key: "getValueForPixel",
18199      value: function getValueForPixel(pixel) {
18200        var me = this;
18201        var offsets = me._offsets;
18202        var decimal = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
18203        return interpolate(me._table, decimal * me._tableRange + me._minPos, true);
18204      }
18205    }]);
18206
18207    return TimeSeriesScale;
18208  }(TimeScale);
18209
18210  TimeSeriesScale.id = 'timeseries';
18211  TimeSeriesScale.defaults = TimeScale.defaults;
18212  var scales = /*#__PURE__*/Object.freeze({
18213    __proto__: null,
18214    CategoryScale: CategoryScale,
18215    LinearScale: LinearScale,
18216    LogarithmicScale: LogarithmicScale,
18217    RadialLinearScale: RadialLinearScale,
18218    TimeScale: TimeScale,
18219    TimeSeriesScale: TimeSeriesScale
18220  });
18221  var registerables = [controllers, elements, plugins, scales];
18222
18223  Chart.register.apply(Chart, _toConsumableArray(registerables));
18224
18225  function toInteger(dirtyNumber) {
18226    if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
18227      return NaN;
18228    }
18229
18230    var number = Number(dirtyNumber);
18231
18232    if (isNaN(number)) {
18233      return number;
18234    }
18235
18236    return number < 0 ? Math.ceil(number) : Math.floor(number);
18237  }
18238
18239  function requiredArgs(required, args) {
18240    if (args.length < required) {
18241      throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
18242    }
18243  }
18244
18245  /**
18246   * @name toDate
18247   * @category Common Helpers
18248   * @summary Convert the given argument to an instance of Date.
18249   *
18250   * @description
18251   * Convert the given argument to an instance of Date.
18252   *
18253   * If the argument is an instance of Date, the function returns its clone.
18254   *
18255   * If the argument is a number, it is treated as a timestamp.
18256   *
18257   * If the argument is none of the above, the function returns Invalid Date.
18258   *
18259   * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
18260   *
18261   * @param {Date|Number} argument - the value to convert
18262   * @returns {Date} the parsed date in the local time zone
18263   * @throws {TypeError} 1 argument required
18264   *
18265   * @example
18266   * // Clone the date:
18267   * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
18268   * //=> Tue Feb 11 2014 11:30:30
18269   *
18270   * @example
18271   * // Convert the timestamp to date:
18272   * const result = toDate(1392098430000)
18273   * //=> Tue Feb 11 2014 11:30:30
18274   */
18275
18276  function toDate(argument) {
18277    requiredArgs(1, arguments);
18278    var argStr = Object.prototype.toString.call(argument); // Clone the date
18279
18280    if (argument instanceof Date || _typeof(argument) === 'object' && argStr === '[object Date]') {
18281      // Prevent the date to lose the milliseconds when passed to 
vendor: 5,863 bytes, lines 18281-18429
18281new Date() in IE10
18282      return new Date(argument.getTime());
18283    } else if (typeof argument === 'number' || argStr === '[object Number]') {
18284      return new Date(argument);
18285    } else {
18286      if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
18287        // eslint-disable-next-line no-console
18288        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://git.io/fjule"); // eslint-disable-next-line no-console
18289
18290        console.warn(new Error().stack);
18291      }
18292
18293      return new Date(NaN);
18294    }
18295  }
18296
18297  /**
18298   * @name addDays
18299   * @category Day Helpers
18300   * @summary Add the specified number of days to the given date.
18301   *
18302   * @description
18303   * Add the specified number of days to the given date.
18304   *
18305   * ### v2.0.0 breaking changes:
18306   *
18307   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18308   *
18309   * @param {Date|Number} date - the date to be changed
18310   * @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`.
18311   * @returns {Date} - the new date with the days added
18312   * @throws {TypeError} - 2 arguments required
18313   *
18314   * @example
18315   * // Add 10 days to 1 September 2014:
18316   * const result = addDays(new Date(2014, 8, 1), 10)
18317   * //=> Thu Sep 11 2014 00:00:00
18318   */
18319
18320  function addDays(dirtyDate, dirtyAmount) {
18321    requiredArgs(2, arguments);
18322    var date = toDate(dirtyDate);
18323    var amount = toInteger(dirtyAmount);
18324
18325    if (isNaN(amount)) {
18326      return new Date(NaN);
18327    }
18328
18329    if (!amount) {
18330      // If 0 days, no-op to avoid changing times in the hour before end of DST
18331      return date;
18332    }
18333
18334    date.setDate(date.getDate() + amount);
18335    return date;
18336  }
18337
18338  /**
18339   * @name addMonths
18340   * @category Month Helpers
18341   * @summary Add the specified number of months to the given date.
18342   *
18343   * @description
18344   * Add the specified number of months to the given date.
18345   *
18346   * ### v2.0.0 breaking changes:
18347   *
18348   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18349   *
18350   * @param {Date|Number} date - the date to be changed
18351   * @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`.
18352   * @returns {Date} the new date with the months added
18353   * @throws {TypeError} 2 arguments required
18354   *
18355   * @example
18356   * // Add 5 months to 1 September 2014:
18357   * const result = addMonths(new Date(2014, 8, 1), 5)
18358   * //=> Sun Feb 01 2015 00:00:00
18359   */
18360
18361  function addMonths(dirtyDate, dirtyAmount) {
18362    requiredArgs(2, arguments);
18363    var date = toDate(dirtyDate);
18364    var amount = toInteger(dirtyAmount);
18365
18366    if (isNaN(amount)) {
18367      return new Date(NaN);
18368    }
18369
18370    if (!amount) {
18371      // If 0 months, no-op to avoid changing times in the hour before end of DST
18372      return date;
18373    }
18374
18375    var dayOfMonth = date.getDate(); // The JS Date object supports date math by accepting out-of-bounds values for
18376    // month, day, etc. For example, new Date(2020, 0, 0) returns 31 Dec 2019 and
18377    // new Date(2020, 13, 1) returns 1 Feb 2021.  This is *almost* the behavior we
18378    // want except that dates will wrap around the end of a month, meaning that
18379    // new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So
18380    // we'll default to the end of the desired month by adding 1 to the desired
18381    // month and using a date of 0 to back up one day to the end of the desired
18382    // month.
18383
18384    var endOfDesiredMonth = new Date(date.getTime());
18385    endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0);
18386    var daysInMonth = endOfDesiredMonth.getDate();
18387
18388    if (dayOfMonth >= daysInMonth) {
18389      // If we're already at the end of the month, then this is the correct date
18390      // and we're done.
18391      return endOfDesiredMonth;
18392    } else {
18393      // Otherwise, we now know that setting the original day-of-month value won't
18394      // cause an overflow, so set the desired day-of-month. Note that we can't
18395      // just set the date of `endOfDesiredMonth` because that object may have had
18396      // its time changed in the unusual case where where a DST transition was on
18397      // the last day of the month and its local time was in the hour skipped or
18398      // repeated next to a DST transition.  So we use `date` instead which is
18399      // guaranteed to still have the original time.
18400      date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth);
18401      return date;
18402    }
18403  }
18404
18405  /**
18406   * @name addMilliseconds
18407   * @category Millisecond Helpers
18408   * @summary Add the specified number of milliseconds to the given date.
18409   *
18410   * @description
18411   * Add the specified number of milliseconds to the given date.
18412   *
18413   * ### v2.0.0 breaking changes:
18414   *
18415   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18416   *
18417   * @param {Date|Number} date - the date to be changed
18418   * @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`.
18419   * @returns {Date} the new date with the milliseconds added
18420   * @throws {TypeError} 2 arguments required
18421   *
18422   * @example
18423   * // Add 750 milliseconds to 10 July 2014 12:45:30.000:
18424   * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
18425   * //=> Thu Jul 10 2014 12:45:30.750
18426   */
18427
18428  function addMilliseconds(dirtyDate, dirtyAmount) {
18429    requiredArgs(2, arguments);
vendor: 10,597 bytes, lines 18430-18701
18430    var timestamp = toDate(dirtyDate).getTime();
18431    var amount = toInteger(dirtyAmount);
18432    return new Date(timestamp + amount);
18433  }
18434
18435  var MILLISECONDS_IN_HOUR$3 = 3600000;
18436  /**
18437   * @name addHours
18438   * @category Hour Helpers
18439   * @summary Add the specified number of hours to the given date.
18440   *
18441   * @description
18442   * Add the specified number of hours to the given date.
18443   *
18444   * ### v2.0.0 breaking changes:
18445   *
18446   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18447   *
18448   * @param {Date|Number} date - the date to be changed
18449   * @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`.
18450   * @returns {Date} the new date with the hours added
18451   * @throws {TypeError} 2 arguments required
18452   *
18453   * @example
18454   * // Add 2 hours to 10 July 2014 23:00:00:
18455   * const result = addHours(new Date(2014, 6, 10, 23, 0), 2)
18456   * //=> Fri Jul 11 2014 01:00:00
18457   */
18458
18459  function addHours(dirtyDate, dirtyAmount) {
18460    requiredArgs(2, arguments);
18461    var amount = toInteger(dirtyAmount);
18462    return addMilliseconds(dirtyDate, amount * MILLISECONDS_IN_HOUR$3);
18463  }
18464
18465  /**
18466   * @name startOfWeek
18467   * @category Week Helpers
18468   * @summary Return the start of a week for the given date.
18469   *
18470   * @description
18471   * Return the start of a week for the given date.
18472   * The result will be in the local timezone.
18473   *
18474   * ### v2.0.0 breaking changes:
18475   *
18476   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18477   *
18478   * @param {Date|Number} date - the original date
18479   * @param {Object} [options] - an object with options.
18480   * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
18481   * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
18482   * @returns {Date} the start of a week
18483   * @throws {TypeError} 1 argument required
18484   * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
18485   *
18486   * @example
18487   * // The start of a week for 2 September 2014 11:55:00:
18488   * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))
18489   * //=> Sun Aug 31 2014 00:00:00
18490   *
18491   * @example
18492   * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:
18493   * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
18494   * //=> Mon Sep 01 2014 00:00:00
18495   */
18496
18497  function startOfWeek(dirtyDate, dirtyOptions) {
18498    requiredArgs(1, arguments);
18499    var options = dirtyOptions || {};
18500    var locale = options.locale;
18501    var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
18502    var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
18503    var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
18504
18505    if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
18506      throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
18507    }
18508
18509    var date = toDate(dirtyDate);
18510    var day = date.getDay();
18511    var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
18512    date.setDate(date.getDate() - diff);
18513    date.setHours(0, 0, 0, 0);
18514    return date;
18515  }
18516
18517  /**
18518   * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
18519   * They usually appear for dates that denote time before the timezones were introduced
18520   * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
18521   * and GMT+01:00:00 after that date)
18522   *
18523   * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
18524   * which would lead to incorrect calculations.
18525   *
18526   * This function returns the timezone offset in milliseconds that takes seconds in account.
18527   */
18528  function getTimezoneOffsetInMilliseconds(date) {
18529    var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
18530    utcDate.setUTCFullYear(date.getFullYear());
18531    return date.getTime() - utcDate.getTime();
18532  }
18533
18534  /**
18535   * @name startOfDay
18536   * @category Day Helpers
18537   * @summary Return the start of a day for the given date.
18538   *
18539   * @description
18540   * Return the start of a day for the given date.
18541   * The result will be in the local timezone.
18542   *
18543   * ### v2.0.0 breaking changes:
18544   *
18545   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18546   *
18547   * @param {Date|Number} date - the original date
18548   * @returns {Date} the start of a day
18549   * @throws {TypeError} 1 argument required
18550   *
18551   * @example
18552   * // The start of a day for 2 September 2014 11:55:00:
18553   * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))
18554   * //=> Tue Sep 02 2014 00:00:00
18555   */
18556
18557  function startOfDay(dirtyDate) {
18558    requiredArgs(1, arguments);
18559    var date = toDate(dirtyDate);
18560    date.setHours(0, 0, 0, 0);
18561    return date;
18562  }
18563
18564  var MILLISECONDS_IN_DAY$1 = 86400000;
18565  /**
18566   * @name differenceInCalendarDays
18567   * @category Day Helpers
18568   * @summary Get the number of calendar days between the given dates.
18569   *
18570   * @description
18571   * Get the number of calendar days between the given dates. This means that the times are removed
18572   * from the dates and then the difference in days is calculated.
18573   *
18574   * ### v2.0.0 breaking changes:
18575   *
18576   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18577   *
18578   * @param {Date|Number} dateLeft - the later date
18579   * @param {Date|Number} dateRight - the earlier date
18580   * @returns {Number} the number of calendar days
18581   * @throws {TypeError} 2 arguments required
18582   *
18583   * @example
18584   * // How many calendar days are between
18585   * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
18586   * var result = differenceInCalendarDays(
18587   *   new Date(2012, 6, 2, 0, 0),
18588   *   new Date(2011, 6, 2, 23, 0)
18589   * )
18590   * //=> 366
18591   * // How many calendar days are between
18592   * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
18593   * var result = differenceInCalendarDays(
18594   *   new Date(2011, 6, 3, 0, 1),
18595   *   new Date(2011, 6, 2, 23, 59)
18596   * )
18597   * //=> 1
18598   */
18599
18600  function differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) {
18601    requiredArgs(2, arguments);
18602    var startOfDayLeft = startOfDay(dirtyDateLeft);
18603    var startOfDayRight = startOfDay(dirtyDateRight);
18604    var timestampLeft = startOfDayLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfDayLeft);
18605    var timestampRight = startOfDayRight.getTime() - getTimezoneOffsetInMilliseconds(startOfDayRight); // Round the number of days to the nearest integer
18606    // because the number of milliseconds in a day is not constant
18607    // (e.g. it's different in the day of the daylight saving time clock shift)
18608
18609    return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY$1);
18610  }
18611
18612  var MILLISECONDS_IN_MINUTE$3 = 60000;
18613  /**
18614   * @name addMinutes
18615   * @category Minute Helpers
18616   * @summary Add the specified number of minutes to the given date.
18617   *
18618   * @description
18619   * Add the specified number of minutes to the given date.
18620   *
18621   * ### v2.0.0 breaking changes:
18622   *
18623   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18624   *
18625   * @param {Date|Number} date - the date to be changed
18626   * @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`.
18627   * @returns {Date} the new date with the minutes added
18628   * @throws {TypeError} 2 arguments required
18629   *
18630   * @example
18631   * // Add 30 minutes to 10 July 2014 12:00:00:
18632   * const result = addMinutes(new Date(2014, 6, 10, 12, 0), 30)
18633   * //=> Thu Jul 10 2014 12:30:00
18634   */
18635
18636  function addMinutes(dirtyDate, dirtyAmount) {
18637    requiredArgs(2, arguments);
18638    var amount = toInteger(dirtyAmount);
18639    return addMilliseconds(dirtyDate, amount * MILLISECONDS_IN_MINUTE$3);
18640  }
18641
18642  /**
18643   * @name addQuarters
18644   * @category Quarter Helpers
18645   * @summary Add the specified number of year quarters to the given date.
18646   *
18647   * @description
18648   * Add the specified number of year quarters to the given date.
18649   *
18650   * ### v2.0.0 breaking changes:
18651   *
18652   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18653   *
18654   * @param {Date|Number} date - the date to be changed
18655   * @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`.
18656   * @returns {Date} the new date with the quarters added
18657   * @throws {TypeError} 2 arguments required
18658   *
18659   * @example
18660   * // Add 1 quarter to 1 September 2014:
18661   * const result = addQuarters(new Date(2014, 8, 1), 1)
18662   * //=> Mon Dec 01 2014 00:00:00
18663   */
18664
18665  function addQuarters(dirtyDate, dirtyAmount) {
18666    requiredArgs(2, arguments);
18667    var amount = toInteger(dirtyAmount);
18668    var months = amount * 3;
18669    return addMonths(dirtyDate, months);
18670  }
18671
18672  /**
18673   * @name addSeconds
18674   * @category Second Helpers
18675   * @summary Add the specified number of seconds to the given date.
18676   *
18677   * @description
18678   * Add the specified number of seconds to the given date.
18679   *
18680   * ### v2.0.0 breaking changes:
18681   *
18682   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18683   *
18684   * @param {Date|Number} date - the date to be changed
18685   * @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`.
18686   * @returns {Date} the new date with the seconds added
18687   * @throws {TypeError} 2 arguments required
18688   *
18689   * @example
18690   * // Add 30 seconds to 10 July 2014 12:45:00:
18691   * const result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30)
18692   * //=> Thu Jul 10 2014 12:45:30
18693   */
18694
18695  function addSeconds(dirtyDate, dirtyAmount) {
18696    requiredArgs(2, arguments);
18697    var amount = toInteger(dirtyAmount);
18698    return addMilliseconds(dirtyDate, amount * 1000);
18699  }
18700
18701  /**
18702   * @name addWeeks
18703   * @category Week Helpers
18704   * @summary Add the specified number of weeks to the given date.
18705   *
18706   * @description
18707   * Add the specified number of week to the given date.
18708   *
18709   * ### v2.0.0 breaking changes:
18710   *
18711   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18712   *
18713   * @param {Date|Number} date - the date to be changed
18714   * @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`.
18715   * @returns {Date} the new date with the weeks added
18716   * @throws {TypeError} 2 arguments required
18717   *
18718   * @example
18719   * // Add 4 weeks to 1 September 2014:
18720   * const result = addWeeks(new Date(2014, 8, 1), 4)
18721   * //=> Mon Sep 29 2014 00:00:00
18722   */
18723
18724  function addWeeks(dirtyDate, dirtyAmount) {
18725    requiredArgs(2, arguments);
18726    var amount = toInteger(dirtyAmount);
18727    var days = amount * 7;
18728    return addDays(dirtyDate, days);
18729  }
18730
18731  /**
18732   * @name addYears
18733   * @category Year Helpers
18734   * @summary Add the specified number of years to the given date.
18735   *
18736   * @description
18737   * Add the specified number of years to the given date.
18738   *
18739   * ### v2.0.0 breaking changes:
18740   *
18741   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18742   *
18743   * @param {Date|Number} date - the date to be changed
18744   * @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`.
18745   * @returns {Date} the new date with the years added
18746   * @throws {TypeError} 2 arguments required
18747   *
18748   * @example
18749   * // Add 5 years to 1 September 2014:
18750   * const result = addYears(new Date(2014, 8, 1), 5)
18751   * //=> Sun Sep 01 2019 00:00:00
18752   */
18753
18754  function addYears(dirtyDate, dirtyAmount) {
18755    requiredArgs(2, arguments);
18756    var amount = toInteger(dirtyAmount);
18757    return addMonths(dirtyDate, amount * 12);
18758  }
18759
18760  /**
18761   * @name compareAsc
18762   * @category Common Helpers
18763   * @summary Compare the two dates and return -1, 0 or 1.
18764   *
18765   * @description
18766   * Compare the two dates and return 1 if the first date is after the second,
18767   * -1 if the first date is before the second or 0 if dates are equal.
18768   *
18769   * ### v2.0.0 breaking changes:
18770   *
18771   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18772   *
18773   * @param {Date|Number} dateLeft - the first date to compare
18774   * @param {Date|Number} dateRight - the second date to compare
18775   * @returns {Number} the result of the comparison
18776   * @throws {TypeError} 2 arguments required
18777   *
18778   * @example
18779   * // Compare 11 February 1987 and 10 July 1989:
18780   * const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))
18781   * //=> -1
18782   *
18783   * @example
18784   * // Sort the array of dates:
18785   * const result = [
18786   *   new Date(1995, 6, 2),
18787   *   new Date(1987, 1, 11),
18788   *   new Date(1989, 6, 10)
18789   * ].sort(compareAsc)
18790   * //=> [
18791   * //   Wed Feb 11 1987 00:00:00,
18792   * //   Mon Jul 10 1989 00:00:00,
18793   * //   Sun Jul 02 1995 00:00:00
18794   * // ]
18795   */
18796
18797  function compareAsc(dirtyDateLeft, dirtyDateRight) {
18798    requiredArgs(2, arguments);
18799    var dateLeft = toDate(dirtyDateLeft);
18800    var dateRight = toDate(dirtyDateRight);
18801    var diff = dateLeft.getTime() - dateRight.getTime();
18802
18803    if (diff < 0) {
18804      return -1;
18805    } else if (diff > 0) {
18806      return 1; // Return 0 if diff is 0; return NaN if diff is NaN
18807    } else {
18808      return diff;
18809    }
18810  }
18811
18812  /**
18813   * @name isValid
18814   * @category Common Helpers
18815   * @summary Is the given date valid?
18816   *
18817   * @description
18818   * Returns false if argument is Invalid Date and true otherwise.
18819   * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
18820   * Invalid Date is a Date, whose time value is NaN.
18821   *
18822   * Time value of Date: http://es5.github.io/#x15.9.1.1
18823   *
18824   * ### v2.0.0 breaking changes:
18825   *
18826   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18827   *
18828   * - Now `isValid` doesn't throw an exception
18829   *   if the first argument is not an instance of Date.
18830   *   Instead, argument is converted beforehand using `toDate`.
18831   *
18832   *   Examples:
18833   *
18834   *   | `isValid` argument        | Before v2.0.0 | v2.0.0 onward |
18835   *   |---------------------------|---------------|---------------|
18836   *   | `new Date()`              | `true`        | `true`        |
18837   *   | `new Date('2016-01-01')`  | `true`        | `true`        |
18838   *   | `new Date('')`            | `false`       | `false`       |
18839   *   | `new Date(1488370835081)` | `true`        | `true`        |
18840   *   | `new Date(NaN)`           | `false`       | `false`       |
18841   *   | `'2016-01-01'`            | `TypeError`   | `false`       |
18842   *   | `''`                      | `TypeError`   | `false`       |
18843   *   | `1488370835081`           | `TypeError`   | `true`        |
18844   *   | `NaN`                     | `TypeError`   | `false`       |
18845   *
18846   *   We introduce this change to make *date-fns* consistent with ECMAScript behavior
18847   *   that try to coerce arguments to the expected type
18848   *   (which is also the case with other *date-fns* functions).
18849   *
18850   * @param {*} date - the date to check
18851   * @returns {Boolean} the date is valid
18852   * @throws {TypeError} 1 argument required
18853   *
18854   * @example
18855   * // For the valid date:
18856   * var result = isValid(new Date(2014, 1, 31))
18857   * //=> true
18858   *
18859   * @example
18860   * // For the value, convertable into a date:
18861   * var result = isValid(1393804800000)
18862   * //=> true
18863   *
18864   * @example
18865   * // For the invalid date:
18866   * var result = isValid(new Date(''))
18867   * //=> false
18868   */
18869
18870  function isValid(dirtyDate) {
18871    requiredArgs(1, arguments);
vendor: 14,085 bytes, lines 18872-19271
18872    var date = toDate(dirtyDate);
18873    return !isNaN(date);
18874  }
18875
18876  /**
18877   * @name differenceInCalendarMonths
18878   * @category Month Helpers
18879   * @summary Get the number of calendar months between the given dates.
18880   *
18881   * @description
18882   * Get the number of calendar months between the given dates.
18883   *
18884   * ### v2.0.0 breaking changes:
18885   *
18886   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18887   *
18888   * @param {Date|Number} dateLeft - the later date
18889   * @param {Date|Number} dateRight - the earlier date
18890   * @returns {Number} the number of calendar months
18891   * @throws {TypeError} 2 arguments required
18892   *
18893   * @example
18894   * // How many calendar months are between 31 January 2014 and 1 September 2014?
18895   * var result = differenceInCalendarMonths(
18896   *   new Date(2014, 8, 1),
18897   *   new Date(2014, 0, 31)
18898   * )
18899   * //=> 8
18900   */
18901
18902  function differenceInCalendarMonths(dirtyDateLeft, dirtyDateRight) {
18903    requiredArgs(2, arguments);
18904    var dateLeft = toDate(dirtyDateLeft);
18905    var dateRight = toDate(dirtyDateRight);
18906    var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear();
18907    var monthDiff = dateLeft.getMonth() - dateRight.getMonth();
18908    return yearDiff * 12 + monthDiff;
18909  }
18910
18911  /**
18912   * @name differenceInCalendarYears
18913   * @category Year Helpers
18914   * @summary Get the number of calendar years between the given dates.
18915   *
18916   * @description
18917   * Get the number of calendar years between the given dates.
18918   *
18919   * ### v2.0.0 breaking changes:
18920   *
18921   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18922   *
18923   * @param {Date|Number} dateLeft - the later date
18924   * @param {Date|Number} dateRight - the earlier date
18925   * @returns {Number} the number of calendar years
18926   * @throws {TypeError} 2 arguments required
18927   *
18928   * @example
18929   * // How many calendar years are between 31 December 2013 and 11 February 2015?
18930   * var result = differenceInCalendarYears(
18931   *   new Date(2015, 1, 11),
18932   *   new Date(2013, 11, 31)
18933   * )
18934   * //=> 2
18935   */
18936
18937  function differenceInCalendarYears(dirtyDateLeft, dirtyDateRight) {
18938    requiredArgs(2, arguments);
18939    var dateLeft = toDate(dirtyDateLeft);
18940    var dateRight = toDate(dirtyDateRight);
18941    return dateLeft.getFullYear() - dateRight.getFullYear();
18942  }
18943
18944  // for accurate equality comparisons of UTC timestamps that end up
18945  // having the same representation in local time, e.g. one hour before
18946  // DST ends vs. the instant that DST ends.
18947
18948  function compareLocalAsc(dateLeft, dateRight) {
18949    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();
18950
18951    if (diff < 0) {
18952      return -1;
18953    } else if (diff > 0) {
18954      return 1; // Return 0 if diff is 0; return NaN if diff is NaN
18955    } else {
18956      return diff;
18957    }
18958  }
18959  /**
18960   * @name differenceInDays
18961   * @category Day Helpers
18962   * @summary Get the number of full days between the given dates.
18963   *
18964   * @description
18965   * Get the number of full day periods between two dates. Fractional days are
18966   * truncated towards zero.
18967   *
18968   * One "full day" is the distance between a local time in one day to the same
18969   * local time on the next or previous day. A full day can sometimes be less than
18970   * or more than 24 hours if a daylight savings change happens between two dates.
18971   *
18972   * To ignore DST and only measure exact 24-hour periods, use this instead:
18973   * `Math.floor(differenceInHours(dateLeft, dateRight)/24)|0`.
18974   *
18975   *
18976   * ### v2.0.0 breaking changes:
18977   *
18978   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
18979   *
18980   * @param {Date|Number} dateLeft - the later date
18981   * @param {Date|Number} dateRight - the earlier date
18982   * @returns {Number} the number of full days according to the local timezone
18983   * @throws {TypeError} 2 arguments required
18984   *
18985   * @example
18986   * // How many full days are between
18987   * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
18988   * var result = differenceInDays(
18989   *   new Date(2012, 6, 2, 0, 0),
18990   *   new Date(2011, 6, 2, 23, 0)
18991   * )
18992   * //=> 365
18993   * // How many full days are between
18994   * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
18995   * var result = differenceInDays(
18996   *   new Date(2011, 6, 3, 0, 1),
18997   *   new Date(2011, 6, 2, 23, 59)
18998   * )
18999   * //=> 0
19000   * // How many full days are between
19001   * // 1 March 2020 0:00 and 1 June 2020 0:00 ?
19002   * // Note: because local time is used, the
19003   * // result will always be 92 days, even in
19004   * // time zones where DST starts and the
19005   * // period has only 92*24-1 hours.
19006   * var result = differenceInDays(
19007   *   new Date(2020, 5, 1),
19008   *   new Date(2020, 2, 1)
19009   * )
19010  //=> 92
19011   */
19012
19013
19014  function differenceInDays(dirtyDateLeft, dirtyDateRight) {
19015    requiredArgs(2, arguments);
19016    var dateLeft = toDate(dirtyDateLeft);
19017    var dateRight = toDate(dirtyDateRight);
19018    var sign = compareLocalAsc(dateLeft, dateRight);
19019    var difference = Math.abs(differenceInCalendarDays(dateLeft, dateRight));
19020    dateLeft.setDate(dateLeft.getDate() - sign * difference); // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full
19021    // If so, result must be decreased by 1 in absolute value
19022
19023    var isLastDayNotFull = compareLocalAsc(dateLeft, dateRight) === -sign;
19024    var result = sign * (difference - isLastDayNotFull); // Prevent negative zero
19025
19026    return result === 0 ? 0 : result;
19027  }
19028
19029  /**
19030   * @name differenceInMilliseconds
19031   * @category Millisecond Helpers
19032   * @summary Get the number of milliseconds between the given dates.
19033   *
19034   * @description
19035   * Get the number of milliseconds between the given dates.
19036   *
19037   * ### v2.0.0 breaking changes:
19038   *
19039   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19040   *
19041   * @param {Date|Number} dateLeft - the later date
19042   * @param {Date|Number} dateRight - the earlier date
19043   * @returns {Number} the number of milliseconds
19044   * @throws {TypeError} 2 arguments required
19045   *
19046   * @example
19047   * // How many milliseconds are between
19048   * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700?
19049   * var result = differenceInMilliseconds(
19050   *   new Date(2014, 6, 2, 12, 30, 21, 700),
19051   *   new Date(2014, 6, 2, 12, 30, 20, 600)
19052   * )
19053   * //=> 1100
19054   */
19055
19056  function differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) {
19057    requiredArgs(2, arguments);
19058    var dateLeft = toDate(dirtyDateLeft);
19059    var dateRight = toDate(dirtyDateRight);
19060    return dateLeft.getTime() - dateRight.getTime();
19061  }
19062
19063  var MILLISECONDS_IN_HOUR$2 = 3600000;
19064  /**
19065   * @name differenceInHours
19066   * @category Hour Helpers
19067   * @summary Get the number of hours between the given dates.
19068   *
19069   * @description
19070   * Get the number of hours between the given dates.
19071   *
19072   * ### v2.0.0 breaking changes:
19073   *
19074   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19075   *
19076   * @param {Date|Number} dateLeft - the later date
19077   * @param {Date|Number} dateRight - the earlier date
19078   * @returns {Number} the number of hours
19079   * @throws {TypeError} 2 arguments required
19080   *
19081   * @example
19082   * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00?
19083   * var result = differenceInHours(
19084   *   new Date(2014, 6, 2, 19, 0),
19085   *   new Date(2014, 6, 2, 6, 50)
19086   * )
19087   * //=> 12
19088   */
19089
19090  function differenceInHours(dirtyDateLeft, dirtyDateRight) {
19091    requiredArgs(2, arguments);
19092    var diff = differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_HOUR$2;
19093    return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
19094  }
19095
19096  var MILLISECONDS_IN_MINUTE$2 = 60000;
19097  /**
19098   * @name differenceInMinutes
19099   * @category Minute Helpers
19100   * @summary Get the number of minutes between the given dates.
19101   *
19102   * @description
19103   * Get the signed number of full (rounded towards 0) minutes between the given dates.
19104   *
19105   * ### v2.0.0 breaking changes:
19106   *
19107   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19108   *
19109   * @param {Date|Number} dateLeft - the later date
19110   * @param {Date|Number} dateRight - the earlier date
19111   * @returns {Number} the number of minutes
19112   * @throws {TypeError} 2 arguments required
19113   *
19114   * @example
19115   * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
19116   * var result = differenceInMinutes(
19117   *   new Date(2014, 6, 2, 12, 20, 0),
19118   *   new Date(2014, 6, 2, 12, 7, 59)
19119   * )
19120   * //=> 12
19121   *
19122   * @example
19123   * // How many minutes are from 10:01:59 to 10:00:00
19124   * var result = differenceInMinutes(
19125   *   new Date(2000, 0, 1, 10, 0, 0),
19126   *   new Date(2000, 0, 1, 10, 1, 59)
19127   * )
19128   * //=> -1
19129   */
19130
19131  function differenceInMinutes(dirtyDateLeft, dirtyDateRight) {
19132    requiredArgs(2, arguments);
19133    var diff = differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_MINUTE$2;
19134    return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
19135  }
19136
19137  /**
19138   * @name endOfDay
19139   * @category Day Helpers
19140   * @summary Return the end of a day for the given date.
19141   *
19142   * @description
19143   * Return the end of a day for the given date.
19144   * The result will be in the local timezone.
19145   *
19146   * ### v2.0.0 breaking changes:
19147   *
19148   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19149   *
19150   * @param {Date|Number} date - the original date
19151   * @returns {Date} the end of a day
19152   * @throws {TypeError} 1 argument required
19153   *
19154   * @example
19155   * // The end of a day for 2 September 2014 11:55:00:
19156   * const result = endOfDay(new Date(2014, 8, 2, 11, 55, 0))
19157   * //=> Tue Sep 02 2014 23:59:59.999
19158   */
19159
19160  function endOfDay(dirtyDate) {
19161    requiredArgs(1, arguments);
19162    var date = toDate(dirtyDate);
19163    date.setHours(23, 59, 59, 999);
19164    return date;
19165  }
19166
19167  /**
19168   * @name endOfMonth
19169   * @category Month Helpers
19170   * @summary Return the end of a month for the given date.
19171   *
19172   * @description
19173   * Return the end of a month for the given date.
19174   * The result will be in the local timezone.
19175   *
19176   * ### v2.0.0 breaking changes:
19177   *
19178   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19179   *
19180   * @param {Date|Number} date - the original date
19181   * @returns {Date} the end of a month
19182   * @throws {TypeError} 1 argument required
19183   *
19184   * @example
19185   * // The end of a month for 2 September 2014 11:55:00:
19186   * const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0))
19187   * //=> Tue Sep 30 2014 23:59:59.999
19188   */
19189
19190  function endOfMonth(dirtyDate) {
19191    requiredArgs(1, arguments);
19192    var date = toDate(dirtyDate);
19193    var month = date.getMonth();
19194    date.setFullYear(date.getFullYear(), month + 1, 0);
19195    date.setHours(23, 59, 59, 999);
19196    return date;
19197  }
19198
19199  /**
19200   * @name isLastDayOfMonth
19201   * @category Month Helpers
19202   * @summary Is the given date the last day of a month?
19203   *
19204   * @description
19205   * Is the given date the last day of a month?
19206   *
19207   * ### v2.0.0 breaking changes:
19208   *
19209   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19210   *
19211   * @param {Date|Number} date - the date to check
19212   * @returns {Boolean} the date is the last day of a month
19213   * @throws {TypeError} 1 argument required
19214   *
19215   * @example
19216   * // Is 28 February 2014 the last day of a month?
19217   * var result = isLastDayOfMonth(new Date(2014, 1, 28))
19218   * //=> true
19219   */
19220
19221  function isLastDayOfMonth(dirtyDate) {
19222    requiredArgs(1, arguments);
19223    var date = toDate(dirtyDate);
19224    return endOfDay(date).getTime() === endOfMonth(date).getTime();
19225  }
19226
19227  /**
19228   * @name differenceInMonths
19229   * @category Month Helpers
19230   * @summary Get the number of full months between the given dates.
19231   *
19232   * @description
19233   * Get the number of full months between the given dates.
19234   *
19235   * ### v2.0.0 breaking changes:
19236   *
19237   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19238   *
19239   * @param {Date|Number} dateLeft - the later date
19240   * @param {Date|Number} dateRight - the earlier date
19241   * @returns {Number} the number of full months
19242   * @throws {TypeError} 2 arguments required
19243   *
19244   * @example
19245   * // How many full months are between 31 January 2014 and 1 September 2014?
19246   * var result = differenceInMonths(new Date(2014, 8, 1), new Date(2014, 0, 31))
19247   * //=> 7
19248   */
19249
19250  function differenceInMonths(dirtyDateLeft, dirtyDateRight) {
19251    requiredArgs(2, arguments);
19252    var dateLeft = toDate(dirtyDateLeft);
19253    var dateRight = toDate(dirtyDateRight);
19254    var sign = compareAsc(dateLeft, dateRight);
19255    var difference = Math.abs(differenceInCalendarMonths(dateLeft, dateRight));
19256    var result; // Check for the difference of less than month
19257
19258    if (difference < 1) {
19259      result = 0;
19260    } else {
19261      if (dateLeft.getMonth() === 1 && dateLeft.getDate() > 27) {
19262        // This will check if the date is end of Feb and assign a higher end of month date
19263        // to compare it with Jan
19264        dateLeft.setDate(30);
19265      }
19266
19267      dateLeft.setMonth(dateLeft.getMonth() - sign * difference); // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full
19268      // If so, result must be decreased by 1 in absolute value
19269
19270      var isLastMonthNotFull = compareAsc(dateLeft, dateRight) === -sign; // Check for cases of one full calendar month
19271
19272      if (isLastDayOfMonth(toDate(dirtyDateLeft)) && difference === 1 && compareAsc(dirtyDateLeft, dateRight) === 1) {
19273        isLastMonthNotFull = false;
19274      }
19275
19276      result = sign * (difference - isLastMonthNotFull);
19277    } // Prevent negative zero
19278
19279
19280    return result === 0 ? 0 : result;
19281  }
19282
19283  /**
19284   * @name differenceInQuarters
19285   * @category Quarter Helpers
19286   * @summary Get the number of full quarters between the given dates.
19287   *
19288   * @description
19289   * Get the number of full quarters between the given dates.
19290   *
19291   * ### v2.0.0 breaking changes:
19292   *
19293   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19294   *
19295   * @param {Date|Number} dateLeft - the later date
19296   * @param {Date|Number} dateRight - the earlier date
19297   * @returns {Number} the number of full quarters
19298   * @throws {TypeError} 2 arguments required
19299   *
19300   * @example
19301   * // How many full quarters are between 31 December 2013 and 2 July 2014?
19302   * var result = differenceInQuarters(new Date(2014, 6, 2), new Date(2013, 11, 31))
19303   * //=> 2
19304   */
19305
19306  function differenceInQuarters(dirtyDateLeft, dirtyDateRight) {
19307    requiredArgs(2, arguments);
19308    var diff = differenceInMonths(dirtyDateLeft, dirtyDateRight) / 3;
19309    return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
19310  }
19311
19312  /**
19313   * @name differenceInSeconds
19314   * @category Second Helpers
19315   * @summary Get the number of seconds between the given dates.
19316   *
19317   * @description
19318   * Get the number of seconds between the given dates.
19319   *
19320   * ### v2.0.0 breaking changes:
19321   *
19322   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19323   *
19324   * @param {Date|Number} dateLeft - the later date
19325   * @param {Date|Number} dateRight - the earlier date
19326   * @returns {Number} the number of seconds
19327   * @throws {TypeError} 2 arguments required
19328   *
19329   * @example
19330   * // How many seconds are between
19331   * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000?
19332   * var result = differenceInSeconds(
19333   *   new Date(2014, 6, 2, 12, 30, 20, 0),
19334   *   new Date(2014, 6, 2, 12, 30, 7, 999)
19335   * )
19336   * //=> 12
19337   */
19338
19339  function differenceInSeconds(dirtyDateLeft, dirtyDateRight) {
19340    requiredArgs(2, arguments);
19341    var diff = differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) / 1000;
19342    return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
19343  }
19344
19345  /**
19346   * @name differenceInWeeks
19347   * @category Week Helpers
19348   * @summary Get the number of full weeks between the given dates.
19349   *
19350   * @description
19351   * Get the number of full weeks between two dates. Fractional weeks are
19352   * truncated towards zero.
19353   *
19354   * One "full week" is the distance between a local time in one day to the same
19355   * local time 7 days earlier or later. A full week can sometimes be less than
19356   * or more than 7*24 hours if a daylight savings change happens between two dates.
19357   *
19358   * To ignore DST and only measure exact 7*24-hour periods, use this instead:
19359   * `Math.floor(differenceInHours(dateLeft, dateRight)/(7*24))|0`.
19360   *
19361   *
19362   * ### v2.0.0 breaking changes:
19363   *
19364   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19365   *
19366   * @param {Date|Number} dateLeft - the later date
19367   * @param {Date|Number} dateRight - the earlier date
19368   * @returns {Number} the number of full weeks
19369   * @throws {TypeError} 2 arguments required
19370   *
19371   * @example
19372   * // How many full weeks are between 5 July 2014 and 20 July 2014?
19373   * var result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5))
19374   * //=> 2
19375   *
19376   * // How many full weeks are between
19377   * // 1 March 2020 0:00 and 6 June 2020 0:00 ?
19378   * // Note: because local time is used, the
19379   * // result will always be 8 weeks (54 days),
19380   * // even if DST starts and the period has
19381   * // only 54*24-1 hours.
19382   * var result = differenceInWeeks(
19383   *   new Date(2020, 5, 1),
19384   *   new Date(2020, 2, 6)
19385   * )
19386   * //=> 8
19387   */
19388
19389  function differenceInWeeks(dirtyDateLeft, dirtyDateRight) {
19390    requiredArgs(2, arguments);
19391    var diff = differenceInDays(dirtyDateLeft, dirtyDateRight) / 7;
19392    return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
19393  }
19394
19395  /**
19396   * @name differenceInYears
19397   * @category Year Helpers
19398   * @summary Get the number of full years between the given dates.
19399   *
19400   * @description
19401   * Get the number of full years between the given dates.
19402   *
19403   * ### v2.0.0 breaking changes:
19404   *
19405   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19406   *
19407   * @param {Date|Number} dateLeft - the later date
19408   * @param {Date|Number} dateRight - the earlier date
19409   * @returns {Number} the number of full years
19410   * @throws {TypeError} 2 arguments required
19411   *
19412   * @example
19413   * // How many full years are between 31 December 2013 and 11 February 2015?
19414   * var result = differenceInYears(new Date(2015, 1, 11), new Date(2013, 11, 31))
19415   * //=> 1
19416   */
19417
19418  function differenceInYears(dirtyDateLeft, dirtyDateRight) {
19419    requiredArgs(2, arguments);
vendor: 13,965 bytes, lines 19420-19867
19420    var dateLeft = toDate(dirtyDateLeft);
19421    var dateRight = toDate(dirtyDateRight);
19422    var sign = compareAsc(dateLeft, dateRight);
19423    var difference = Math.abs(differenceInCalendarYears(dateLeft, dateRight)); // Set both dates to a valid leap year for accurate comparison when dealing
19424    // with leap days
19425
19426    dateLeft.setFullYear('1584');
19427    dateRight.setFullYear('1584'); // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full
19428    // If so, result must be decreased by 1 in absolute value
19429
19430    var isLastYearNotFull = compareAsc(dateLeft, dateRight) === -sign;
19431    var result = sign * (difference - isLastYearNotFull); // Prevent negative zero
19432
19433    return result === 0 ? 0 : result;
19434  }
19435
19436  /**
19437   * @name startOfMinute
19438   * @category Minute Helpers
19439   * @summary Return the start of a minute for the given date.
19440   *
19441   * @description
19442   * Return the start of a minute for the given date.
19443   * The result will be in the local timezone.
19444   *
19445   * ### v2.0.0 breaking changes:
19446   *
19447   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19448   *
19449   * @param {Date|Number} date - the original date
19450   * @returns {Date} the start of a minute
19451   * @throws {TypeError} 1 argument required
19452   *
19453   * @example
19454   * // The start of a minute for 1 December 2014 22:15:45.400:
19455   * const result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400))
19456   * //=> Mon Dec 01 2014 22:15:00
19457   */
19458
19459  function startOfMinute(dirtyDate) {
19460    requiredArgs(1, arguments);
19461    var date = toDate(dirtyDate);
19462    date.setSeconds(0, 0);
19463    return date;
19464  }
19465
19466  /**
19467   * @name startOfQuarter
19468   * @category Quarter Helpers
19469   * @summary Return the start of a year quarter for the given date.
19470   *
19471   * @description
19472   * Return the start of a year quarter for the given date.
19473   * The result will be in the local timezone.
19474   *
19475   * ### v2.0.0 breaking changes:
19476   *
19477   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19478   *
19479   * @param {Date|Number} date - the original date
19480   * @returns {Date} the start of a quarter
19481   * @throws {TypeError} 1 argument required
19482   *
19483   * @example
19484   * // The start of a quarter for 2 September 2014 11:55:00:
19485   * const result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0))
19486   * //=> Tue Jul 01 2014 00:00:00
19487   */
19488
19489  function startOfQuarter(dirtyDate) {
19490    requiredArgs(1, arguments);
19491    var date = toDate(dirtyDate);
19492    var currentMonth = date.getMonth();
19493    var month = currentMonth - currentMonth % 3;
19494    date.setMonth(month, 1);
19495    date.setHours(0, 0, 0, 0);
19496    return date;
19497  }
19498
19499  /**
19500   * @name startOfMonth
19501   * @category Month Helpers
19502   * @summary Return the start of a month for the given date.
19503   *
19504   * @description
19505   * Return the start of a month for the given date.
19506   * The result will be in the local timezone.
19507   *
19508   * ### v2.0.0 breaking changes:
19509   *
19510   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19511   *
19512   * @param {Date|Number} date - the original date
19513   * @returns {Date} the start of a month
19514   * @throws {TypeError} 1 argument required
19515   *
19516   * @example
19517   * // The start of a month for 2 September 2014 11:55:00:
19518   * const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0))
19519   * //=> Mon Sep 01 2014 00:00:00
19520   */
19521
19522  function startOfMonth(dirtyDate) {
19523    requiredArgs(1, arguments);
19524    var date = toDate(dirtyDate);
19525    date.setDate(1);
19526    date.setHours(0, 0, 0, 0);
19527    return date;
19528  }
19529
19530  /**
19531   * @name startOfYear
19532   * @category Year Helpers
19533   * @summary Return the start of a year for the given date.
19534   *
19535   * @description
19536   * Return the start of a year for the given date.
19537   * The result will be in the local timezone.
19538   *
19539   * ### v2.0.0 breaking changes:
19540   *
19541   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19542   *
19543   * @param {Date|Number} date - the original date
19544   * @returns {Date} the start of a year
19545   * @throws {TypeError} 1 argument required
19546   *
19547   * @example
19548   * // The start of a year for 2 September 2014 11:55:00:
19549   * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00))
19550   * //=> Wed Jan 01 2014 00:00:00
19551   */
19552
19553  function startOfYear(dirtyDate) {
19554    requiredArgs(1, arguments);
19555    var cleanDate = toDate(dirtyDate);
19556    var date = new Date(0);
19557    date.setFullYear(cleanDate.getFullYear(), 0, 1);
19558    date.setHours(0, 0, 0, 0);
19559    return date;
19560  }
19561
19562  /**
19563   * @name endOfYear
19564   * @category Year Helpers
19565   * @summary Return the end of a year for the given date.
19566   *
19567   * @description
19568   * Return the end of a year for the given date.
19569   * The result will be in the local timezone.
19570   *
19571   * ### v2.0.0 breaking changes:
19572   *
19573   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19574   *
19575   * @param {Date|Number} date - the original date
19576   * @returns {Date} the end of a year
19577   * @throws {TypeError} 1 argument required
19578   *
19579   * @example
19580   * // The end of a year for 2 September 2014 11:55:00:
19581   * var result = endOfYear(new Date(2014, 8, 2, 11, 55, 00))
19582   * //=> Wed Dec 31 2014 23:59:59.999
19583   */
19584
19585  function endOfYear(dirtyDate) {
19586    requiredArgs(1, arguments);
19587    var date = toDate(dirtyDate);
19588    var year = date.getFullYear();
19589    date.setFullYear(year + 1, 0, 0);
19590    date.setHours(23, 59, 59, 999);
19591    return date;
19592  }
19593
19594  /**
19595   * @name endOfHour
19596   * @category Hour Helpers
19597   * @summary Return the end of an hour for the given date.
19598   *
19599   * @description
19600   * Return the end of an hour for the given date.
19601   * The result will be in the local timezone.
19602   *
19603   * ### v2.0.0 breaking changes:
19604   *
19605   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19606   *
19607   * @param {Date|Number} date - the original date
19608   * @returns {Date} the end of an hour
19609   * @throws {TypeError} 1 argument required
19610   *
19611   * @example
19612   * // The end of an hour for 2 September 2014 11:55:00:
19613   * const result = endOfHour(new Date(2014, 8, 2, 11, 55))
19614   * //=> Tue Sep 02 2014 11:59:59.999
19615   */
19616
19617  function endOfHour(dirtyDate) {
19618    requiredArgs(1, arguments);
19619    var date = toDate(dirtyDate);
19620    date.setMinutes(59, 59, 999);
19621    return date;
19622  }
19623
19624  /**
19625   * @name endOfWeek
19626   * @category Week Helpers
19627   * @summary Return the end of a week for the given date.
19628   *
19629   * @description
19630   * Return the end of a week for the given date.
19631   * The result will be in the local timezone.
19632   *
19633   * ### v2.0.0 breaking changes:
19634   *
19635   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19636   *
19637   * @param {Date|Number} date - the original date
19638   * @param {Object} [options] - an object with options.
19639   * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
19640   * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
19641   * @returns {Date} the end of a week
19642   * @throws {TypeError} 1 argument required
19643   * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
19644   *
19645   * @example
19646   * // The end of a week for 2 September 2014 11:55:00:
19647   * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))
19648   * //=> Sat Sep 06 2014 23:59:59.999
19649   *
19650   * @example
19651   * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:
19652   * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
19653   * //=> Sun Sep 07 2014 23:59:59.999
19654   */
19655
19656  function endOfWeek(dirtyDate, dirtyOptions) {
19657    requiredArgs(1, arguments);
19658    var options = dirtyOptions || {};
19659    var locale = options.locale;
19660    var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
19661    var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
19662    var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
19663
19664    if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
19665      throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
19666    }
19667
19668    var date = toDate(dirtyDate);
19669    var day = date.getDay();
19670    var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
19671    date.setDate(date.getDate() + diff);
19672    date.setHours(23, 59, 59, 999);
19673    return date;
19674  }
19675
19676  /**
19677   * @name endOfMinute
19678   * @category Minute Helpers
19679   * @summary Return the end of a minute for the given date.
19680   *
19681   * @description
19682   * Return the end of a minute for the given date.
19683   * The result will be in the local timezone.
19684   *
19685   * ### v2.0.0 breaking changes:
19686   *
19687   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19688   *
19689   * @param {Date|Number} date - the original date
19690   * @returns {Date} the end of a minute
19691   * @throws {TypeError} 1 argument required
19692   *
19693   * @example
19694   * // The end of a minute for 1 December 2014 22:15:45.400:
19695   * const result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400))
19696   * //=> Mon Dec 01 2014 22:15:59.999
19697   */
19698
19699  function endOfMinute(dirtyDate) {
19700    requiredArgs(1, arguments);
19701    var date = toDate(dirtyDate);
19702    date.setSeconds(59, 999);
19703    return date;
19704  }
19705
19706  /**
19707   * @name endOfQuarter
19708   * @category Quarter Helpers
19709   * @summary Return the end of a year quarter for the given date.
19710   *
19711   * @description
19712   * Return the end of a year quarter for the given date.
19713   * The result will be in the local timezone.
19714   *
19715   * ### v2.0.0 breaking changes:
19716   *
19717   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19718   *
19719   * @param {Date|Number} date - the original date
19720   * @returns {Date} the end of a quarter
19721   * @throws {TypeError} 1 argument required
19722   *
19723   * @example
19724   * // The end of a quarter for 2 September 2014 11:55:00:
19725   * const result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0))
19726   * //=> Tue Sep 30 2014 23:59:59.999
19727   */
19728
19729  function endOfQuarter(dirtyDate) {
19730    requiredArgs(1, arguments);
19731    var date = toDate(dirtyDate);
19732    var currentMonth = date.getMonth();
19733    var month = currentMonth - currentMonth % 3 + 3;
19734    date.setMonth(month, 0);
19735    date.setHours(23, 59, 59, 999);
19736    return date;
19737  }
19738
19739  /**
19740   * @name endOfSecond
19741   * @category Second Helpers
19742   * @summary Return the end of a second for the given date.
19743   *
19744   * @description
19745   * Return the end of a second for the given date.
19746   * The result will be in the local timezone.
19747   *
19748   * ### v2.0.0 breaking changes:
19749   *
19750   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
19751   *
19752   * @param {Date|Number} date - the original date
19753   * @returns {Date} the end of a second
19754   * @throws {TypeError} 1 argument required
19755   *
19756   * @example
19757   * // The end of a second for 1 December 2014 22:15:45.400:
19758   * const result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400))
19759   * //=> Mon Dec 01 2014 22:15:45.999
19760   */
19761
19762  function endOfSecond(dirtyDate) {
19763    requiredArgs(1, arguments);
19764    var date = toDate(dirtyDate);
19765    date.setMilliseconds(999);
19766    return date;
19767  }
19768
19769  var formatDistanceLocale = {
19770    lessThanXSeconds: {
19771      one: 'less than a second',
19772      other: 'less than {{count}} seconds'
19773    },
19774    xSeconds: {
19775      one: '1 second',
19776      other: '{{count}} seconds'
19777    },
19778    halfAMinute: 'half a minute',
19779    lessThanXMinutes: {
19780      one: 'less than a minute',
19781      other: 'less than {{count}} minutes'
19782    },
19783    xMinutes: {
19784      one: '1 minute',
19785      other: '{{count}} minutes'
19786    },
19787    aboutXHours: {
19788      one: 'about 1 hour',
19789      other: 'about {{count}} hours'
19790    },
19791    xHours: {
19792      one: '1 hour',
19793      other: '{{count}} hours'
19794    },
19795    xDays: {
19796      one: '1 day',
19797      other: '{{count}} days'
19798    },
19799    aboutXWeeks: {
19800      one: 'about 1 week',
19801      other: 'about {{count}} weeks'
19802    },
19803    xWeeks: {
19804      one: '1 week',
19805      other: '{{count}} weeks'
19806    },
19807    aboutXMonths: {
19808      one: 'about 1 month',
19809      other: 'about {{count}} months'
19810    },
19811    xMonths: {
19812      one: '1 month',
19813      other: '{{count}} months'
19814    },
19815    aboutXYears: {
19816      one: 'about 1 year',
19817      other: 'about {{count}} years'
19818    },
19819    xYears: {
19820      one: '1 year',
19821      other: '{{count}} years'
19822    },
19823    overXYears: {
19824      one: 'over 1 year',
19825      other: 'over {{count}} years'
19826    },
19827    almostXYears: {
19828      one: 'almost 1 year',
19829      other: 'almost {{count}} years'
19830    }
19831  };
19832  function formatDistance(token, count, options) {
19833    options = options || {};
19834    var result;
19835
19836    if (typeof formatDistanceLocale[token] === 'string') {
19837      result = formatDistanceLocale[token];
19838    } else if (count === 1) {
19839      result = formatDistanceLocale[token].one;
19840    } else {
19841      result = formatDistanceLocale[token].other.replace('{{count}}', count);
19842    }
19843
19844    if (options.addSuffix) {
19845      if (options.comparison > 0) {
19846        return 'in ' + result;
19847      } else {
19848        return result + ' ago';
19849      }
19850    }
19851
19852    return result;
19853  }
19854
19855  function buildFormatLongFn(args) {
19856    return function (dirtyOptions) {
19857      var options = dirtyOptions || {};
19858      var width = options.width ? String(options.width) : args.defaultWidth;
19859      var format = args.formats[width] || args.formats[args.defaultWidth];
19860      return format;
19861    };
19862  }
19863
19864  var dateFormats = {
19865    full: 'EEEE, MMMM do, y',
19866    long: 'MMMM do, y',
19867    medium: 'MMM d, y',
vendor: 12,700 bytes, lines 19868-20295
19868    short: 'MM/dd/yyyy'
19869  };
19870  var timeFormats = {
19871    full: 'h:mm:ss a zzzz',
19872    long: 'h:mm:ss a z',
19873    medium: 'h:mm:ss a',
19874    short: 'h:mm a'
19875  };
19876  var dateTimeFormats = {
19877    full: "{{date}} 'at' {{time}}",
19878    long: "{{date}} 'at' {{time}}",
19879    medium: '{{date}}, {{time}}',
19880    short: '{{date}}, {{time}}'
19881  };
19882  var formatLong = {
19883    date: buildFormatLongFn({
19884      formats: dateFormats,
19885      defaultWidth: 'full'
19886    }),
19887    time: buildFormatLongFn({
19888      formats: timeFormats,
19889      defaultWidth: 'full'
19890    }),
19891    dateTime: buildFormatLongFn({
19892      formats: dateTimeFormats,
19893      defaultWidth: 'full'
19894    })
19895  };
19896
19897  var formatRelativeLocale = {
19898    lastWeek: "'last' eeee 'at' p",
19899    yesterday: "'yesterday at' p",
19900    today: "'today at' p",
19901    tomorrow: "'tomorrow at' p",
19902    nextWeek: "eeee 'at' p",
19903    other: 'P'
19904  };
19905  function formatRelative(token, _date, _baseDate, _options) {
19906    return formatRelativeLocale[token];
19907  }
19908
19909  function buildLocalizeFn(args) {
19910    return function (dirtyIndex, dirtyOptions) {
19911      var options = dirtyOptions || {};
19912      var context = options.context ? String(options.context) : 'standalone';
19913      var valuesArray;
19914
19915      if (context === 'formatting' && args.formattingValues) {
19916        var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
19917        var width = options.width ? String(options.width) : defaultWidth;
19918        valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
19919      } else {
19920        var _defaultWidth = args.defaultWidth;
19921
19922        var _width = options.width ? String(options.width) : args.defaultWidth;
19923
19924        valuesArray = args.values[_width] || args.values[_defaultWidth];
19925      }
19926
19927      var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex;
19928      return valuesArray[index];
19929    };
19930  }
19931
19932  var eraValues = {
19933    narrow: ['B', 'A'],
19934    abbreviated: ['BC', 'AD'],
19935    wide: ['Before Christ', 'Anno Domini']
19936  };
19937  var quarterValues = {
19938    narrow: ['1', '2', '3', '4'],
19939    abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'],
19940    wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter'] // Note: in English, the names of days of the week and months are capitalized.
19941    // If you are making a new locale based on this one, check if the same is true for the language you're working on.
19942    // Generally, formatted dates should look like they are in the middle of a sentence,
19943    // e.g. in Spanish language the weekdays and months should be in the lowercase.
19944
19945  };
19946  var monthValues = {
19947    narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
19948    abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
19949    wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
19950  };
19951  var dayValues = {
19952    narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
19953    short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
19954    abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
19955    wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
19956  };
19957  var dayPeriodValues = {
19958    narrow: {
19959      am: 'a',
19960      pm: 'p',
19961      midnight: 'mi',
19962      noon: 'n',
19963      morning: 'morning',
19964      afternoon: 'afternoon',
19965      evening: 'evening',
19966      night: 'night'
19967    },
19968    abbreviated: {
19969      am: 'AM',
19970      pm: 'PM',
19971      midnight: 'midnight',
19972      noon: 'noon',
19973      morning: 'morning',
19974      afternoon: 'afternoon',
19975      evening: 'evening',
19976      night: 'night'
19977    },
19978    wide: {
19979      am: 'a.m.',
19980      pm: 'p.m.',
19981      midnight: 'midnight',
19982      noon: 'noon',
19983      morning: 'morning',
19984      afternoon: 'afternoon',
19985      evening: 'evening',
19986      night: 'night'
19987    }
19988  };
19989  var formattingDayPeriodValues = {
19990    narrow: {
19991      am: 'a',
19992      pm: 'p',
19993      midnight: 'mi',
19994      noon: 'n',
19995      morning: 'in the morning',
19996      afternoon: 'in the afternoon',
19997      evening: 'in the evening',
19998      night: 'at night'
19999    },
20000    abbreviated: {
20001      am: 'AM',
20002      pm: 'PM',
20003      midnight: 'midnight',
20004      noon: 'noon',
20005      morning: 'in the morning',
20006      afternoon: 'in the afternoon',
20007      evening: 'in the evening',
20008      night: 'at night'
20009    },
20010    wide: {
20011      am: 'a.m.',
20012      pm: 'p.m.',
20013      midnight: 'midnight',
20014      noon: 'noon',
20015      morning: 'in the morning',
20016      afternoon: 'in the afternoon',
20017      evening: 'in the evening',
20018      night: 'at night'
20019    }
20020  };
20021
20022  function ordinalNumber(dirtyNumber, _dirtyOptions) {
20023    var number = Number(dirtyNumber); // If ordinal numbers depend on context, for example,
20024    // if they are different for different grammatical genders,
20025    // use `options.unit`:
20026    //
20027    //   var options = dirtyOptions || {}
20028    //   var unit = String(options.unit)
20029    //
20030    // where `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',
20031    // 'day', 'hour', 'minute', 'second'
20032
20033    var rem100 = number % 100;
20034
20035    if (rem100 > 20 || rem100 < 10) {
20036      switch (rem100 % 10) {
20037        case 1:
20038          return number + 'st';
20039
20040        case 2:
20041          return number + 'nd';
20042
20043        case 3:
20044          return number + 'rd';
20045      }
20046    }
20047
20048    return number + 'th';
20049  }
20050
20051  var localize = {
20052    ordinalNumber: ordinalNumber,
20053    era: buildLocalizeFn({
20054      values: eraValues,
20055      defaultWidth: 'wide'
20056    }),
20057    quarter: buildLocalizeFn({
20058      values: quarterValues,
20059      defaultWidth: 'wide',
20060      argumentCallback: function argumentCallback(quarter) {
20061        return Number(quarter) - 1;
20062      }
20063    }),
20064    month: buildLocalizeFn({
20065      values: monthValues,
20066      defaultWidth: 'wide'
20067    }),
20068    day: buildLocalizeFn({
20069      values: dayValues,
20070      defaultWidth: 'wide'
20071    }),
20072    dayPeriod: buildLocalizeFn({
20073      values: dayPeriodValues,
20074      defaultWidth: 'wide',
20075      formattingValues: formattingDayPeriodValues,
20076      defaultFormattingWidth: 'wide'
20077    })
20078  };
20079
20080  function buildMatchPatternFn(args) {
20081    return function (dirtyString, dirtyOptions) {
20082      var string = String(dirtyString);
20083      var options = dirtyOptions || {};
20084      var matchResult = string.match(args.matchPattern);
20085
20086      if (!matchResult) {
20087        return null;
20088      }
20089
20090      var matchedString = matchResult[0];
20091      var parseResult = string.match(args.parsePattern);
20092
20093      if (!parseResult) {
20094        return null;
20095      }
20096
20097      var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
20098      value = options.valueCallback ? options.valueCallback(value) : value;
20099      return {
20100        value: value,
20101        rest: string.slice(matchedString.length)
20102      };
20103    };
20104  }
20105
20106  function buildMatchFn(args) {
20107    return function (dirtyString, dirtyOptions) {
20108      var string = String(dirtyString);
20109      var options = dirtyOptions || {};
20110      var width = options.width;
20111      var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
20112      var matchResult = string.match(matchPattern);
20113
20114      if (!matchResult) {
20115        return null;
20116      }
20117
20118      var matchedString = matchResult[0];
20119      var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
20120      var value;
20121
20122      if (Object.prototype.toString.call(parsePatterns) === '[object Array]') {
20123        value = findIndex(parsePatterns, function (pattern) {
20124          return pattern.test(matchedString);
20125        });
20126      } else {
20127        value = findKey(parsePatterns, function (pattern) {
20128          return pattern.test(matchedString);
20129        });
20130      }
20131
20132      value = args.valueCallback ? args.valueCallback(value) : value;
20133      value = options.valueCallback ? options.valueCallback(value) : value;
20134      return {
20135        value: value,
20136        rest: string.slice(matchedString.length)
20137      };
20138    };
20139  }
20140
20141  function findKey(object, predicate) {
20142    for (var key in object) {
20143      if (object.hasOwnProperty(key) && predicate(object[key])) {
20144        return key;
20145      }
20146    }
20147  }
20148
20149  function findIndex(array, predicate) {
20150    for (var key = 0; key < array.length; key++) {
20151      if (predicate(array[key])) {
20152        return key;
20153      }
20154    }
20155  }
20156
20157  var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
20158  var parseOrdinalNumberPattern = /\d+/i;
20159  var matchEraPatterns = {
20160    narrow: /^(b|a)/i,
20161    abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
20162    wide: /^(before christ|before common era|anno domini|common era)/i
20163  };
20164  var parseEraPatterns = {
20165    any: [/^b/i, /^(a|c)/i]
20166  };
20167  var matchQuarterPatterns = {
20168    narrow: /^[1234]/i,
20169    abbreviated: /^q[1234]/i,
20170    wide: /^[1234](th|st|nd|rd)? quarter/i
20171  };
20172  var parseQuarterPatterns = {
20173    any: [/1/i, /2/i, /3/i, /4/i]
20174  };
20175  var matchMonthPatterns = {
20176    narrow: /^[jfmasond]/i,
20177    abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
20178    wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
20179  };
20180  var parseMonthPatterns = {
20181    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],
20182    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]
20183  };
20184  var matchDayPatterns = {
20185    narrow: /^[smtwf]/i,
20186    short: /^(su|mo|tu|we|th|fr|sa)/i,
20187    abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
20188    wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
20189  };
20190  var parseDayPatterns = {
20191    narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
20192    any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
20193  };
20194  var matchDayPeriodPatterns = {
20195    narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
20196    any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
20197  };
20198  var parseDayPeriodPatterns = {
20199    any: {
20200      am: /^a/i,
20201      pm: /^p/i,
20202      midnight: /^mi/i,
20203      noon: /^no/i,
20204      morning: /morning/i,
20205      afternoon: /afternoon/i,
20206      evening: /evening/i,
20207      night: /night/i
20208    }
20209  };
20210  var match = {
20211    ordinalNumber: buildMatchPatternFn({
20212      matchPattern: matchOrdinalNumberPattern,
20213      parsePattern: parseOrdinalNumberPattern,
20214      valueCallback: function valueCallback(value) {
20215        return parseInt(value, 10);
20216      }
20217    }),
20218    era: buildMatchFn({
20219      matchPatterns: matchEraPatterns,
20220      defaultMatchWidth: 'wide',
20221      parsePatterns: parseEraPatterns,
20222      defaultParseWidth: 'any'
20223    }),
20224    quarter: buildMatchFn({
20225      matchPatterns: matchQuarterPatterns,
20226      defaultMatchWidth: 'wide',
20227      parsePatterns: parseQuarterPatterns,
20228      defaultParseWidth: 'any',
20229      valueCallback: function valueCallback(index) {
20230        return index + 1;
20231      }
20232    }),
20233    month: buildMatchFn({
20234      matchPatterns: matchMonthPatterns,
20235      defaultMatchWidth: 'wide',
20236      parsePatterns: parseMonthPatterns,
20237      defaultParseWidth: 'any'
20238    }),
20239    day: buildMatchFn({
20240      matchPatterns: matchDayPatterns,
20241      defaultMatchWidth: 'wide',
20242      parsePatterns: parseDayPatterns,
20243      defaultParseWidth: 'any'
20244    }),
20245    dayPeriod: buildMatchFn({
20246      matchPatterns: matchDayPeriodPatterns,
20247      defaultMatchWidth: 'any',
20248      parsePatterns: parseDayPeriodPatterns,
20249      defaultParseWidth: 'any'
20250    })
20251  };
20252
20253  /**
20254   * @type {Locale}
20255   * @category Locales
20256   * @summary English locale (United States).
20257   * @language English
20258   * @iso-639-2 eng
20259   * @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp}
20260   * @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss}
20261   */
20262
20263  var locale = {
20264    code: 'en-US',
20265    formatDistance: formatDistance,
20266    formatLong: formatLong,
20267    formatRelative: formatRelative,
20268    localize: localize,
20269    match: match,
20270    options: {
20271      weekStartsOn: 0
20272      /* Sunday */
20273      ,
20274      firstWeekContainsDate: 1
20275    }
20276  };
20277
20278  /**
20279   * @name subMilliseconds
20280   * @category Millisecond Helpers
20281   * @summary Subtract the specified number of milliseconds from the given date.
20282   *
20283   * @description
20284   * Subtract the specified number of milliseconds from the given date.
20285   *
20286   * ### v2.0.0 breaking changes:
20287   *
20288   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
20289   *
20290   * @param {Date|Number} date - the date to be changed
20291   * @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`.
20292   * @returns {Date} the new date with the milliseconds subtracted
20293   * @throws {TypeError} 2 arguments required
20294   *
20295   * @example
vendor: 4,530 bytes, lines 20296-20419
20296   * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000:
20297   * const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
20298   * //=> Thu Jul 10 2014 12:45:29.250
20299   */
20300
20301  function subMilliseconds(dirtyDate, dirtyAmount) {
20302    requiredArgs(2, arguments);
20303    var amount = toInteger(dirtyAmount);
20304    return addMilliseconds(dirtyDate, -amount);
20305  }
20306
20307  function addLeadingZeros(number, targetLength) {
20308    var sign = number < 0 ? '-' : '';
20309    var output = Math.abs(number).toString();
20310
20311    while (output.length < targetLength) {
20312      output = '0' + output;
20313    }
20314
20315    return sign + output;
20316  }
20317
20318  /*
20319   * |     | Unit                           |     | Unit                           |
20320   * |-----|--------------------------------|-----|--------------------------------|
20321   * |  a  | AM, PM                         |  A* |                                |
20322   * |  d  | Day of month                   |  D  |                                |
20323   * |  h  | Hour [1-12]                    |  H  | Hour [0-23]                    |
20324   * |  m  | Minute                         |  M  | Month                          |
20325   * |  s  | Second                         |  S  | Fraction of second             |
20326   * |  y  | Year (abs)                     |  Y  |                                |
20327   *
20328   * Letters marked by * are not implemented but reserved by Unicode standard.
20329   */
20330
20331  var formatters$1 = {
20332    // Year
20333    y: function y(date, token) {
20334      // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens
20335      // | Year     |     y | yy |   yyy |  yyyy | yyyyy |
20336      // |----------|-------|----|-------|-------|-------|
20337      // | AD 1     |     1 | 01 |   001 |  0001 | 00001 |
20338      // | AD 12    |    12 | 12 |   012 |  0012 | 00012 |
20339      // | AD 123   |   123 | 23 |   123 |  0123 | 00123 |
20340      // | AD 1234  |  1234 | 34 |  1234 |  1234 | 01234 |
20341      // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
20342      var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript)
20343
20344      var year = signedYear > 0 ? signedYear : 1 - signedYear;
20345      return addLeadingZeros(token === 'yy' ? year % 100 : year, token.length);
20346    },
20347    // Month
20348    M: function M(date, token) {
20349      var month = date.getUTCMonth();
20350      return token === 'M' ? String(month + 1) : addLeadingZeros(month + 1, 2);
20351    },
20352    // Day of the month
20353    d: function d(date, token) {
20354      return addLeadingZeros(date.getUTCDate(), token.length);
20355    },
20356    // AM or PM
20357    a: function a(date, token) {
20358      var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am';
20359
20360      switch (token) {
20361        case 'a':
20362        case 'aa':
20363          return dayPeriodEnumValue.toUpperCase();
20364
20365        case 'aaa':
20366          return dayPeriodEnumValue;
20367
20368        case 'aaaaa':
20369          return dayPeriodEnumValue[0];
20370
20371        case 'aaaa':
20372        default:
20373          return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.';
20374      }
20375    },
20376    // Hour [1-12]
20377    h: function h(date, token) {
20378      return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
20379    },
20380    // Hour [0-23]
20381    H: function H(date, token) {
20382      return addLeadingZeros(date.getUTCHours(), token.length);
20383    },
20384    // Minute
20385    m: function m(date, token) {
20386      return addLeadingZeros(date.getUTCMinutes(), token.length);
20387    },
20388    // Second
20389    s: function s(date, token) {
20390      return addLeadingZeros(date.getUTCSeconds(), token.length);
20391    },
20392    // Fraction of second
20393    S: function S(date, token) {
20394      var numberOfDigits = token.length;
20395      var milliseconds = date.getUTCMilliseconds();
20396      var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
20397      return addLeadingZeros(fractionalSeconds, token.length);
20398    }
20399  };
20400
20401  var MILLISECONDS_IN_DAY = 86400000; // This function will be a part of public API when UTC function will be implemented.
20402  // See issue: https://github.com/date-fns/date-fns/issues/376
20403
20404  function getUTCDayOfYear(dirtyDate) {
20405    requiredArgs(1, arguments);
20406    var date = toDate(dirtyDate);
20407    var timestamp = date.getTime();
20408    date.setUTCMonth(0, 1);
20409    date.setUTCHours(0, 0, 0, 0);
20410    var startOfYearTimestamp = date.getTime();
20411    var difference = timestamp - startOfYearTimestamp;
20412    return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
20413  }
20414
20415  // See issue: https://github.com/date-fns/date-fns/issues/376
20416
20417  function startOfUTCISOWeek(dirtyDate) {
20418    requiredArgs(1, arguments);
20419    var weekStartsOn = 1;
vendor: 5,841 bytes, lines 20420-20554
20420    var date = toDate(dirtyDate);
20421    var day = date.getUTCDay();
20422    var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
20423    date.setUTCDate(date.getUTCDate() - diff);
20424    date.setUTCHours(0, 0, 0, 0);
20425    return date;
20426  }
20427
20428  // See issue: https://github.com/date-fns/date-fns/issues/376
20429
20430  function getUTCISOWeekYear(dirtyDate) {
20431    requiredArgs(1, arguments);
20432    var date = toDate(dirtyDate);
20433    var year = date.getUTCFullYear();
20434    var fourthOfJanuaryOfNextYear = new Date(0);
20435    fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
20436    fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
20437    var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
20438    var fourthOfJanuaryOfThisYear = new Date(0);
20439    fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
20440    fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
20441    var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
20442
20443    if (date.getTime() >= startOfNextYear.getTime()) {
20444      return year + 1;
20445    } else if (date.getTime() >= startOfThisYear.getTime()) {
20446      return year;
20447    } else {
20448      return year - 1;
20449    }
20450  }
20451
20452  // See issue: https://github.com/date-fns/date-fns/issues/376
20453
20454  function startOfUTCISOWeekYear(dirtyDate) {
20455    requiredArgs(1, arguments);
20456    var year = getUTCISOWeekYear(dirtyDate);
20457    var fourthOfJanuary = new Date(0);
20458    fourthOfJanuary.setUTCFullYear(year, 0, 4);
20459    fourthOfJanuary.setUTCHours(0, 0, 0, 0);
20460    var date = startOfUTCISOWeek(fourthOfJanuary);
20461    return date;
20462  }
20463
20464  var MILLISECONDS_IN_WEEK$1 = 604800000; // This function will be a part of public API when UTC function will be implemented.
20465  // See issue: https://github.com/date-fns/date-fns/issues/376
20466
20467  function getUTCISOWeek(dirtyDate) {
20468    requiredArgs(1, arguments);
20469    var date = toDate(dirtyDate);
20470    var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); // Round the number of days to the nearest integer
20471    // because the number of milliseconds in a week is not constant
20472    // (e.g. it's different in the week of the daylight saving time clock shift)
20473
20474    return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1;
20475  }
20476
20477  // See issue: https://github.com/date-fns/date-fns/issues/376
20478
20479  function startOfUTCWeek(dirtyDate, dirtyOptions) {
20480    requiredArgs(1, arguments);
20481    var options = dirtyOptions || {};
20482    var locale = options.locale;
20483    var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
20484    var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
20485    var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
20486
20487    if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
20488      throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
20489    }
20490
20491    var date = toDate(dirtyDate);
20492    var day = date.getUTCDay();
20493    var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
20494    date.setUTCDate(date.getUTCDate() - diff);
20495    date.setUTCHours(0, 0, 0, 0);
20496    return date;
20497  }
20498
20499  // See issue: https://github.com/date-fns/date-fns/issues/376
20500
20501  function getUTCWeekYear(dirtyDate, dirtyOptions) {
20502    requiredArgs(1, arguments);
20503    var date = toDate(dirtyDate, dirtyOptions);
20504    var year = date.getUTCFullYear();
20505    var options = dirtyOptions || {};
20506    var locale = options.locale;
20507    var localeFirstWeekContainsDate = locale && locale.options && locale.options.firstWeekContainsDate;
20508    var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate);
20509    var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
20510
20511    if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
20512      throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
20513    }
20514
20515    var firstWeekOfNextYear = new Date(0);
20516    firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
20517    firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
20518    var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, dirtyOptions);
20519    var firstWeekOfThisYear = new Date(0);
20520    firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
20521    firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
20522    var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, dirtyOptions);
20523
20524    if (date.getTime() >= startOfNextYear.getTime()) {
20525      return year + 1;
20526    } else if (date.getTime() >= startOfThisYear.getTime()) {
20527      return year;
20528    } else {
20529      return year - 1;
20530    }
20531  }
20532
20533  // See issue: https://github.com/date-fns/date-fns/issues/376
20534
20535  function startOfUTCWeekYear(dirtyDate, dirtyOptions) {
20536    requiredArgs(1, arguments);
20537    var options = dirtyOptions || {};
20538    var locale = options.locale;
20539    var localeFirstWeekContainsDate = locale && locale.options && locale.options.firstWeekContainsDate;
20540    var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate);
20541    var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate);
20542    var year = getUTCWeekYear(dirtyDate, dirtyOptions);
20543    var firstWeek = new Date(0);
20544    firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
20545    firstWeek.setUTCHours(0, 0, 0, 0);
20546    var date = startOfUTCWeek(firstWeek, dirtyOptions);
20547    return date;
20548  }
20549
20550  var MILLISECONDS_IN_WEEK = 604800000; // This function will be a part of public API when UTC function will be implemented.
20551  // See issue: https://github.com/date-fns/date-fns/issues/376
20552
20553  function getUTCWeek(dirtyDate, options) {
20554    requiredArgs(1, arguments);
vendor: 6,433 bytes, lines 20555-20702
20555    var date = toDate(dirtyDate);
20556    var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime(); // Round the number of days to the nearest integer
20557    // because the number of milliseconds in a week is not constant
20558    // (e.g. it's different in the week of the daylight saving time clock shift)
20559
20560    return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
20561  }
20562
20563  var dayPeriodEnum = {
20564    am: 'am',
20565    pm: 'pm',
20566    midnight: 'midnight',
20567    noon: 'noon',
20568    morning: 'morning',
20569    afternoon: 'afternoon',
20570    evening: 'evening',
20571    night: 'night'
20572    /*
20573     * |     | Unit                           |     | Unit                           |
20574     * |-----|--------------------------------|-----|--------------------------------|
20575     * |  a  | AM, PM                         |  A* | Milliseconds in day            |
20576     * |  b  | AM, PM, noon, midnight         |  B  | Flexible day period            |
20577     * |  c  | Stand-alone local day of week  |  C* | Localized hour w/ day period   |
20578     * |  d  | Day of month                   |  D  | Day of year                    |
20579     * |  e  | Local day of week              |  E  | Day of week                    |
20580     * |  f  |                                |  F* | Day of week in month           |
20581     * |  g* | Modified Julian day            |  G  | Era                            |
20582     * |  h  | Hour [1-12]                    |  H  | Hour [0-23]                    |
20583     * |  i! | ISO day of week                |  I! | ISO week of year               |
20584     * |  j* | Localized hour w/ day period   |  J* | Localized hour w/o day period  |
20585     * |  k  | Hour [1-24]                    |  K  | Hour [0-11]                    |
20586     * |  l* | (deprecated)                   |  L  | Stand-alone month              |
20587     * |  m  | Minute                         |  M  | Month                          |
20588     * |  n  |                                |  N  |                                |
20589     * |  o! | Ordinal number modifier        |  O  | Timezone (GMT)                 |
20590     * |  p! | Long localized time            |  P! | Long localized date            |
20591     * |  q  | Stand-alone quarter            |  Q  | Quarter                        |
20592     * |  r* | Related Gregorian year         |  R! | ISO week-numbering year        |
20593     * |  s  | Second                         |  S  | Fraction of second             |
20594     * |  t! | Seconds timestamp              |  T! | Milliseconds timestamp         |
20595     * |  u  | Extended year                  |  U* | Cyclic year                    |
20596     * |  v* | Timezone (generic non-locat.)  |  V* | Timezone (location)            |
20597     * |  w  | Local week of year             |  W* | Week of month                  |
20598     * |  x  | Timezone (ISO-8601 w/o Z)      |  X  | Timezone (ISO-8601)            |
20599     * |  y  | Year (abs)                     |  Y  | Local week-numbering year      |
20600     * |  z  | Timezone (specific non-locat.) |  Z* | Timezone (aliases)             |
20601     *
20602     * Letters marked by * are not implemented but reserved by Unicode standard.
20603     *
20604     * Letters marked by ! are non-standard, but implemented by date-fns:
20605     * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
20606     * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
20607     *   i.e. 7 for Sunday, 1 for Monday, etc.
20608     * - `I` is ISO week of year, as opposed to `w` which is local week of year.
20609     * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
20610     *   `R` is supposed to be used in conjunction with `I` and `i`
20611     *   for universal ISO week-numbering date, whereas
20612     *   `Y` is supposed to be used in conjunction with `w` and `e`
20613     *   for week-numbering date specific to the locale.
20614     * - `P` is long localized date format
20615     * - `p` is long localized time format
20616     */
20617
20618  };
20619  var formatters = {
20620    // Era
20621    G: function G(date, token, localize) {
20622      var era = date.getUTCFullYear() > 0 ? 1 : 0;
20623
20624      switch (token) {
20625        // AD, BC
20626        case 'G':
20627        case 'GG':
20628        case 'GGG':
20629          return localize.era(era, {
20630            width: 'abbreviated'
20631          });
20632        // A, B
20633
20634        case 'GGGGG':
20635          return localize.era(era, {
20636            width: 'narrow'
20637          });
20638        // Anno Domini, Before Christ
20639
20640        case 'GGGG':
20641        default:
20642          return localize.era(era, {
20643            width: 'wide'
20644          });
20645      }
20646    },
20647    // Year
20648    y: function y(date, token, localize) {
20649      // Ordinal number
20650      if (token === 'yo') {
20651        var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript)
20652
20653        var year = signedYear > 0 ? signedYear : 1 - signedYear;
20654        return localize.ordinalNumber(year, {
20655          unit: 'year'
20656        });
20657      }
20658
20659      return formatters$1.y(date, token);
20660    },
20661    // Local week-numbering year
20662    Y: function Y(date, token, localize, options) {
20663      var signedWeekYear = getUTCWeekYear(date, options); // Returns 1 for 1 BC (which is year 0 in JavaScript)
20664
20665      var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; // Two digit year
20666
20667      if (token === 'YY') {
20668        var twoDigitYear = weekYear % 100;
20669        return addLeadingZeros(twoDigitYear, 2);
20670      } // Ordinal number
20671
20672
20673      if (token === 'Yo') {
20674        return localize.ordinalNumber(weekYear, {
20675          unit: 'year'
20676        });
20677      } // Padding
20678
20679
20680      return addLeadingZeros(weekYear, token.length);
20681    },
20682    // ISO week-numbering year
20683    R: function R(date, token) {
20684      var isoWeekYear = getUTCISOWeekYear(date); // Padding
20685
20686      return addLeadingZeros(isoWeekYear, token.length);
20687    },
20688    // Extended year. This is a single number designating the year of this calendar system.
20689    // The main difference between `y` and `u` localizers are B.C. years:
20690    // | Year | `y` | `u` |
20691    // |------|-----|-----|
20692    // | AC 1 |   1 |   1 |
20693    // | BC 1 |   1 |   0 |
20694    // | BC 2 |   2 |  -1 |
20695    // Also `yy` always returns the last two digits of a year,
20696    // while `uu` pads single digit years to 2 characters and returns other years unchanged.
20697    u: function u(date, token) {
20698      var year = date.getUTCFullYear();
20699      return addLeadingZeros(year, token.length);
20700    },
20701    // Quarter
20702    Q: function Q(date, token, localize) {
vendor: 14,940 bytes, lines 20703-21293
20703      var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
20704
20705      switch (token) {
20706        // 1, 2, 3, 4
20707        case 'Q':
20708          return String(quarter);
20709        // 01, 02, 03, 04
20710
20711        case 'QQ':
20712          return addLeadingZeros(quarter, 2);
20713        // 1st, 2nd, 3rd, 4th
20714
20715        case 'Qo':
20716          return localize.ordinalNumber(quarter, {
20717            unit: 'quarter'
20718          });
20719        // Q1, Q2, Q3, Q4
20720
20721        case 'QQQ':
20722          return localize.quarter(quarter, {
20723            width: 'abbreviated',
20724            context: 'formatting'
20725          });
20726        // 1, 2, 3, 4 (narrow quarter; could be not numerical)
20727
20728        case 'QQQQQ':
20729          return localize.quarter(quarter, {
20730            width: 'narrow',
20731            context: 'formatting'
20732          });
20733        // 1st quarter, 2nd quarter, ...
20734
20735        case 'QQQQ':
20736        default:
20737          return localize.quarter(quarter, {
20738            width: 'wide',
20739            context: 'formatting'
20740          });
20741      }
20742    },
20743    // Stand-alone quarter
20744    q: function q(date, token, localize) {
20745      var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
20746
20747      switch (token) {
20748        // 1, 2, 3, 4
20749        case 'q':
20750          return String(quarter);
20751        // 01, 02, 03, 04
20752
20753        case 'qq':
20754          return addLeadingZeros(quarter, 2);
20755        // 1st, 2nd, 3rd, 4th
20756
20757        case 'qo':
20758          return localize.ordinalNumber(quarter, {
20759            unit: 'quarter'
20760          });
20761        // Q1, Q2, Q3, Q4
20762
20763        case 'qqq':
20764          return localize.quarter(quarter, {
20765            width: 'abbreviated',
20766            context: 'standalone'
20767          });
20768        // 1, 2, 3, 4 (narrow quarter; could be not numerical)
20769
20770        case 'qqqqq':
20771          return localize.quarter(quarter, {
20772            width: 'narrow',
20773            context: 'standalone'
20774          });
20775        // 1st quarter, 2nd quarter, ...
20776
20777        case 'qqqq':
20778        default:
20779          return localize.quarter(quarter, {
20780            width: 'wide',
20781            context: 'standalone'
20782          });
20783      }
20784    },
20785    // Month
20786    M: function M(date, token, localize) {
20787      var month = date.getUTCMonth();
20788
20789      switch (token) {
20790        case 'M':
20791        case 'MM':
20792          return formatters$1.M(date, token);
20793        // 1st, 2nd, ..., 12th
20794
20795        case 'Mo':
20796          return localize.ordinalNumber(month + 1, {
20797            unit: 'month'
20798          });
20799        // Jan, Feb, ..., Dec
20800
20801        case 'MMM':
20802          return localize.month(month, {
20803            width: 'abbreviated',
20804            context: 'formatting'
20805          });
20806        // J, F, ..., D
20807
20808        case 'MMMMM':
20809          return localize.month(month, {
20810            width: 'narrow',
20811            context: 'formatting'
20812          });
20813        // January, February, ..., December
20814
20815        case 'MMMM':
20816        default:
20817          return localize.month(month, {
20818            width: 'wide',
20819            context: 'formatting'
20820          });
20821      }
20822    },
20823    // Stand-alone month
20824    L: function L(date, token, localize) {
20825      var month = date.getUTCMonth();
20826
20827      switch (token) {
20828        // 1, 2, ..., 12
20829        case 'L':
20830          return String(month + 1);
20831        // 01, 02, ..., 12
20832
20833        case 'LL':
20834          return addLeadingZeros(month + 1, 2);
20835        // 1st, 2nd, ..., 12th
20836
20837        case 'Lo':
20838          return localize.ordinalNumber(month + 1, {
20839            unit: 'month'
20840          });
20841        // Jan, Feb, ..., Dec
20842
20843        case 'LLL':
20844          return localize.month(month, {
20845            width: 'abbreviated',
20846            context: 'standalone'
20847          });
20848        // J, F, ..., D
20849
20850        case 'LLLLL':
20851          return localize.month(month, {
20852            width: 'narrow',
20853            context: 'standalone'
20854          });
20855        // January, February, ..., December
20856
20857        case 'LLLL':
20858        default:
20859          return localize.month(month, {
20860            width: 'wide',
20861            context: 'standalone'
20862          });
20863      }
20864    },
20865    // Local week of year
20866    w: function w(date, token, localize, options) {
20867      var week = getUTCWeek(date, options);
20868
20869      if (token === 'wo') {
20870        return localize.ordinalNumber(week, {
20871          unit: 'week'
20872        });
20873      }
20874
20875      return addLeadingZeros(week, token.length);
20876    },
20877    // ISO week of year
20878    I: function I(date, token, localize) {
20879      var isoWeek = getUTCISOWeek(date);
20880
20881      if (token === 'Io') {
20882        return localize.ordinalNumber(isoWeek, {
20883          unit: 'week'
20884        });
20885      }
20886
20887      return addLeadingZeros(isoWeek, token.length);
20888    },
20889    // Day of the month
20890    d: function d(date, token, localize) {
20891      if (token === 'do') {
20892        return localize.ordinalNumber(date.getUTCDate(), {
20893          unit: 'date'
20894        });
20895      }
20896
20897      return formatters$1.d(date, token);
20898    },
20899    // Day of year
20900    D: function D(date, token, localize) {
20901      var dayOfYear = getUTCDayOfYear(date);
20902
20903      if (token === 'Do') {
20904        return localize.ordinalNumber(dayOfYear, {
20905          unit: 'dayOfYear'
20906        });
20907      }
20908
20909      return addLeadingZeros(dayOfYear, token.length);
20910    },
20911    // Day of week
20912    E: function E(date, token, localize) {
20913      var dayOfWeek = date.getUTCDay();
20914
20915      switch (token) {
20916        // Tue
20917        case 'E':
20918        case 'EE':
20919        case 'EEE':
20920          return localize.day(dayOfWeek, {
20921            width: 'abbreviated',
20922            context: 'formatting'
20923          });
20924        // T
20925
20926        case 'EEEEE':
20927          return localize.day(dayOfWeek, {
20928            width: 'narrow',
20929            context: 'formatting'
20930          });
20931        // Tu
20932
20933        case 'EEEEEE':
20934          return localize.day(dayOfWeek, {
20935            width: 'short',
20936            context: 'formatting'
20937          });
20938        // Tuesday
20939
20940        case 'EEEE':
20941        default:
20942          return localize.day(dayOfWeek, {
20943            width: 'wide',
20944            context: 'formatting'
20945          });
20946      }
20947    },
20948    // Local day of week
20949    e: function e(date, token, localize, options) {
20950      var dayOfWeek = date.getUTCDay();
20951      var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
20952
20953      switch (token) {
20954        // Numerical value (Nth day of week with current locale or weekStartsOn)
20955        case 'e':
20956          return String(localDayOfWeek);
20957        // Padded numerical value
20958
20959        case 'ee':
20960          return addLeadingZeros(localDayOfWeek, 2);
20961        // 1st, 2nd, ..., 7th
20962
20963        case 'eo':
20964          return localize.ordinalNumber(localDayOfWeek, {
20965            unit: 'day'
20966          });
20967
20968        case 'eee':
20969          return localize.day(dayOfWeek, {
20970            width: 'abbreviated',
20971            context: 'formatting'
20972          });
20973        // T
20974
20975        case 'eeeee':
20976          return localize.day(dayOfWeek, {
20977            width: 'narrow',
20978            context: 'formatting'
20979          });
20980        // Tu
20981
20982        case 'eeeeee':
20983          return localize.day(dayOfWeek, {
20984            width: 'short',
20985            context: 'formatting'
20986          });
20987        // Tuesday
20988
20989        case 'eeee':
20990        default:
20991          return localize.day(dayOfWeek, {
20992            width: 'wide',
20993            context: 'formatting'
20994          });
20995      }
20996    },
20997    // Stand-alone local day of week
20998    c: function c(date, token, localize, options) {
20999      var dayOfWeek = date.getUTCDay();
21000      var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
21001
21002      switch (token) {
21003        // Numerical value (same as in `e`)
21004        case 'c':
21005          return String(localDayOfWeek);
21006        // Padded numerical value
21007
21008        case 'cc':
21009          return addLeadingZeros(localDayOfWeek, token.length);
21010        // 1st, 2nd, ..., 7th
21011
21012        case 'co':
21013          return localize.ordinalNumber(localDayOfWeek, {
21014            unit: 'day'
21015          });
21016
21017        case 'ccc':
21018          return localize.day(dayOfWeek, {
21019            width: 'abbreviated',
21020            context: 'standalone'
21021          });
21022        // T
21023
21024        case 'ccccc':
21025          return localize.day(dayOfWeek, {
21026            width: 'narrow',
21027            context: 'standalone'
21028          });
21029        // Tu
21030
21031        case 'cccccc':
21032          return localize.day(dayOfWeek, {
21033            width: 'short',
21034            context: 'standalone'
21035          });
21036        // Tuesday
21037
21038        case 'cccc':
21039        default:
21040          return localize.day(dayOfWeek, {
21041            width: 'wide',
21042            context: 'standalone'
21043          });
21044      }
21045    },
21046    // ISO day of week
21047    i: function i(date, token, localize) {
21048      var dayOfWeek = date.getUTCDay();
21049      var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
21050
21051      switch (token) {
21052        // 2
21053        case 'i':
21054          return String(isoDayOfWeek);
21055        // 02
21056
21057        case 'ii':
21058          return addLeadingZeros(isoDayOfWeek, token.length);
21059        // 2nd
21060
21061        case 'io':
21062          return localize.ordinalNumber(isoDayOfWeek, {
21063            unit: 'day'
21064          });
21065        // Tue
21066
21067        case 'iii':
21068          return localize.day(dayOfWeek, {
21069            width: 'abbreviated',
21070            context: 'formatting'
21071          });
21072        // T
21073
21074        case 'iiiii':
21075          return localize.day(dayOfWeek, {
21076            width: 'narrow',
21077            context: 'formatting'
21078          });
21079        // Tu
21080
21081        case 'iiiiii':
21082          return localize.day(dayOfWeek, {
21083            width: 'short',
21084            context: 'formatting'
21085          });
21086        // Tuesday
21087
21088        case 'iiii':
21089        default:
21090          return localize.day(dayOfWeek, {
21091            width: 'wide',
21092            context: 'formatting'
21093          });
21094      }
21095    },
21096    // AM or PM
21097    a: function a(date, token, localize) {
21098      var hours = date.getUTCHours();
21099      var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
21100
21101      switch (token) {
21102        case 'a':
21103        case 'aa':
21104          return localize.dayPeriod(dayPeriodEnumValue, {
21105            width: 'abbreviated',
21106            context: 'formatting'
21107          });
21108
21109        case 'aaa':
21110          return localize.dayPeriod(dayPeriodEnumValue, {
21111            width: 'abbreviated',
21112            context: 'formatting'
21113          }).toLowerCase();
21114
21115        case 'aaaaa':
21116          return localize.dayPeriod(dayPeriodEnumValue, {
21117            width: 'narrow',
21118            context: 'formatting'
21119          });
21120
21121        case 'aaaa':
21122        default:
21123          return localize.dayPeriod(dayPeriodEnumValue, {
21124            width: 'wide',
21125            context: 'formatting'
21126          });
21127      }
21128    },
21129    // AM, PM, midnight, noon
21130    b: function b(date, token, localize) {
21131      var hours = date.getUTCHours();
21132      var dayPeriodEnumValue;
21133
21134      if (hours === 12) {
21135        dayPeriodEnumValue = dayPeriodEnum.noon;
21136      } else if (hours === 0) {
21137        dayPeriodEnumValue = dayPeriodEnum.midnight;
21138      } else {
21139        dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
21140      }
21141
21142      switch (token) {
21143        case 'b':
21144        case 'bb':
21145          return localize.dayPeriod(dayPeriodEnumValue, {
21146            width: 'abbreviated',
21147            context: 'formatting'
21148          });
21149
21150        case 'bbb':
21151          return localize.dayPeriod(dayPeriodEnumValue, {
21152            width: 'abbreviated',
21153            context: 'formatting'
21154          }).toLowerCase();
21155
21156        case 'bbbbb':
21157          return localize.dayPeriod(dayPeriodEnumValue, {
21158            width: 'narrow',
21159            context: 'formatting'
21160          });
21161
21162        case 'bbbb':
21163        default:
21164          return localize.dayPeriod(dayPeriodEnumValue, {
21165            width: 'wide',
21166            context: 'formatting'
21167          });
21168      }
21169    },
21170    // in the morning, in the afternoon, in the evening, at night
21171    B: function B(date, token, localize) {
21172      var hours = date.getUTCHours();
21173      var dayPeriodEnumValue;
21174
21175      if (hours >= 17) {
21176        dayPeriodEnumValue = dayPeriodEnum.evening;
21177      } else if (hours >= 12) {
21178        dayPeriodEnumValue = dayPeriodEnum.afternoon;
21179      } else if (hours >= 4) {
21180        dayPeriodEnumValue = dayPeriodEnum.morning;
21181      } else {
21182        dayPeriodEnumValue = dayPeriodEnum.night;
21183      }
21184
21185      switch (token) {
21186        case 'B':
21187        case 'BB':
21188        case 'BBB':
21189          return localize.dayPeriod(dayPeriodEnumValue, {
21190            width: 'abbreviated',
21191            context: 'formatting'
21192          });
21193
21194        case 'BBBBB':
21195          return localize.dayPeriod(dayPeriodEnumValue, {
21196            width: 'narrow',
21197            context: 'formatting'
21198          });
21199
21200        case 'BBBB':
21201        default:
21202          return localize.dayPeriod(dayPeriodEnumValue, {
21203            width: 'wide',
21204            context: 'formatting'
21205          });
21206      }
21207    },
21208    // Hour [1-12]
21209    h: function h(date, token, localize) {
21210      if (token === 'ho') {
21211        var hours = date.getUTCHours() % 12;
21212        if (hours === 0) hours = 12;
21213        return localize.ordinalNumber(hours, {
21214          unit: 'hour'
21215        });
21216      }
21217
21218      return formatters$1.h(date, token);
21219    },
21220    // Hour [0-23]
21221    H: function H(date, token, localize) {
21222      if (token === 'Ho') {
21223        return localize.ordinalNumber(date.getUTCHours(), {
21224          unit: 'hour'
21225        });
21226      }
21227
21228      return formatters$1.H(date, token);
21229    },
21230    // Hour [0-11]
21231    K: function K(date, token, localize) {
21232      var hours = date.getUTCHours() % 12;
21233
21234      if (token === 'Ko') {
21235        return localize.ordinalNumber(hours, {
21236          unit: 'hour'
21237        });
21238      }
21239
21240      return addLeadingZeros(hours, token.length);
21241    },
21242    // Hour [1-24]
21243    k: function k(date, token, localize) {
21244      var hours = date.getUTCHours();
21245      if (hours === 0) hours = 24;
21246
21247      if (token === 'ko') {
21248        return localize.ordinalNumber(hours, {
21249          unit: 'hour'
21250        });
21251      }
21252
21253      return addLeadingZeros(hours, token.length);
21254    },
21255    // Minute
21256    m: function m(date, token, localize) {
21257      if (token === 'mo') {
21258        return localize.ordinalNumber(date.getUTCMinutes(), {
21259          unit: 'minute'
21260        });
21261      }
21262
21263      return formatters$1.m(date, token);
21264    },
21265    // Second
21266    s: function s(date, token, localize) {
21267      if (token === 'so') {
21268        return localize.ordinalNumber(date.getUTCSeconds(), {
21269          unit: 'second'
21270        });
21271      }
21272
21273      return formatters$1.s(date, token);
21274    },
21275    // Fraction of second
21276    S: function S(date, token) {
21277      return formatters$1.S(date, token);
21278    },
21279    // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
21280    X: function X(date, token, _localize, options) {
21281      var originalDate = options._originalDate || date;
21282      var timezoneOffset = originalDate.getTimezoneOffset();
21283
21284      if (timezoneOffset === 0) {
21285        return 'Z';
21286      }
21287
21288      switch (token) {
21289        // Hours and optional minutes
21290        case 'X':
21291          return formatTimezoneWithOptionalMinutes(timezoneOffset);
21292        // Hours, minutes and optional seconds without `:` delimiter
21293        // Note: neither ISO-8601 nor JavaScript supports seconds 
vendor: 6,738 bytes, lines 21293-21527
21293in timezone offsets
21294        // so this token always has the same output as `XX`
21295
21296        case 'XXXX':
21297        case 'XX':
21298          // Hours and minutes without `:` delimiter
21299          return formatTimezone(timezoneOffset);
21300        // Hours, minutes and optional seconds with `:` delimiter
21301        // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
21302        // so this token always has the same output as `XXX`
21303
21304        case 'XXXXX':
21305        case 'XXX': // Hours and minutes with `:` delimiter
21306
21307        default:
21308          return formatTimezone(timezoneOffset, ':');
21309      }
21310    },
21311    // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
21312    x: function x(date, token, _localize, options) {
21313      var originalDate = options._originalDate || date;
21314      var timezoneOffset = originalDate.getTimezoneOffset();
21315
21316      switch (token) {
21317        // Hours and optional minutes
21318        case 'x':
21319          return formatTimezoneWithOptionalMinutes(timezoneOffset);
21320        // Hours, minutes and optional seconds without `:` delimiter
21321        // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
21322        // so this token always has the same output as `xx`
21323
21324        case 'xxxx':
21325        case 'xx':
21326          // Hours and minutes without `:` delimiter
21327          return formatTimezone(timezoneOffset);
21328        // Hours, minutes and optional seconds with `:` delimiter
21329        // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
21330        // so this token always has the same output as `xxx`
21331
21332        case 'xxxxx':
21333        case 'xxx': // Hours and minutes with `:` delimiter
21334
21335        default:
21336          return formatTimezone(timezoneOffset, ':');
21337      }
21338    },
21339    // Timezone (GMT)
21340    O: function O(date, token, _localize, options) {
21341      var originalDate = options._originalDate || date;
21342      var timezoneOffset = originalDate.getTimezoneOffset();
21343
21344      switch (token) {
21345        // Short
21346        case 'O':
21347        case 'OO':
21348        case 'OOO':
21349          return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
21350        // Long
21351
21352        case 'OOOO':
21353        default:
21354          return 'GMT' + formatTimezone(timezoneOffset, ':');
21355      }
21356    },
21357    // Timezone (specific non-location)
21358    z: function z(date, token, _localize, options) {
21359      var originalDate = options._originalDate || date;
21360      var timezoneOffset = originalDate.getTimezoneOffset();
21361
21362      switch (token) {
21363        // Short
21364        case 'z':
21365        case 'zz':
21366        case 'zzz':
21367          return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
21368        // Long
21369
21370        case 'zzzz':
21371        default:
21372          return 'GMT' + formatTimezone(timezoneOffset, ':');
21373      }
21374    },
21375    // Seconds timestamp
21376    t: function t(date, token, _localize, options) {
21377      var originalDate = options._originalDate || date;
21378      var timestamp = Math.floor(originalDate.getTime() / 1000);
21379      return addLeadingZeros(timestamp, token.length);
21380    },
21381    // Milliseconds timestamp
21382    T: function T(date, token, _localize, options) {
21383      var originalDate = options._originalDate || date;
21384      var timestamp = originalDate.getTime();
21385      return addLeadingZeros(timestamp, token.length);
21386    }
21387  };
21388
21389  function formatTimezoneShort(offset, dirtyDelimiter) {
21390    var sign = offset > 0 ? '-' : '+';
21391    var absOffset = Math.abs(offset);
21392    var hours = Math.floor(absOffset / 60);
21393    var minutes = absOffset % 60;
21394
21395    if (minutes === 0) {
21396      return sign + String(hours);
21397    }
21398
21399    var delimiter = dirtyDelimiter || '';
21400    return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
21401  }
21402
21403  function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
21404    if (offset % 60 === 0) {
21405      var sign = offset > 0 ? '-' : '+';
21406      return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
21407    }
21408
21409    return formatTimezone(offset, dirtyDelimiter);
21410  }
21411
21412  function formatTimezone(offset, dirtyDelimiter) {
21413    var delimiter = dirtyDelimiter || '';
21414    var sign = offset > 0 ? '-' : '+';
21415    var absOffset = Math.abs(offset);
21416    var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
21417    var minutes = addLeadingZeros(absOffset % 60, 2);
21418    return sign + hours + delimiter + minutes;
21419  }
21420
21421  function dateLongFormatter(pattern, formatLong) {
21422    switch (pattern) {
21423      case 'P':
21424        return formatLong.date({
21425          width: 'short'
21426        });
21427
21428      case 'PP':
21429        return formatLong.date({
21430          width: 'medium'
21431        });
21432
21433      case 'PPP':
21434        return formatLong.date({
21435          width: 'long'
21436        });
21437
21438      case 'PPPP':
21439      default:
21440        return formatLong.date({
21441          width: 'full'
21442        });
21443    }
21444  }
21445
21446  function timeLongFormatter(pattern, formatLong) {
21447    switch (pattern) {
21448      case 'p':
21449        return formatLong.time({
21450          width: 'short'
21451        });
21452
21453      case 'pp':
21454        return formatLong.time({
21455          width: 'medium'
21456        });
21457
21458      case 'ppp':
21459        return formatLong.time({
21460          width: 'long'
21461        });
21462
21463      case 'pppp':
21464      default:
21465        return formatLong.time({
21466          width: 'full'
21467        });
21468    }
21469  }
21470
21471  function dateTimeLongFormatter(pattern, formatLong) {
21472    var matchResult = pattern.match(/(P+)(p+)?/);
21473    var datePattern = matchResult[1];
21474    var timePattern = matchResult[2];
21475
21476    if (!timePattern) {
21477      return dateLongFormatter(pattern, formatLong);
21478    }
21479
21480    var dateTimeFormat;
21481
21482    switch (datePattern) {
21483      case 'P':
21484        dateTimeFormat = formatLong.dateTime({
21485          width: 'short'
21486        });
21487        break;
21488
21489      case 'PP':
21490        dateTimeFormat = formatLong.dateTime({
21491          width: 'medium'
21492        });
21493        break;
21494
21495      case 'PPP':
21496        dateTimeFormat = formatLong.dateTime({
21497          width: 'long'
21498        });
21499        break;
21500
21501      case 'PPPP':
21502      default:
21503        dateTimeFormat = formatLong.dateTime({
21504          width: 'full'
21505        });
21506        break;
21507    }
21508
21509    return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong));
21510  }
21511
21512  var longFormatters = {
21513    p: timeLongFormatter,
21514    P: dateTimeLongFormatter
21515  };
21516
21517  var protectedDayOfYearTokens = ['D', 'DD'];
21518  var protectedWeekYearTokens = ['YY', 'YYYY'];
21519  function isProtectedDayOfYearToken(token) {
21520    return protectedDayOfYearTokens.indexOf(token) !== -1;
21521  }
21522  function isProtectedWeekYearToken(token) {
21523    return protectedWeekYearTokens.indexOf(token) !== -1;
21524  }
21525  function throwProtectedError(token, format, input) {
21526    if (token === 'YYYY') {
21527      throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format, "`) for formatting years to the input `").
21527concat(input, "`; see: https://git.io/fxCyr"));
21528    } else if (token === 'YY') {
21529      throw new RangeError("Use `yy` instead of `YY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://git.io/fxCyr"));
21530    } else if (token === 'D') {
21531      throw new RangeError("Use `d` instead of `D` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://git.io/fxCyr"));
21532    } else if (token === 'DD') {
21533      throw new RangeError("Use `dd` instead of `DD` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://git.io/fxCyr"));
21534    }
21535  }
21536
21537  // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
21538  //   (one of the certain letters followed by `o`)
21539  // - (\w)\1* matches any sequences of the same letter
21540  // - '' matches two quote characters in a row
21541  // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
21542  //   except a single quote symbol, which ends the sequence.
21543  //   Two quote characters do not end the sequence.
21544  //   If there is no matching single quote
21545  //   then the sequence will continue until the end of the string.
21546  // - . matches any single character unmatched by previous parts of the RegExps
21547
21548  var formattingTokensRegExp$1 = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also
21549  // sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
21550
21551  var longFormattingTokensRegExp$1 = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
21552  var escapedStringRegExp$1 = /^'([^]*?)'?$/;
21553  var doubleQuoteRegExp$1 = /''/g;
21554  var unescapedLatinCharacterRegExp$1 = /[a-zA-Z]/;
21555  /**
21556   * @name format
21557   * @category Common Helpers
21558   * @summary Format the date.
21559   *
21560   * @description
21561   * Return the formatted date string in the given format. The result may vary by locale.
21562   *
21563   * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
21564   * > See: https://git.io/fxCyr
21565   *
21566   * The characters wrapped between two single quotes characters (') are escaped.
21567   * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
21568   * (see the last example)
21569   *
21570   * Format of the string is based on Unicode Technical Standard #35:
21571   * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
21572   * with a few additions (see note 7 below the table).
21573   *
21574   * Accepted patterns:
21575   * | Unit                            | Pattern | Result examples                   | Notes |
21576   * |---------------------------------|---------|-----------------------------------|-------|
21577   * | Era                             | G..GGG  | AD, BC                            |       |
21578   * |                                 | GGGG    | Anno Domini, Before Christ        | 2     |
21579   * |                                 | GGGGG   | A, B                              |       |
21580   * | Calendar year                   | y       | 44, 1, 1900, 2017                 | 5     |
21581   * |                                 | yo      | 44th, 1st, 0th, 17th              | 5,7   |
21582   * |                                 | yy      | 44, 01, 00, 17                    | 5     |
21583   * |                                 | yyy     | 044, 001, 1900, 2017              | 5     |
21584   * |                                 | yyyy    | 0044, 0001, 1900, 2017            | 5     |
21585   * |                                 | yyyyy   | ...                               | 3,5   |
21586   * | Local week-numbering year       | Y       | 44, 1, 1900, 2017                 | 5     |
21587   * |                                 | Yo      | 44th, 1st, 1900th, 2017th         | 5,7   |
21588   * |                                 | YY      | 44, 01, 00, 17                    | 5,8   |
21589   * |                                 | YYY     | 044, 001, 1900, 2017              | 5     |
21590   * |                                 | YYYY    | 0044, 0001, 1900, 2017            | 5,8   |
21591   * |                                 | YYYYY   | ...                               | 3,5   |
21592   * | ISO week-numbering year         | R       | -43, 0, 1, 1900, 2017             | 5,7   |
21593   * |                                 | RR      | -43, 00, 01, 1900, 2017           | 5,7   |
21594   * |                                 | RRR     | -043, 000, 001, 1900, 2017        | 5,7   |
21595   * |                                 | RRRR    | -0043, 0000, 0001, 1900, 2017     | 5,7   |
21596   * |                                 | RRRRR   | ...                               | 3,5,7 |
21597   * | Extended year                   | u       | -43, 0, 1, 1900, 2017             | 5     |
21598   * |                                 | uu      | -43, 01, 1900, 2017               | 5     |
21599   * |                                 | uuu     | -043, 001, 1900, 2017             | 5     |
21600   * |                                 | uuuu    | -0043, 0001, 1900, 2017           | 5     |
21601   * |                                 | uuuuu   | ...                               | 3,5   |
21602   * | Quarter (formatting)            | Q       | 1, 2, 3, 4                        |       |
21603   * |                                 | Qo      | 1st, 2nd, 3rd, 4th                | 7     |
21604   * |                                 | QQ      | 01, 02, 03, 04                    |       |
21605   * |                                 | QQQ     | Q1, Q2, Q3, Q4                    |       |
21606   * |                                 | QQQQ    | 1st quarter, 2nd quarter, ...     | 2     |
21607   * |                                 | QQQQQ   | 1, 2, 3, 4                        | 4     |
21608   * | Quarter (stand-alone)           | q       | 1, 2, 3, 4                        |       |
21609   * |                                 | qo      | 1st, 2nd, 3rd, 4th                | 7     |
21610   * |                                 | qq      | 01, 02, 03, 04                    |       |
21611   * |                                 | qqq     | Q1, Q2, Q3, Q4                    |       |
21612   * |                                 | qqqq    | 1st quarter, 2nd quarter, ...     | 2     |
21613   * |                                 | qqqqq   | 1, 2, 3, 4                        | 4     |
21614   * | Month (formatting)              | M       | 1, 2, ..., 12                     |       |
21615   * |                                 | Mo      | 1st, 2nd, ..., 12th               | 7     |
21616   * |                                 | MM      | 01, 02, ..., 12                   |       |
21617   * |                                 | MMM     | Jan, Feb, ..., Dec                |       |
21618   * |                                 | MMMM    | January, February, ..., December  | 2     |
21619   * |                                 | MMMMM   | J, F, ..., D                      |       |
21620   * | Month (stand-alone)             | L       | 1, 2, ..., 12                     |       |
21621   * |                                 | Lo      | 1st, 2nd, ..., 12th               | 7     |
21622   * |                                 | LL      | 01, 02, ..., 12                   |       |
21623   * |                                 | LLL     | Jan, Feb, ..., Dec                |       |
21624   * |                                 | LLLL    | January, February, ..., December  | 2     |
21625   * |                                 | LLLLL   | J, F, ..., D                      |       |
21626   * | Local week of year              | w       | 1, 2, ..., 53                     |       |
21627   * |                                 | wo      | 1st, 2nd, ..., 53th               | 7     |
21628   * |                                 | ww      | 01, 02, ..., 53                   |       |
21629   * | ISO week of year                | I       | 1, 2, ..., 53                     | 7     |
21630   * |                                 | Io      | 1st, 2nd, ..., 53th               | 7     |
21631   * |                                 | II      | 01, 02, ..., 53                   | 7     |
21632   * | Day of month                    | d       | 1, 2, ..., 31                     |       |
21633   * |                                 | do      | 1st, 2nd, ..., 31st               | 7     |
21634   * |                                 | dd      | 01, 02, ..., 31                   |       |
21635   * | Day of year                     | D       | 1, 2, ..., 365, 366               | 9     |
21636   * |                                 | Do      | 1st, 2nd, ..., 365th, 366th       | 7     |
21637   * |                                 | DD      | 01, 02, ..., 365, 366             | 9     |
21638   * |                                 | DDD     | 001, 002, ..., 365, 366           |       |
21639   * |                                 | DDDD    | ...                               | 3     |
21640   * | Day of week (formatting)        | E..EEE  | Mon, Tue, Wed, ..., Sun           |       |
21641   * |                                 | EEEE    | Monday, Tuesday, ..., Sunday      | 2     |
21642   * |                                 | EEEEE   | M, T, W, T, F, S, S               |       |
21643   * |                                 | EEEEEE  | Mo, Tu, We, Th, Fr, Su, Sa        |       |
21644   * | ISO day of week (formatting)    | i       | 1, 2, 3, ..., 7                   | 7     |
21645   * |                                 | io      | 1st, 2nd, ..., 7th                | 7     |
21646   * |                                 | ii      | 01, 02, ..., 
2164607                   | 7     |
21647   * |                                 | iii     | Mon, Tue, Wed, ..., Sun           | 7     |
21648   * |                                 | iiii    | Monday, Tuesday, ..., Sunday      | 2,7   |
21649   * |                                 | iiiii   | M, T, W, T, F, S, S               | 7     |
21650   * |                                 | iiiiii  | Mo, Tu, We, Th, Fr, Su, Sa        | 7     |
21651   * | Local day of week (formatting)  | e       | 2, 3, 4, ..., 1                   |       |
21652   * |                                 | eo      | 2nd, 3rd, ..., 1st                | 7     |
21653   * |                                 | ee      | 02, 03, ..., 01                   |       |
21654   * |                                 | eee     | Mon, Tue, Wed, ..., Sun           |       |
21655   * |                                 | eeee    | Monday, Tuesday, ..., Sunday      | 2     |
21656   * |                                 | eeeee   | M, T, W, T, F, S, S               |       |
21657   * |                                 | eeeeee  | Mo, Tu, We, Th, Fr, Su, Sa        |       |
21658   * | Local day of week (stand-alone) | c       | 2, 3, 4, ..., 1                   |       |
21659   * |                                 | co      | 2nd, 3rd, ..., 1st                | 7     |
21660   * |                                 | cc      | 02, 03, ..., 01                   |       |
21661   * |                                 | ccc     | Mon, Tue, Wed, ..., Sun           |       |
21662   * |                                 | cccc    | Monday, Tuesday, ..., Sunday      | 2     |
21663   * |                                 | ccccc   | M, T, W, T, F, S, S               |       |
21664   * |                                 | cccccc  | Mo, Tu, We, Th, Fr, Su, Sa        |       |
21665   * | AM, PM                          | a..aa   | AM, PM                            |       |
21666   * |                                 | aaa     | am, pm                            |       |
21667   * |                                 | aaaa    | a.m., p.m.                        | 2     |
21668   * |                                 | aaaaa   | a, p                              |       |
21669   * | AM, PM, noon, midnight          | b..bb   | AM, PM, noon, midnight            |       |
21670   * |                                 | bbb     | am, pm, noon, midnight            |       |
21671   * |                                 | bbbb    | a.m., p.m., noon, midnight        | 2     |
21672   * |                                 | bbbbb   | a, p, n, mi                       |       |
21673   * | Flexible day period             | B..BBB  | at night, in the morning, ...     |       |
21674   * |                                 | BBBB    | at night, in the morning, ...     | 2     |
21675   * |                                 | BBBBB   | at night, in the morning, ...     |       |
21676   * | Hour [1-12]                     | h       | 1, 2, ..., 11, 12                 |       |
21677   * |                                 | ho      | 1st, 2nd, ..., 11th, 12th         | 7     |
21678   * |                                 | hh      | 01, 02, ..., 11, 12               |       |
21679   * | Hour [0-23]                     | H       | 0, 1, 2, ..., 23                  |       |
21680   * |                                 | Ho      | 0th, 1st, 2nd, ..., 23rd          | 7     |
21681   * |                                 | HH      | 00, 01, 02, ..., 23               |       |
21682   * | Hour [0-11]                     | K       | 1, 2, ..., 11, 0                  |       |
21683   * |                                 | Ko      | 1st, 2nd, ..., 11th, 0th          | 7     |
21684   * |                                 | KK      | 01, 02, ..., 11, 00               |       |
21685   * | Hour [1-24]                     | k       | 24, 1, 2, ..., 23                 |       |
21686   * |                                 | ko      | 24th, 1st, 2nd, ..., 23rd         | 7     |
21687   * |                                 | kk      | 24, 01, 02, ..., 23               |       |
21688   * | Minute                          | m       | 0, 1, ..., 59                     |       |
21689   * |                                 | mo      | 0th, 1st, ..., 59th               | 7     |
21690   * |                                 | mm      | 00, 01, ..., 59                   |       |
21691   * | Second                          | s       | 0, 1, ..., 59                     |       |
21692   * |                                 | so      | 0th, 1st, ..., 59th               | 7     |
21693   * |                                 | ss      | 00, 01, ..., 59                   |       |
21694   * | Fraction of second              | S       | 0, 1, ..., 9                      |       |
21695   * |                                 | SS      | 00, 01, ..., 99                   |       |
21696   * |                                 | SSS     | 000, 001, ..., 999 
vendor: 12,268 bytes, lines 21696-21913
21696               |       |
21697   * |                                 | SSSS    | ...                               | 3     |
21698   * | Timezone (ISO-8601 w/ Z)        | X       | -08, +0530, Z                     |       |
21699   * |                                 | XX      | -0800, +0530, Z                   |       |
21700   * |                                 | XXX     | -08:00, +05:30, Z                 |       |
21701   * |                                 | XXXX    | -0800, +0530, Z, +123456          | 2     |
21702   * |                                 | XXXXX   | -08:00, +05:30, Z, +12:34:56      |       |
21703   * | Timezone (ISO-8601 w/o Z)       | x       | -08, +0530, +00                   |       |
21704   * |                                 | xx      | -0800, +0530, +0000               |       |
21705   * |                                 | xxx     | -08:00, +05:30, +00:00            | 2     |
21706   * |                                 | xxxx    | -0800, +0530, +0000, +123456      |       |
21707   * |                                 | xxxxx   | -08:00, +05:30, +00:00, +12:34:56 |       |
21708   * | Timezone (GMT)                  | O...OOO | GMT-8, GMT+5:30, GMT+0            |       |
21709   * |                                 | OOOO    | GMT-08:00, GMT+05:30, GMT+00:00   | 2     |
21710   * | Timezone (specific non-locat.)  | z...zzz | GMT-8, GMT+5:30, GMT+0            | 6     |
21711   * |                                 | zzzz    | GMT-08:00, GMT+05:30, GMT+00:00   | 2,6   |
21712   * | Seconds timestamp               | t       | 512969520                         | 7     |
21713   * |                                 | tt      | ...                               | 3,7   |
21714   * | Milliseconds timestamp          | T       | 512969520900                      | 7     |
21715   * |                                 | TT      | ...                               | 3,7   |
21716   * | Long localized date             | P       | 04/29/1453                        | 7     |
21717   * |                                 | PP      | Apr 29, 1453                      | 7     |
21718   * |                                 | PPP     | April 29th, 1453                  | 7     |
21719   * |                                 | PPPP    | Friday, April 29th, 1453          | 2,7   |
21720   * | Long localized time             | p       | 12:00 AM                          | 7     |
21721   * |                                 | pp      | 12:00:00 AM                       | 7     |
21722   * |                                 | ppp     | 12:00:00 AM GMT+2                 | 7     |
21723   * |                                 | pppp    | 12:00:00 AM GMT+02:00             | 2,7   |
21724   * | Combination of date and time    | Pp      | 04/29/1453, 12:00 AM              | 7     |
21725   * |                                 | PPpp    | Apr 29, 1453, 12:00:00 AM         | 7     |
21726   * |                                 | PPPppp  | April 29th, 1453 at ...           | 7     |
21727   * |                                 | PPPPpppp| Friday, April 29th, 1453 at ...   | 2,7   |
21728   * Notes:
21729   * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
21730   *    are the same as "stand-alone" units, but are different in some languages.
21731   *    "Formatting" units are declined according to the rules of the language
21732   *    in the context of a date. "Stand-alone" units are always nominative singular:
21733   *
21734   *    `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
21735   *
21736   *    `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
21737   *
21738   * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
21739   *    the single quote characters (see below).
21740   *    If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
21741   *    the output will be the same as default pattern for this unit, usually
21742   *    the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
21743   *    are marked with "2" in the last column of the table.
21744   *
21745   *    `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
21746   *
21747   *    `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
21748   *
21749   *    `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
21750   *
21751   *    `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
21752   *
21753   *    `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
21754   *
21755   * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
21756   *    The output will be padded with zeros to match the length of the pattern.
21757   *
21758   *    `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
21759   *
21760   * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
21761   *    These tokens represent the shortest form of the quarter.
21762   *
21763   * 5. The main difference between `y` and `u` patterns are B.C. years:
21764   *
21765   *    | Year | `y` | `u` |
21766   *    |------|-----|-----|
21767   *    | AC 1 |   1 |   1 |
21768   *    | BC 1 |   1 |   0 |
21769   *    | BC 2 |   2 |  -1 |
21770   *
21771   *    Also `yy` always returns the last two digits of a year,
21772   *    while `uu` pads single digit years to 2 characters and returns other years unchanged:
21773   *
21774   *    | Year | `yy` | `uu` |
21775   *    |------|------|------|
21776   *    | 1    |   01 |   01 |
21777   *    | 14   |   14 |   14 |
21778   *    | 376  |   76 |  376 |
21779   *    | 1453 |   53 | 1453 |
21780   *
21781   *    The same difference is true for local and ISO week-numbering years (`Y` and `R`),
21782   *    except local week-numbering years are dependent on `options.weekStartsOn`
21783   *    and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear}
21784   *    and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}).
21785   *
21786   * 6. Specific non-location timezones are currently unavailable in `date-fns`,
21787   *    so right now these tokens fall back to GMT timezones.
21788   *
21789   * 7. These patterns are not in the Unicode Technical Standard #35:
21790   *    - `i`: ISO day of week
21791   *    - `I`: ISO week of year
21792   *    - `R`: ISO week-numbering year
21793   *    - `t`: seconds timestamp
21794   *    - `T`: milliseconds timestamp
21795   *    - `o`: ordinal number modifier
21796   *    - `P`: long localized date
21797   *    - `p`: long localized time
21798   *
21799   * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
21800   *    You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://git.io/fxCyr
21801   *
21802   * 9. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month.
21803   *    You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://git.io/fxCyr
21804   *
21805   * ### v2.0.0 breaking changes:
21806   *
21807   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
21808   *
21809   * - The second argument is now required for the sake of explicitness.
21810   *
21811   *   ```javascript
21812   *   // Before v2.0.0
21813   *   format(new Date(2016, 0, 1))
21814   *
21815   *   // v2.0.0 onward
21816   *   format(new Date(2016, 0, 1), "yyyy-MM-dd'T'HH:mm:ss.SSSxxx")
21817   *   ```
21818   *
21819   * - New format string API for `format` function
21820   *   which is based on [Unicode Technical Standard #35](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table).
21821   *   See [this post](https://blog.date-fns.org/post/unicode-tokens-in-date-fns-v2-sreatyki91jg) for more details.
21822   *
21823   * - Characters are now escaped using single quote symbols (`'`) instead of square brackets.
21824   *
21825   * @param {Date|Number} date - the original date
21826   * @param {String} format - the string of tokens
21827   * @param {Object} [options] - an object with options.
21828   * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
21829   * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
21830   * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is
21831   * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`;
21832   *   see: https://git.io/fxCyr
21833   * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`;
21834   *   see: https://git.io/fxCyr
21835   * @returns {String} the formatted date string
21836   * @throws {TypeError} 2 arguments required
21837   * @throws {RangeError} `date` must not be Invalid Date
21838   * @throws {RangeError} `options.locale` must contain `localize` property
21839   * @throws {RangeError} `options.locale` must contain `formatLong` property
21840   * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
21841   * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
21842   * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://git.io/fxCyr
21843   * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://git.io/fxCyr
21844   * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://git.io/fxCyr
21845   * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://git.io/fxCyr
21846   * @throws {RangeError} format string contains an unescaped latin alphabet character
21847   *
21848   * @example
21849   * // Represent 11 February 2014 in middle-endian format:
21850   * var result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
21851   * //=> '02/11/2014'
21852   *
21853   * @example
21854   * // Represent 2 July 2014 in Esperanto:
21855   * import { eoLocale } from 'date-fns/locale/eo'
21856   * var result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
21857   *   locale: eoLocale
21858   * })
21859   * //=> '2-a de julio 2014'
21860   *
21861   * @example
21862   * // Escape string by single quote characters:
21863   * var result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
21864   * //=> "3 o'clock"
21865   */
21866
21867  function format(dirtyDate, dirtyFormatStr, dirtyOptions) {
21868    requiredArgs(2, arguments);
21869    var formatStr = String(dirtyFormatStr);
21870    var options = dirtyOptions || {};
21871    var locale$1 = options.locale || locale;
21872    var localeFirstWeekContainsDate = locale$1.options && locale$1.options.firstWeekContainsDate;
21873    var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate);
21874    var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
21875
21876    if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
21877      throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
21878    }
21879
21880    var localeWeekStartsOn = locale$1.options && locale$1.options.weekStartsOn;
21881    var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
21882    var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
21883
21884    if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
21885      throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
21886    }
21887
21888    if (!locale$1.localize) {
21889      throw new RangeError('locale must contain localize property');
21890    }
21891
21892    if (!locale$1.formatLong) {
21893      throw new RangeError('locale must contain formatLong property');
21894    }
21895
21896    var originalDate = toDate(dirtyDate);
21897
21898    if (!isValid(originalDate)) {
21899      throw new RangeError('Invalid time value');
21900    } // Convert the date in system timezone to the same date in UTC+00:00 timezone.
21901    // This ensures that when UTC functions will be implemented, locales will be compatible with them.
21902    // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
21903
21904
21905    var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
21906    var utcDate = subMilliseconds(originalDate, timezoneOffset);
21907    var formatterOptions = {
21908      firstWeekContainsDate: firstWeekContainsDate,
21909      weekStartsOn: weekStartsOn,
21910      locale: locale$1,
21911      _originalDate: originalDate
21912    };
21913    var result = formatStr.match(longFormattingTokensRegExp
vendor: 51,065 bytes, lines 21913-23547
21913$1).map(function (substring) {
21914      var firstCharacter = substring[0];
21915
21916      if (firstCharacter === 'p' || firstCharacter === 'P') {
21917        var longFormatter = longFormatters[firstCharacter];
21918        return longFormatter(substring, locale$1.formatLong, formatterOptions);
21919      }
21920
21921      return substring;
21922    }).join('').match(formattingTokensRegExp$1).map(function (substring) {
21923      // Replace two single quote characters with one single quote character
21924      if (substring === "''") {
21925        return "'";
21926      }
21927
21928      var firstCharacter = substring[0];
21929
21930      if (firstCharacter === "'") {
21931        return cleanEscapedString$1(substring);
21932      }
21933
21934      var formatter = formatters[firstCharacter];
21935
21936      if (formatter) {
21937        if (!options.useAdditionalWeekYearTokens && isProtectedWeekYearToken(substring)) {
21938          throwProtectedError(substring, dirtyFormatStr, dirtyDate);
21939        }
21940
21941        if (!options.useAdditionalDayOfYearTokens && isProtectedDayOfYearToken(substring)) {
21942          throwProtectedError(substring, dirtyFormatStr, dirtyDate);
21943        }
21944
21945        return formatter(utcDate, substring, locale$1.localize, formatterOptions);
21946      }
21947
21948      if (firstCharacter.match(unescapedLatinCharacterRegExp$1)) {
21949        throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`');
21950      }
21951
21952      return substring;
21953    }).join('');
21954    return result;
21955  }
21956
21957  function cleanEscapedString$1(input) {
21958    return input.match(escapedStringRegExp$1)[1].replace(doubleQuoteRegExp$1, "'");
21959  }
21960
21961  function assign(target, dirtyObject) {
21962    if (target == null) {
21963      throw new TypeError('assign requires that input parameter not be null or undefined');
21964    }
21965
21966    dirtyObject = dirtyObject || {};
21967
21968    for (var property in dirtyObject) {
21969      if (dirtyObject.hasOwnProperty(property)) {
21970        target[property] = dirtyObject[property];
21971      }
21972    }
21973
21974    return target;
21975  }
21976
21977  // See issue: https://github.com/date-fns/date-fns/issues/376
21978
21979  function setUTCDay(dirtyDate, dirtyDay, dirtyOptions) {
21980    requiredArgs(2, arguments);
21981    var options = dirtyOptions || {};
21982    var locale = options.locale;
21983    var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
21984    var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
21985    var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
21986
21987    if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
21988      throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
21989    }
21990
21991    var date = toDate(dirtyDate);
21992    var day = toInteger(dirtyDay);
21993    var currentDay = date.getUTCDay();
21994    var remainder = day % 7;
21995    var dayIndex = (remainder + 7) % 7;
21996    var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay;
21997    date.setUTCDate(date.getUTCDate() + diff);
21998    return date;
21999  }
22000
22001  // See issue: https://github.com/date-fns/date-fns/issues/376
22002
22003  function setUTCISODay(dirtyDate, dirtyDay) {
22004    requiredArgs(2, arguments);
22005    var day = toInteger(dirtyDay);
22006
22007    if (day % 7 === 0) {
22008      day = day - 7;
22009    }
22010
22011    var weekStartsOn = 1;
22012    var date = toDate(dirtyDate);
22013    var currentDay = date.getUTCDay();
22014    var remainder = day % 7;
22015    var dayIndex = (remainder + 7) % 7;
22016    var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay;
22017    date.setUTCDate(date.getUTCDate() + diff);
22018    return date;
22019  }
22020
22021  // See issue: https://github.com/date-fns/date-fns/issues/376
22022
22023  function setUTCISOWeek(dirtyDate, dirtyISOWeek) {
22024    requiredArgs(2, arguments);
22025    var date = toDate(dirtyDate);
22026    var isoWeek = toInteger(dirtyISOWeek);
22027    var diff = getUTCISOWeek(date) - isoWeek;
22028    date.setUTCDate(date.getUTCDate() - diff * 7);
22029    return date;
22030  }
22031
22032  // See issue: https://github.com/date-fns/date-fns/issues/376
22033
22034  function setUTCWeek(dirtyDate, dirtyWeek, options) {
22035    requiredArgs(2, arguments);
22036    var date = toDate(dirtyDate);
22037    var week = toInteger(dirtyWeek);
22038    var diff = getUTCWeek(date, options) - week;
22039    date.setUTCDate(date.getUTCDate() - diff * 7);
22040    return date;
22041  }
22042
22043  var MILLISECONDS_IN_HOUR$1 = 3600000;
22044  var MILLISECONDS_IN_MINUTE$1 = 60000;
22045  var MILLISECONDS_IN_SECOND = 1000;
22046  var numericPatterns = {
22047    month: /^(1[0-2]|0?\d)/,
22048    // 0 to 12
22049    date: /^(3[0-1]|[0-2]?\d)/,
22050    // 0 to 31
22051    dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,
22052    // 0 to 366
22053    week: /^(5[0-3]|[0-4]?\d)/,
22054    // 0 to 53
22055    hour23h: /^(2[0-3]|[0-1]?\d)/,
22056    // 0 to 23
22057    hour24h: /^(2[0-4]|[0-1]?\d)/,
22058    // 0 to 24
22059    hour11h: /^(1[0-1]|0?\d)/,
22060    // 0 to 11
22061    hour12h: /^(1[0-2]|0?\d)/,
22062    // 0 to 12
22063    minute: /^[0-5]?\d/,
22064    // 0 to 59
22065    second: /^[0-5]?\d/,
22066    // 0 to 59
22067    singleDigit: /^\d/,
22068    // 0 to 9
22069    twoDigits: /^\d{1,2}/,
22070    // 0 to 99
22071    threeDigits: /^\d{1,3}/,
22072    // 0 to 999
22073    fourDigits: /^\d{1,4}/,
22074    // 0 to 9999
22075    anyDigitsSigned: /^-?\d+/,
22076    singleDigitSigned: /^-?\d/,
22077    // 0 to 9, -0 to -9
22078    twoDigitsSigned: /^-?\d{1,2}/,
22079    // 0 to 99, -0 to -99
22080    threeDigitsSigned: /^-?\d{1,3}/,
22081    // 0 to 999, -0 to -999
22082    fourDigitsSigned: /^-?\d{1,4}/ // 0 to 9999, -0 to -9999
22083
22084  };
22085  var timezonePatterns = {
22086    basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/,
22087    basic: /^([+-])(\d{2})(\d{2})|Z/,
22088    basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,
22089    extended: /^([+-])(\d{2}):(\d{2})|Z/,
22090    extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/
22091  };
22092
22093  function parseNumericPattern(pattern, string, valueCallback) {
22094    var matchResult = string.match(pattern);
22095
22096    if (!matchResult) {
22097      return null;
22098    }
22099
22100    var value = parseInt(matchResult[0], 10);
22101    return {
22102      value: valueCallback ? valueCallback(value) : value,
22103      rest: string.slice(matchResult[0].length)
22104    };
22105  }
22106
22107  function parseTimezonePattern(pattern, string) {
22108    var matchResult = string.match(pattern);
22109
22110    if (!matchResult) {
22111      return null;
22112    } // Input is 'Z'
22113
22114
22115    if (matchResult[0] === 'Z') {
22116      return {
22117        value: 0,
22118        rest: string.slice(1)
22119      };
22120    }
22121
22122    var sign = matchResult[1] === '+' ? 1 : -1;
22123    var hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0;
22124    var minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0;
22125    var seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0;
22126    return {
22127      value: sign * (hours * MILLISECONDS_IN_HOUR$1 + minutes * MILLISECONDS_IN_MINUTE$1 + seconds * MILLISECONDS_IN_SECOND),
22128      rest: string.slice(matchResult[0].length)
22129    };
22130  }
22131
22132  function parseAnyDigitsSigned(string, valueCallback) {
22133    return parseNumericPattern(numericPatterns.anyDigitsSigned, string, valueCallback);
22134  }
22135
22136  function parseNDigits(n, string, valueCallback) {
22137    switch (n) {
22138      case 1:
22139        return parseNumericPattern(numericPatterns.singleDigit, string, valueCallback);
22140
22141      case 2:
22142        return parseNumericPattern(numericPatterns.twoDigits, string, valueCallback);
22143
22144      case 3:
22145        return parseNumericPattern(numericPatterns.threeDigits, string, valueCallback);
22146
22147      case 4:
22148        return parseNumericPattern(numericPatterns.fourDigits, string, valueCallback);
22149
22150      default:
22151        return parseNumericPattern(new RegExp('^\\d{1,' + n + '}'), string, valueCallback);
22152    }
22153  }
22154
22155  function parseNDigitsSigned(n, string, valueCallback) {
22156    switch (n) {
22157      case 1:
22158        return parseNumericPattern(numericPatterns.singleDigitSigned, string, valueCallback);
22159
22160      case 2:
22161        return parseNumericPattern(numericPatterns.twoDigitsSigned, string, valueCallback);
22162
22163      case 3:
22164        return parseNumericPattern(numericPatterns.threeDigitsSigned, string, valueCallback);
22165
22166      case 4:
22167        return parseNumericPattern(numericPatterns.fourDigitsSigned, string, valueCallback);
22168
22169      default:
22170        return parseNumericPattern(new RegExp('^-?\\d{1,' + n + '}'), string, valueCallback);
22171    }
22172  }
22173
22174  function dayPeriodEnumToHours(enumValue) {
22175    switch (enumValue) {
22176      case 'morning':
22177        return 4;
22178
22179      case 'evening':
22180        return 17;
22181
22182      case 'pm':
22183      case 'noon':
22184      case 'afternoon':
22185        return 12;
22186
22187      case 'am':
22188      case 'midnight':
22189      case 'night':
22190      default:
22191        return 0;
22192    }
22193  }
22194
22195  function normalizeTwoDigitYear(twoDigitYear, currentYear) {
22196    var isCommonEra = currentYear > 0; // Absolute number of the current year:
22197    // 1 -> 1 AC
22198    // 0 -> 1 BC
22199    // -1 -> 2 BC
22200
22201    var absCurrentYear = isCommonEra ? currentYear : 1 - currentYear;
22202    var result;
22203
22204    if (absCurrentYear <= 50) {
22205      result = twoDigitYear || 100;
22206    } else {
22207      var rangeEnd = absCurrentYear + 50;
22208      var rangeEndCentury = Math.floor(rangeEnd / 100) * 100;
22209      var isPreviousCentury = twoDigitYear >= rangeEnd % 100;
22210      result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0);
22211    }
22212
22213    return isCommonEra ? result : 1 - result;
22214  }
22215
22216  var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
22217  var DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // User for validation
22218
22219  function isLeapYearIndex$1(year) {
22220    return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
22221  }
22222  /*
22223   * |     | Unit                           |     | Unit                           |
22224   * |-----|--------------------------------|-----|--------------------------------|
22225   * |  a  | AM, PM                         |  A* | Milliseconds in day            |
22226   * |  b  | AM, PM, noon, midnight         |  B  | Flexible day period            |
22227   * |  c  | Stand-alone local day of week  |  C* | Localized hour w/ day period   |
22228   * |  d  | Day of month                   |  D  | Day of year                    |
22229   * |  e  | Local day of week              |  E  | Day of week                    |
22230   * |  f  |                                |  F* | Day of week in month           |
22231   * |  g* | Modified Julian day            |  G  | Era                            |
22232   * |  h  | Hour [1-12]                    |  H  | Hour [0-23]                    |
22233   * |  i! | ISO day of week                |  I! | ISO week of year               |
22234   * |  j* | Localized hour w/ day period   |  J* | Localized hour w/o day period  |
22235   * |  k  | Hour [1-24]                    |  K  | Hour [0-11]                    |
22236   * |  l* | (deprecated)                   |  L  | Stand-alone month              |
22237   * |  m  | Minute                         |  M  | Month                          |
22238   * |  n  |                                |  N  |                                |
22239   * |  o! | Ordinal number modifier        |  O* | Timezone (GMT)                 |
22240   * |  p  |                                |  P  |                                |
22241   * |  q  | Stand-alone quarter            |  Q  | Quarter                        |
22242   * |  r* | Related Gregorian year         |  R! | ISO week-numbering year        |
22243   * |  s  | Second                         |  S  | Fraction of second             |
22244   * |  t! | Seconds timestamp              |  T! | Milliseconds timestamp         |
22245   * |  u  | Extended year                  |  U* | Cyclic year                    |
22246   * |  v* | Timezone (generic non-locat.)  |  V* | Timezone (location)            |
22247   * |  w  | Local week of year             |  W* | Week of month                  |
22248   * |  x  | Timezone (ISO-8601 w/o Z)      |  X  | Timezone (ISO-8601)            |
22249   * |  y  | Year (abs)                     |  Y  | Local week-numbering year      |
22250   * |  z* | Timezone (specific non-locat.) |  Z* | Timezone (aliases)             |
22251   *
22252   * Letters marked by * are not implemented but reserved by Unicode standard.
22253   *
22254   * Letters marked by ! are non-standard, but implemented by date-fns:
22255   * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs)
22256   * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
22257   *   i.e. 7 for Sunday, 1 for Monday, etc.
22258   * - `I` is ISO week of year, as opposed to `w` which is local week of year.
22259   * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
22260   *   `R` is supposed to be used in conjunction with `I` and `i`
22261   *   for universal ISO week-numbering date, whereas
22262   *   `Y` is supposed to be used in conjunction with `w` and `e`
22263   *   for week-numbering date specific to the locale.
22264   */
22265
22266
22267  var parsers = {
22268    // Era
22269    G: {
22270      priority: 140,
22271      parse: function parse(string, token, match, _options) {
22272        switch (token) {
22273          // AD, BC
22274          case 'G':
22275          case 'GG':
22276          case 'GGG':
22277            return match.era(string, {
22278              width: 'abbreviated'
22279            }) || match.era(string, {
22280              width: 'narrow'
22281            });
22282          // A, B
22283
22284          case 'GGGGG':
22285            return match.era(string, {
22286              width: 'narrow'
22287            });
22288          // Anno Domini, Before Christ
22289
22290          case 'GGGG':
22291          default:
22292            return match.era(string, {
22293              width: 'wide'
22294            }) || match.era(string, {
22295              width: 'abbreviated'
22296            }) || match.era(string, {
22297              width: 'narrow'
22298            });
22299        }
22300      },
22301      set: function set(date, flags, value, _options) {
22302        flags.era = value;
22303        date.setUTCFullYear(value, 0, 1);
22304        date.setUTCHours(0, 0, 0, 0);
22305        return date;
22306      },
22307      incompatibleTokens: ['R', 'u', 't', 'T']
22308    },
22309    // Year
22310    y: {
22311      // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
22312      // | Year     |     y | yy |   yyy |  yyyy | yyyyy |
22313      // |----------|-------|----|-------|-------|-------|
22314      // | AD 1     |     1 | 01 |   001 |  0001 | 00001 |
22315      // | AD 12    |    12 | 12 |   012 |  0012 | 00012 |
22316      // | AD 123   |   123 | 23 |   123 |  0123 | 00123 |
22317      // | AD 1234  |  1234 | 34 |  1234 |  1234 | 01234 |
22318      // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
22319      priority: 130,
22320      parse: function parse(string, token, match, _options) {
22321        var valueCallback = function valueCallback(year) {
22322          return {
22323            year: year,
22324            isTwoDigitYear: token === 'yy'
22325          };
22326        };
22327
22328        switch (token) {
22329          case 'y':
22330            return parseNDigits(4, string, valueCallback);
22331
22332          case 'yo':
22333            return match.ordinalNumber(string, {
22334              unit: 'year',
22335              valueCallback: valueCallback
22336            });
22337
22338          default:
22339            return parseNDigits(token.length, string, valueCallback);
22340        }
22341      },
22342      validate: function validate(_date, value, _options) {
22343        return value.isTwoDigitYear || value.year > 0;
22344      },
22345      set: function set(date, flags, value, _options) {
22346        var currentYear = date.getUTCFullYear();
22347
22348        if (value.isTwoDigitYear) {
22349          var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear);
22350          date.setUTCFullYear(normalizedTwoDigitYear, 0, 1);
22351          date.setUTCHours(0, 0, 0, 0);
22352          return date;
22353        }
22354
22355        var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year;
22356        date.setUTCFullYear(year, 0, 1);
22357        date.setUTCHours(0, 0, 0, 0);
22358        return date;
22359      },
22360      incompatibleTokens: ['Y', 'R', 'u', 'w', 'I', 'i', 'e', 'c', 't', 'T']
22361    },
22362    // Local week-numbering year
22363    Y: {
22364      priority: 130,
22365      parse: function parse(string, token, match, _options) {
22366        var valueCallback = function valueCallback(year) {
22367          return {
22368            year: year,
22369            isTwoDigitYear: token === 'YY'
22370          };
22371        };
22372
22373        switch (token) {
22374          case 'Y':
22375            return parseNDigits(4, string, valueCallback);
22376
22377          case 'Yo':
22378            return match.ordinalNumber(string, {
22379              unit: 'year',
22380              valueCallback: valueCallback
22381            });
22382
22383          default:
22384            return parseNDigits(token.length, string, valueCallback);
22385        }
22386      },
22387      validate: function validate(_date, value, _options) {
22388        return value.isTwoDigitYear || value.year > 0;
22389      },
22390      set: function set(date, flags, value, options) {
22391        var currentYear = getUTCWeekYear(date, options);
22392
22393        if (value.isTwoDigitYear) {
22394          var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear);
22395          date.setUTCFullYear(normalizedTwoDigitYear, 0, options.firstWeekContainsDate);
22396          date.setUTCHours(0, 0, 0, 0);
22397          return startOfUTCWeek(date, options);
22398        }
22399
22400        var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year;
22401        date.setUTCFullYear(year, 0, options.firstWeekContainsDate);
22402        date.setUTCHours(0, 0, 0, 0);
22403        return startOfUTCWeek(date, options);
22404      },
22405      incompatibleTokens: ['y', 'R', 'u', 'Q', 'q', 'M', 'L', 'I', 'd', 'D', 'i', 't', 'T']
22406    },
22407    // ISO week-numbering year
22408    R: {
22409      priority: 130,
22410      parse: function parse(string, token, _match, _options) {
22411        if (token === 'R') {
22412          return parseNDigitsSigned(4, string);
22413        }
22414
22415        return parseNDigitsSigned(token.length, string);
22416      },
22417      set: function set(_date, _flags, value, _options) {
22418        var firstWeekOfYear = new Date(0);
22419        firstWeekOfYear.setUTCFullYear(value, 0, 4);
22420        firstWeekOfYear.setUTCHours(0, 0, 0, 0);
22421        return startOfUTCISOWeek(firstWeekOfYear);
22422      },
22423      incompatibleTokens: ['G', 'y', 'Y', 'u', 'Q', 'q', 'M', 'L', 'w', 'd', 'D', 'e', 'c', 't', 'T']
22424    },
22425    // Extended year
22426    u: {
22427      priority: 130,
22428      parse: function parse(string, token, _match, _options) {
22429        if (token === 'u') {
22430          return parseNDigitsSigned(4, string);
22431        }
22432
22433        return parseNDigitsSigned(token.length, string);
22434      },
22435      set: function set(date, _flags, value, _options) {
22436        date.setUTCFullYear(value, 0, 1);
22437        date.setUTCHours(0, 0, 0, 0);
22438        return date;
22439      },
22440      incompatibleTokens: ['G', 'y', 'Y', 'R', 'w', 'I', 'i', 'e', 'c', 't', 'T']
22441    },
22442    // Quarter
22443    Q: {
22444      priority: 120,
22445      parse: function parse(string, token, match, _options) {
22446        switch (token) {
22447          // 1, 2, 3, 4
22448          case 'Q':
22449          case 'QQ':
22450            // 01, 02, 03, 04
22451            return parseNDigits(token.length, string);
22452          // 1st, 2nd, 3rd, 4th
22453
22454          case 'Qo':
22455            return match.ordinalNumber(string, {
22456              unit: 'quarter'
22457            });
22458          // Q1, Q2, Q3, Q4
22459
22460          case 'QQQ':
22461            return match.quarter(string, {
22462              width: 'abbreviated',
22463              context: 'formatting'
22464            }) || match.quarter(string, {
22465              width: 'narrow',
22466              context: 'formatting'
22467            });
22468          // 1, 2, 3, 4 (narrow quarter; could be not numerical)
22469
22470          case 'QQQQQ':
22471            return match.quarter(string, {
22472              width: 'narrow',
22473              context: 'formatting'
22474            });
22475          // 1st quarter, 2nd quarter, ...
22476
22477          case 'QQQQ':
22478          default:
22479            return match.quarter(string, {
22480              width: 'wide',
22481              context: 'formatting'
22482            }) || match.quarter(string, {
22483              width: 'abbreviated',
22484              context: 'formatting'
22485            }) || match.quarter(string, {
22486              width: 'narrow',
22487              context: 'formatting'
22488            });
22489        }
22490      },
22491      validate: function validate(_date, value, _options) {
22492        return value >= 1 && value <= 4;
22493      },
22494      set: function set(date, _flags, value, _options) {
22495        date.setUTCMonth((value - 1) * 3, 1);
22496        date.setUTCHours(0, 0, 0, 0);
22497        return date;
22498      },
22499      incompatibleTokens: ['Y', 'R', 'q', 'M', 'L', 'w', 'I', 'd', 'D', 'i', 'e', 'c', 't', 'T']
22500    },
22501    // Stand-alone quarter
22502    q: {
22503      priority: 120,
22504      parse: function parse(string, token, match, _options) {
22505        switch (token) {
22506          // 1, 2, 3, 4
22507          case 'q':
22508          case 'qq':
22509            // 01, 02, 03, 04
22510            return parseNDigits(token.length, string);
22511          // 1st, 2nd, 3rd, 4th
22512
22513          case 'qo':
22514            return match.ordinalNumber(string, {
22515              unit: 'quarter'
22516            });
22517          // Q1, Q2, Q3, Q4
22518
22519          case 'qqq':
22520            return match.quarter(string, {
22521              width: 'abbreviated',
22522              context: 'standalone'
22523            }) || match.quarter(string, {
22524              width: 'narrow',
22525              context: 'standalone'
22526            });
22527          // 1, 2, 3, 4 (narrow quarter; could be not numerical)
22528
22529          case 'qqqqq':
22530            return match.quarter(string, {
22531              width: 'narrow',
22532              context: 'standalone'
22533            });
22534          // 1st quarter, 2nd quarter, ...
22535
22536          case 'qqqq':
22537          default:
22538            return match.quarter(string, {
22539              width: 'wide',
22540              context: 'standalone'
22541            }) || match.quarter(string, {
22542              width: 'abbreviated',
22543              context: 'standalone'
22544            }) || match.quarter(string, {
22545              width: 'narrow',
22546              context: 'standalone'
22547            });
22548        }
22549      },
22550      validate: function validate(_date, value, _options) {
22551        return value >= 1 && value <= 4;
22552      },
22553      set: function set(date, _flags, value, _options) {
22554        date.setUTCMonth((value - 1) * 3, 1);
22555        date.setUTCHours(0, 0, 0, 0);
22556        return date;
22557      },
22558      incompatibleTokens: ['Y', 'R', 'Q', 'M', 'L', 'w', 'I', 'd', 'D', 'i', 'e', 'c', 't', 'T']
22559    },
22560    // Month
22561    M: {
22562      priority: 110,
22563      parse: function parse(string, token, match, _options) {
22564        var valueCallback = function valueCallback(value) {
22565          return value - 1;
22566        };
22567
22568        switch (token) {
22569          // 1, 2, ..., 12
22570          case 'M':
22571            return parseNumericPattern(numericPatterns.month, string, valueCallback);
22572          // 01, 02, ..., 12
22573
22574          case 'MM':
22575            return parseNDigits(2, string, valueCallback);
22576          // 1st, 2nd, ..., 12th
22577
22578          case 'Mo':
22579            return match.ordinalNumber(string, {
22580              unit: 'month',
22581              valueCallback: valueCallback
22582            });
22583          // Jan, Feb, ..., Dec
22584
22585          case 'MMM':
22586            return match.month(string, {
22587              width: 'abbreviated',
22588              context: 'formatting'
22589            }) || match.month(string, {
22590              width: 'narrow',
22591              context: 'formatting'
22592            });
22593          // J, F, ..., D
22594
22595          case 'MMMMM':
22596            return match.month(string, {
22597              width: 'narrow',
22598              context: 'formatting'
22599            });
22600          // January, February, ..., December
22601
22602          case 'MMMM':
22603          default:
22604            return match.month(string, {
22605              width: 'wide',
22606              context: 'formatting'
22607            }) || match.month(string, {
22608              width: 'abbreviated',
22609              context: 'formatting'
22610            }) || match.month(string, {
22611              width: 'narrow',
22612              context: 'formatting'
22613            });
22614        }
22615      },
22616      validate: function validate(_date, value, _options) {
22617        return value >= 0 && value <= 11;
22618      },
22619      set: function set(date, _flags, value, _options) {
22620        date.setUTCMonth(value, 1);
22621        date.setUTCHours(0, 0, 0, 0);
22622        return date;
22623      },
22624      incompatibleTokens: ['Y', 'R', 'q', 'Q', 'L', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']
22625    },
22626    // Stand-alone month
22627    L: {
22628      priority: 110,
22629      parse: function parse(string, token, match, _options) {
22630        var valueCallback = function valueCallback(value) {
22631          return value - 1;
22632        };
22633
22634        switch (token) {
22635          // 1, 2, ..., 12
22636          case 'L':
22637            return parseNumericPattern(numericPatterns.month, string, valueCallback);
22638          // 01, 02, ..., 12
22639
22640          case 'LL':
22641            return parseNDigits(2, string, valueCallback);
22642          // 1st, 2nd, ..., 12th
22643
22644          case 'Lo':
22645            return match.ordinalNumber(string, {
22646              unit: 'month',
22647              valueCallback: valueCallback
22648            });
22649          // Jan, Feb, ..., Dec
22650
22651          case 'LLL':
22652            return match.month(string, {
22653              width: 'abbreviated',
22654              context: 'standalone'
22655            }) || match.month(string, {
22656              width: 'narrow',
22657              context: 'standalone'
22658            });
22659          // J, F, ..., D
22660
22661          case 'LLLLL':
22662            return match.month(string, {
22663              width: 'narrow',
22664              context: 'standalone'
22665            });
22666          // January, February, ..., December
22667
22668          case 'LLLL':
22669          default:
22670            return match.month(string, {
22671              width: 'wide',
22672              context: 'standalone'
22673            }) || match.month(string, {
22674              width: 'abbreviated',
22675              context: 'standalone'
22676            }) || match.month(string, {
22677              width: 'narrow',
22678              context: 'standalone'
22679            });
22680        }
22681      },
22682      validate: function validate(_date, value, _options) {
22683        return value >= 0 && value <= 11;
22684      },
22685      set: function set(date, _flags, value, _options) {
22686        date.setUTCMonth(value, 1);
22687        date.setUTCHours(0, 0, 0, 0);
22688        return date;
22689      },
22690      incompatibleTokens: ['Y', 'R', 'q', 'Q', 'M', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']
22691    },
22692    // Local week of year
22693    w: {
22694      priority: 100,
22695      parse: function parse(string, token, match, _options) {
22696        switch (token) {
22697          case 'w':
22698            return parseNumericPattern(numericPatterns.week, string);
22699
22700          case 'wo':
22701            return match.ordinalNumber(string, {
22702              unit: 'week'
22703            });
22704
22705          default:
22706            return parseNDigits(token.length, string);
22707        }
22708      },
22709      validate: function validate(_date, value, _options) {
22710        return value >= 1 && value <= 53;
22711      },
22712      set: function set(date, _flags, value, options) {
22713        return startOfUTCWeek(setUTCWeek(date, value, options), options);
22714      },
22715      incompatibleTokens: ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'i', 't', 'T']
22716    },
22717    // ISO week of year
22718    I: {
22719      priority: 100,
22720      parse: function parse(string, token, match, _options) {
22721        switch (token) {
22722          case 'I':
22723            return parseNumericPattern(numericPatterns.week, string);
22724
22725          case 'Io':
22726            return match.ordinalNumber(string, {
22727              unit: 'week'
22728            });
22729
22730          default:
22731            return parseNDigits(token.length, string);
22732        }
22733      },
22734      validate: function validate(_date, value, _options) {
22735        return value >= 1 && value <= 53;
22736      },
22737      set: function set(date, _flags, value, options) {
22738        return startOfUTCISOWeek(setUTCISOWeek(date, value, options), options);
22739      },
22740      incompatibleTokens: ['y', 'Y', 'u', 'q', 'Q', 'M', 'L', 'w', 'd', 'D', 'e', 'c', 't', 'T']
22741    },
22742    // Day of the month
22743    d: {
22744      priority: 90,
22745      subPriority: 1,
22746      parse: function parse(string, token, match, _options) {
22747        switch (token) {
22748          case 'd':
22749            return parseNumericPattern(numericPatterns.date, string);
22750
22751          case 'do':
22752            return match.ordinalNumber(string, {
22753              unit: 'date'
22754            });
22755
22756          default:
22757            return parseNDigits(token.length, string);
22758        }
22759      },
22760      validate: function validate(date, value, _options) {
22761        var year = date.getUTCFullYear();
22762        var isLeapYear = isLeapYearIndex$1(year);
22763        var month = date.getUTCMonth();
22764
22765        if (isLeapYear) {
22766          return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month];
22767        } else {
22768          return value >= 1 && value <= DAYS_IN_MONTH[month];
22769        }
22770      },
22771      set: function set(date, _flags, value, _options) {
22772        date.setUTCDate(value);
22773        date.setUTCHours(0, 0, 0, 0);
22774        return date;
22775      },
22776      incompatibleTokens: ['Y', 'R', 'q', 'Q', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']
22777    },
22778    // Day of year
22779    D: {
22780      priority: 90,
22781      subPriority: 1,
22782      parse: function parse(string, token, match, _options) {
22783        switch (token) {
22784          case 'D':
22785          case 'DD':
22786            return parseNumericPattern(numericPatterns.dayOfYear, string);
22787
22788          case 'Do':
22789            return match.ordinalNumber(string, {
22790              unit: 'date'
22791            });
22792
22793          default:
22794            return parseNDigits(token.length, string);
22795        }
22796      },
22797      validate: function validate(date, value, _options) {
22798        var year = date.getUTCFullYear();
22799        var isLeapYear = isLeapYearIndex$1(year);
22800
22801        if (isLeapYear) {
22802          return value >= 1 && value <= 366;
22803        } else {
22804          return value >= 1 && value <= 365;
22805        }
22806      },
22807      set: function set(date, _flags, value, _options) {
22808        date.setUTCMonth(0, value);
22809        date.setUTCHours(0, 0, 0, 0);
22810        return date;
22811      },
22812      incompatibleTokens: ['Y', 'R', 'q', 'Q', 'M', 'L', 'w', 'I', 'd', 'E', 'i', 'e', 'c', 't', 'T']
22813    },
22814    // Day of week
22815    E: {
22816      priority: 90,
22817      parse: function parse(string, token, match, _options) {
22818        switch (token) {
22819          // Tue
22820          case 'E':
22821          case 'EE':
22822          case 'EEE':
22823            return match.day(string, {
22824              width: 'abbreviated',
22825              context: 'formatting'
22826            }) || match.day(string, {
22827              width: 'short',
22828              context: 'formatting'
22829            }) || match.day(string, {
22830              width: 'narrow',
22831              context: 'formatting'
22832            });
22833          // T
22834
22835          case 'EEEEE':
22836            return match.day(string, {
22837              width: 'narrow',
22838              context: 'formatting'
22839            });
22840          // Tu
22841
22842          case 'EEEEEE':
22843            return match.day(string, {
22844              width: 'short',
22845              context: 'formatting'
22846            }) || match.day(string, {
22847              width: 'narrow',
22848              context: 'formatting'
22849            });
22850          // Tuesday
22851
22852          case 'EEEE':
22853          default:
22854            return match.day(string, {
22855              width: 'wide',
22856              context: 'formatting'
22857            }) || match.day(string, {
22858              width: 'abbreviated',
22859              context: 'formatting'
22860            }) || match.day(string, {
22861              width: 'short',
22862              context: 'formatting'
22863            }) || match.day(string, {
22864              width: 'narrow',
22865              context: 'formatting'
22866            });
22867        }
22868      },
22869      validate: function validate(_date, value, _options) {
22870        return value >= 0 && value <= 6;
22871      },
22872      set: function set(date, _flags, value, options) {
22873        date = setUTCDay(date, value, options);
22874        date.setUTCHours(0, 0, 0, 0);
22875        return date;
22876      },
22877      incompatibleTokens: ['D', 'i', 'e', 'c', 't', 'T']
22878    },
22879    // Local day of week
22880    e: {
22881      priority: 90,
22882      parse: function parse(string, token, match, options) {
22883        var valueCallback = function valueCallback(value) {
22884          var wholeWeekDays = Math.floor((value - 1) / 7) * 7;
22885          return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays;
22886        };
22887
22888        switch (token) {
22889          // 3
22890          case 'e':
22891          case 'ee':
22892            // 03
22893            return parseNDigits(token.length, string, valueCallback);
22894          // 3rd
22895
22896          case 'eo':
22897            return match.ordinalNumber(string, {
22898              unit: 'day',
22899              valueCallback: valueCallback
22900            });
22901          // Tue
22902
22903          case 'eee':
22904            return match.day(string, {
22905              width: 'abbreviated',
22906              context: 'formatting'
22907            }) || match.day(string, {
22908              width: 'short',
22909              context: 'formatting'
22910            }) || match.day(string, {
22911              width: 'narrow',
22912              context: 'formatting'
22913            });
22914          // T
22915
22916          case 'eeeee':
22917            return match.day(string, {
22918              width: 'narrow',
22919              context: 'formatting'
22920            });
22921          // Tu
22922
22923          case 'eeeeee':
22924            return match.day(string, {
22925              width: 'short',
22926              context: 'formatting'
22927            }) || match.day(string, {
22928              width: 'narrow',
22929              context: 'formatting'
22930            });
22931          // Tuesday
22932
22933          case 'eeee':
22934          default:
22935            return match.day(string, {
22936              width: 'wide',
22937              context: 'formatting'
22938            }) || match.day(string, {
22939              width: 'abbreviated',
22940              context: 'formatting'
22941            }) || match.day(string, {
22942              width: 'short',
22943              context: 'formatting'
22944            }) || match.day(string, {
22945              width: 'narrow',
22946              context: 'formatting'
22947            });
22948        }
22949      },
22950      validate: function validate(_date, value, _options) {
22951        return value >= 0 && value <= 6;
22952      },
22953      set: function set(date, _flags, value, options) {
22954        date = setUTCDay(date, value, options);
22955        date.setUTCHours(0, 0, 0, 0);
22956        return date;
22957      },
22958      incompatibleTokens: ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'E', 'i', 'c', 't', 'T']
22959    },
22960    // Stand-alone local day of week
22961    c: {
22962      priority: 90,
22963      parse: function parse(string, token, match, options) {
22964        var valueCallback = function valueCallback(value) {
22965          var wholeWeekDays = Math.floor((value - 1) / 7) * 7;
22966          return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays;
22967        };
22968
22969        switch (token) {
22970          // 3
22971          case 'c':
22972          case 'cc':
22973            // 03
22974            return parseNDigits(token.length, string, valueCallback);
22975          // 3rd
22976
22977          case 'co':
22978            return match.ordinalNumber(string, {
22979              unit: 'day',
22980              valueCallback: valueCallback
22981            });
22982          // Tue
22983
22984          case 'ccc':
22985            return match.day(string, {
22986              width: 'abbreviated',
22987              context: 'standalone'
22988            }) || match.day(string, {
22989              width: 'short',
22990              context: 'standalone'
22991            }) || match.day(string, {
22992              width: 'narrow',
22993              context: 'standalone'
22994            });
22995          // T
22996
22997          case 'ccccc':
22998            return match.day(string, {
22999              width: 'narrow',
23000              context: 'standalone'
23001            });
23002          // Tu
23003
23004          case 'cccccc':
23005            return match.day(string, {
23006              width: 'short',
23007              context: 'standalone'
23008            }) || match.day(string, {
23009              width: 'narrow',
23010              context: 'standalone'
23011            });
23012          // Tuesday
23013
23014          case 'cccc':
23015          default:
23016            return match.day(string, {
23017              width: 'wide',
23018              context: 'standalone'
23019            }) || match.day(string, {
23020              width: 'abbreviated',
23021              context: 'standalone'
23022            }) || match.day(string, {
23023              width: 'short',
23024              context: 'standalone'
23025            }) || match.day(string, {
23026              width: 'narrow',
23027              context: 'standalone'
23028            });
23029        }
23030      },
23031      validate: function validate(_date, value, _options) {
23032        return value >= 0 && value <= 6;
23033      },
23034      set: function set(date, _flags, value, options) {
23035        date = setUTCDay(date, value, options);
23036        date.setUTCHours(0, 0, 0, 0);
23037        return date;
23038      },
23039      incompatibleTokens: ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'E', 'i', 'e', 't', 'T']
23040    },
23041    // ISO day of week
23042    i: {
23043      priority: 90,
23044      parse: function parse(string, token, match, _options) {
23045        var valueCallback = function valueCallback(value) {
23046          if (value === 0) {
23047            return 7;
23048          }
23049
23050          return value;
23051        };
23052
23053        switch (token) {
23054          // 2
23055          case 'i':
23056          case 'ii':
23057            // 02
23058            return parseNDigits(token.length, string);
23059          // 2nd
23060
23061          case 'io':
23062            return match.ordinalNumber(string, {
23063              unit: 'day'
23064            });
23065          // Tue
23066
23067          case 'iii':
23068            return match.day(string, {
23069              width: 'abbreviated',
23070              context: 'formatting',
23071              valueCallback: valueCallback
23072            }) || match.day(string, {
23073              width: 'short',
23074              context: 'formatting',
23075              valueCallback: valueCallback
23076            }) || match.day(string, {
23077              width: 'narrow',
23078              context: 'formatting',
23079              valueCallback: valueCallback
23080            });
23081          // T
23082
23083          case 'iiiii':
23084            return match.day(string, {
23085              width: 'narrow',
23086              context: 'formatting',
23087              valueCallback: valueCallback
23088            });
23089          // Tu
23090
23091          case 'iiiiii':
23092            return match.day(string, {
23093              width: 'short',
23094              context: 'formatting',
23095              valueCallback: valueCallback
23096            }) || match.day(string, {
23097              width: 'narrow',
23098              context: 'formatting',
23099              valueCallback: valueCallback
23100            });
23101          // Tuesday
23102
23103          case 'iiii':
23104          default:
23105            return match.day(string, {
23106              width: 'wide',
23107              context: 'formatting',
23108              valueCallback: valueCallback
23109            }) || match.day(string, {
23110              width: 'abbreviated',
23111              context: 'formatting',
23112              valueCallback: valueCallback
23113            }) || match.day(string, {
23114              width: 'short',
23115              context: 'formatting',
23116              valueCallback: valueCallback
23117            }) || match.day(string, {
23118              width: 'narrow',
23119              context: 'formatting',
23120              valueCallback: valueCallback
23121            });
23122        }
23123      },
23124      validate: function validate(_date, value, _options) {
23125        return value >= 1 && value <= 7;
23126      },
23127      set: function set(date, _flags, value, options) {
23128        date = setUTCISODay(date, value, options);
23129        date.setUTCHours(0, 0, 0, 0);
23130        return date;
23131      },
23132      incompatibleTokens: ['y', 'Y', 'u', 'q', 'Q', 'M', 'L', 'w', 'd', 'D', 'E', 'e', 'c', 't', 'T']
23133    },
23134    // AM or PM
23135    a: {
23136      priority: 80,
23137      parse: function parse(string, token, match, _options) {
23138        switch (token) {
23139          case 'a':
23140          case 'aa':
23141          case 'aaa':
23142            return match.dayPeriod(string, {
23143              width: 'abbreviated',
23144              context: 'formatting'
23145            }) || match.dayPeriod(string, {
23146              width: 'narrow',
23147              context: 'formatting'
23148            });
23149
23150          case 'aaaaa':
23151            return match.dayPeriod(string, {
23152              width: 'narrow',
23153              context: 'formatting'
23154            });
23155
23156          case 'aaaa':
23157          default:
23158            return match.dayPeriod(string, {
23159              width: 'wide',
23160              context: 'formatting'
23161            }) || match.dayPeriod(string, {
23162              width: 'abbreviated',
23163              context: 'formatting'
23164            }) || match.dayPeriod(string, {
23165              width: 'narrow',
23166              context: 'formatting'
23167            });
23168        }
23169      },
23170      set: function set(date, _flags, value, _options) {
23171        date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0);
23172        return date;
23173      },
23174      incompatibleTokens: ['b', 'B', 'H', 'K', 'k', 't', 'T']
23175    },
23176    // AM, PM, midnight
23177    b: {
23178      priority: 80,
23179      parse: function parse(string, token, match, _options) {
23180        switch (token) {
23181          case 'b':
23182          case 'bb':
23183          case 'bbb':
23184            return match.dayPeriod(string, {
23185              width: 'abbreviated',
23186              context: 'formatting'
23187            }) || match.dayPeriod(string, {
23188              width: 'narrow',
23189              context: 'formatting'
23190            });
23191
23192          case 'bbbbb':
23193            return match.dayPeriod(string, {
23194              width: 'narrow',
23195              context: 'formatting'
23196            });
23197
23198          case 'bbbb':
23199          default:
23200            return match.dayPeriod(string, {
23201              width: 'wide',
23202              context: 'formatting'
23203            }) || match.dayPeriod(string, {
23204              width: 'abbreviated',
23205              context: 'formatting'
23206            }) || match.dayPeriod(string, {
23207              width: 'narrow',
23208              context: 'formatting'
23209            });
23210        }
23211      },
23212      set: function set(date, _flags, value, _options) {
23213        date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0);
23214        return date;
23215      },
23216      incompatibleTokens: ['a', 'B', 'H', 'K', 'k', 't', 'T']
23217    },
23218    // in the morning, in the afternoon, in the evening, at night
23219    B: {
23220      priority: 80,
23221      parse: function parse(string, token, match, _options) {
23222        switch (token) {
23223          case 'B':
23224          case 'BB':
23225          case 'BBB':
23226            return match.dayPeriod(string, {
23227              width: 'abbreviated',
23228              context: 'formatting'
23229            }) || match.dayPeriod(string, {
23230              width: 'narrow',
23231              context: 'formatting'
23232            });
23233
23234          case 'BBBBB':
23235            return match.dayPeriod(string, {
23236              width: 'narrow',
23237              context: 'formatting'
23238            });
23239
23240          case 'BBBB':
23241          default:
23242            return match.dayPeriod(string, {
23243              width: 'wide',
23244              context: 'formatting'
23245            }) || match.dayPeriod(string, {
23246              width: 'abbreviated',
23247              context: 'formatting'
23248            }) || match.dayPeriod(string, {
23249              width: 'narrow',
23250              context: 'formatting'
23251            });
23252        }
23253      },
23254      set: function set(date, _flags, value, _options) {
23255        date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0);
23256        return date;
23257      },
23258      incompatibleTokens: ['a', 'b', 't', 'T']
23259    },
23260    // Hour [1-12]
23261    h: {
23262      priority: 70,
23263      parse: function parse(string, token, match, _options) {
23264        switch (token) {
23265          case 'h':
23266            return parseNumericPattern(numericPatterns.hour12h, string);
23267
23268          case 'ho':
23269            return match.ordinalNumber(string, {
23270              unit: 'hour'
23271            });
23272
23273          default:
23274            return parseNDigits(token.length, string);
23275        }
23276      },
23277      validate: function validate(_date, value, _options) {
23278        return value >= 1 && value <= 12;
23279      },
23280      set: function set(date, _flags, value, _options) {
23281        var isPM = date.getUTCHours() >= 12;
23282
23283        if (isPM && value < 12) {
23284          date.setUTCHours(value + 12, 0, 0, 0);
23285        } else if (!isPM && value === 12) {
23286          date.setUTCHours(0, 0, 0, 0);
23287        } else {
23288          date.setUTCHours(value, 0, 0, 0);
23289        }
23290
23291        return date;
23292      },
23293      incompatibleTokens: ['H', 'K', 'k', 't', 'T']
23294    },
23295    // Hour [0-23]
23296    H: {
23297      priority: 70,
23298      parse: function parse(string, token, match, _options) {
23299        switch (token) {
23300          case 'H':
23301            return parseNumericPattern(numericPatterns.hour23h, string);
23302
23303          case 'Ho':
23304            return match.ordinalNumber(string, {
23305              unit: 'hour'
23306            });
23307
23308          default:
23309            return parseNDigits(token.length, string);
23310        }
23311      },
23312      validate: function validate(_date, value, _options) {
23313        return value >= 0 && value <= 23;
23314      },
23315      set: function set(date, _flags, value, _options) {
23316        date.setUTCHours(value, 0, 0, 0);
23317        return date;
23318      },
23319      incompatibleTokens: ['a', 'b', 'h', 'K', 'k', 't', 'T']
23320    },
23321    // Hour [0-11]
23322    K: {
23323      priority: 70,
23324      parse: function parse(string, token, match, _options) {
23325        switch (token) {
23326          case 'K':
23327            return parseNumericPattern(numericPatterns.hour11h, string);
23328
23329          case 'Ko':
23330            return match.ordinalNumber(string, {
23331              unit: 'hour'
23332            });
23333
23334          default:
23335            return parseNDigits(token.length, string);
23336        }
23337      },
23338      validate: function validate(_date, value, _options) {
23339        return value >= 0 && value <= 11;
23340      },
23341      set: function set(date, _flags, value, _options) {
23342        var isPM = date.getUTCHours() >= 12;
23343
23344        if (isPM && value < 12) {
23345          date.setUTCHours(value + 12, 0, 0, 0);
23346        } else {
23347          date.setUTCHours(value, 0, 0, 0);
23348        }
23349
23350        return date;
23351      },
23352      incompatibleTokens: ['a', 'b', 'h', 'H', 'k', 't', 'T']
23353    },
23354    // Hour [1-24]
23355    k: {
23356      priority: 70,
23357      parse: function parse(string, token, match, _options) {
23358        switch (token) {
23359          case 'k':
23360            return parseNumericPattern(numericPatterns.hour24h, string);
23361
23362          case 'ko':
23363            return match.ordinalNumber(string, {
23364              unit: 'hour'
23365            });
23366
23367          default:
23368            return parseNDigits(token.length, string);
23369        }
23370      },
23371      validate: function validate(_date, value, _options) {
23372        return value >= 1 && value <= 24;
23373      },
23374      set: function set(date, _flags, value, _options) {
23375        var hours = value <= 24 ? value % 24 : value;
23376        date.setUTCHours(hours, 0, 0, 0);
23377        return date;
23378      },
23379      incompatibleTokens: ['a', 'b', 'h', 'H', 'K', 't', 'T']
23380    },
23381    // Minute
23382    m: {
23383      priority: 60,
23384      parse: function parse(string, token, match, _options) {
23385        switch (token) {
23386          case 'm':
23387            return parseNumericPattern(numericPatterns.minute, string);
23388
23389          case 'mo':
23390            return match.ordinalNumber(string, {
23391              unit: 'minute'
23392            });
23393
23394          default:
23395            return parseNDigits(token.length, string);
23396        }
23397      },
23398      validate: function validate(_date, value, _options) {
23399        return value >= 0 && value <= 59;
23400      },
23401      set: function set(date, _flags, value, _options) {
23402        date.setUTCMinutes(value, 0, 0);
23403        return date;
23404      },
23405      incompatibleTokens: ['t', 'T']
23406    },
23407    // Second
23408    s: {
23409      priority: 50,
23410      parse: function parse(string, token, match, _options) {
23411        switch (token) {
23412          case 's':
23413            return parseNumericPattern(numericPatterns.second, string);
23414
23415          case 'so':
23416            return match.ordinalNumber(string, {
23417              unit: 'second'
23418            });
23419
23420          default:
23421            return parseNDigits(token.length, string);
23422        }
23423      },
23424      validate: function validate(_date, value, _options) {
23425        return value >= 0 && value <= 59;
23426      },
23427      set: function set(date, _flags, value, _options) {
23428        date.setUTCSeconds(value, 0);
23429        return date;
23430      },
23431      incompatibleTokens: ['t', 'T']
23432    },
23433    // Fraction of second
23434    S: {
23435      priority: 30,
23436      parse: function parse(string, token, _match, _options) {
23437        var valueCallback = function valueCallback(value) {
23438          return Math.floor(value * Math.pow(10, -token.length + 3));
23439        };
23440
23441        return parseNDigits(token.length, string, valueCallback);
23442      },
23443      set: function set(date, _flags, value, _options) {
23444        date.setUTCMilliseconds(value);
23445        return date;
23446      },
23447      incompatibleTokens: ['t', 'T']
23448    },
23449    // Timezone (ISO-8601. +00:00 is `'Z'`)
23450    X: {
23451      priority: 10,
23452      parse: function parse(string, token, _match, _options) {
23453        switch (token) {
23454          case 'X':
23455            return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, string);
23456
23457          case 'XX':
23458            return parseTimezonePattern(timezonePatterns.basic, string);
23459
23460          case 'XXXX':
23461            return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, string);
23462
23463          case 'XXXXX':
23464            return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, string);
23465
23466          case 'XXX':
23467          default:
23468            return parseTimezonePattern(timezonePatterns.extended, string);
23469        }
23470      },
23471      set: function set(date, flags, value, _options) {
23472        if (flags.timestampIsSet) {
23473          return date;
23474        }
23475
23476        return new Date(date.getTime() - value);
23477      },
23478      incompatibleTokens: ['t', 'T', 'x']
23479    },
23480    // Timezone (ISO-8601)
23481    x: {
23482      priority: 10,
23483      parse: function parse(string, token, _match, _options) {
23484        switch (token) {
23485          case 'x':
23486            return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, string);
23487
23488          case 'xx':
23489            return parseTimezonePattern(timezonePatterns.basic, string);
23490
23491          case 'xxxx':
23492            return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, string);
23493
23494          case 'xxxxx':
23495            return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, string);
23496
23497          case 'xxx':
23498          default:
23499            return parseTimezonePattern(timezonePatterns.extended, string);
23500        }
23501      },
23502      set: function set(date, flags, value, _options) {
23503        if (flags.timestampIsSet) {
23504          return date;
23505        }
23506
23507        return new Date(date.getTime() - value);
23508      },
23509      incompatibleTokens: ['t', 'T', 'X']
23510    },
23511    // Seconds timestamp
23512    t: {
23513      priority: 40,
23514      parse: function parse(string, _token, _match, _options) {
23515        return parseAnyDigitsSigned(string);
23516      },
23517      set: function set(_date, _flags, value, _options) {
23518        return [new Date(value * 1000), {
23519          timestampIsSet: true
23520        }];
23521      },
23522      incompatibleTokens: '*'
23523    },
23524    // Milliseconds timestamp
23525    T: {
23526      priority: 20,
23527      parse: function parse(string, _token, _match, _options) {
23528        return parseAnyDigitsSigned(string);
23529      },
23530      set: function set(_date, _flags, value, _options) {
23531        return [new Date(value), {
23532          timestampIsSet: true
23533        }];
23534      },
23535      incompatibleTokens: '*'
23536    }
23537  };
23538
23539  var TIMEZONE_UNIT_PRIORITY = 10; // This RegExp consists of three parts separated by `|`:
23540  // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
23541  //   (one of the certain letters followed by `o`)
23542  // - (\w)\1* matches any sequences of the same letter
23543  // - '' matches two quote characters in a row
23544  // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
23545  //   except a single quote symbol, which ends the sequence.
23546  //   Two quote characters do not end the sequence.
23547  //   If there is no matching single quote
23548  //   then the sequence will continue until the end of the string.
23549  // - . matches any single character unmatched by previous parts of the RegExps
23550
23551  var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also
23552  // sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
23553
23554  var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
23555  var escapedStringRegExp = /^'([^]*?)'?$/;
23556  var doubleQuoteRegExp = /''/g;
23557  var notWhitespaceRegExp = /\S/;
23558  var unescapedLatinCharacterRegExp
vendor: 25,808 bytes, lines 23558-23926
23558 = /[a-zA-Z]/;
23559  /**
23560   * @name parse
23561   * @category Common Helpers
23562   * @summary Parse the date.
23563   *
23564   * @description
23565   * Return the date parsed from string using the given format string.
23566   *
23567   * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
23568   * > See: https://git.io/fxCyr
23569   *
23570   * The characters in the format string wrapped between two single quotes characters (') are escaped.
23571   * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
23572   *
23573   * Format of the format string is based on Unicode Technical Standard #35:
23574   * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
23575   * with a few additions (see note 5 below the table).
23576   *
23577   * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited
23578   * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception:
23579   *
23580   * ```javascript
23581   * parse('23 AM', 'HH a', new Date())
23582   * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time
23583   * ```
23584   *
23585   * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true
23586   *
23587   * Accepted format string patterns:
23588   * | Unit                            |Prior| Pattern | Result examples                   | Notes |
23589   * |---------------------------------|-----|---------|-----------------------------------|-------|
23590   * | Era                             | 140 | G..GGG  | AD, BC                            |       |
23591   * |                                 |     | GGGG    | Anno Domini, Before Christ        | 2     |
23592   * |                                 |     | GGGGG   | A, B                              |       |
23593   * | Calendar year                   | 130 | y       | 44, 1, 1900, 2017, 9999           | 4     |
23594   * |                                 |     | yo      | 44th, 1st, 1900th, 9999999th      | 4,5   |
23595   * |                                 |     | yy      | 44, 01, 00, 17                    | 4     |
23596   * |                                 |     | yyy     | 044, 001, 123, 999                | 4     |
23597   * |                                 |     | yyyy    | 0044, 0001, 1900, 2017            | 4     |
23598   * |                                 |     | yyyyy   | ...                               | 2,4   |
23599   * | Local week-numbering year       | 130 | Y       | 44, 1, 1900, 2017, 9000           | 4     |
23600   * |                                 |     | Yo      | 44th, 1st, 1900th, 9999999th      | 4,5   |
23601   * |                                 |     | YY      | 44, 01, 00, 17                    | 4,6   |
23602   * |                                 |     | YYY     | 044, 001, 123, 999                | 4     |
23603   * |                                 |     | YYYY    | 0044, 0001, 1900, 2017            | 4,6   |
23604   * |                                 |     | YYYYY   | ...                               | 2,4   |
23605   * | ISO week-numbering year         | 130 | R       | -43, 1, 1900, 2017, 9999, -9999   | 4,5   |
23606   * |                                 |     | RR      | -43, 01, 00, 17                   | 4,5   |
23607   * |                                 |     | RRR     | -043, 001, 123, 999, -999         | 4,5   |
23608   * |                                 |     | RRRR    | -0043, 0001, 2017, 9999, -9999    | 4,5   |
23609   * |                                 |     | RRRRR   | ...                               | 2,4,5 |
23610   * | Extended year                   | 130 | u       | -43, 1, 1900, 2017, 9999, -999    | 4     |
23611   * |                                 |     | uu      | -43, 01, 99, -99                  | 4     |
23612   * |                                 |     | uuu     | -043, 001, 123, 999, -999         | 4     |
23613   * |                                 |     | uuuu    | -0043, 0001, 2017, 9999, -9999    | 4     |
23614   * |                                 |     | uuuuu   | ...                               | 2,4   |
23615   * | Quarter (formatting)            | 120 | Q       | 1, 2, 3, 4                        |       |
23616   * |                                 |     | Qo      | 1st, 2nd, 3rd, 4th                | 5     |
23617   * |                                 |     | QQ      | 01, 02, 03, 04                    |       |
23618   * |                                 |     | QQQ     | Q1, Q2, Q3, Q4                    |       |
23619   * |                                 |     | QQQQ    | 1st quarter, 2nd quarter, ...     | 2     |
23620   * |                                 |     | QQQQQ   | 1, 2, 3, 4                        | 4     |
23621   * | Quarter (stand-alone)           | 120 | q       | 1, 2, 3, 4                        |       |
23622   * |                                 |     | qo      | 1st, 2nd, 3rd, 4th                | 5     |
23623   * |                                 |     | qq      | 01, 02, 03, 04                    |       |
23624   * |                                 |     | qqq     | Q1, Q2, Q3, Q4                    |       |
23625   * |                                 |     | qqqq    | 1st quarter, 2nd quarter, ...     | 2     |
23626   * |                                 |     | qqqqq   | 1, 2, 3, 4                        | 3     |
23627   * | Month (formatting)              | 110 | M       | 1, 2, ..., 12                     |       |
23628   * |                                 |     | Mo      | 1st, 2nd, ..., 12th               | 5     |
23629   * |                                 |     | MM      | 01, 02, ..., 12                   |       |
23630   * |                                 |     | MMM     | Jan, Feb, ..., Dec                |       |
23631   * |                                 |     | MMMM    | January, February, ..., December  | 2     |
23632   * |                                 |     | MMMMM   | J, F, ..., D                      |       |
23633   * | Month (stand-alone)             | 110 | L       | 1, 2, ..., 12                     |       |
23634   * |                                 |     | Lo      | 1st, 2nd, ..., 12th               | 5     |
23635   * |                                 |     | LL      | 01, 02, ..., 12                   |       |
23636   * |                                 |     | LLL     | Jan, Feb, ..., Dec                |       |
23637   * |                                 |     | LLLL    | January, February, ..., December  | 2     |
23638   * |                                 |     | LLLLL   | J, F, ..., D                      |       |
23639   * | Local week of year              | 100 | w       | 1, 2, ..., 53                     |       |
23640   * |                                 |     | wo      | 1st, 2nd, ..., 53th               | 5     |
23641   * |                                 |     | ww      | 01, 02, ..., 53                   |       |
23642   * | ISO week of year                | 100 | I       | 1, 2, ..., 53                     | 5     |
23643   * |                                 |     | Io      | 1st, 2nd, ..., 53th               | 5     |
23644   * |                                 |     | II      | 01, 02, ..., 53                   | 5     |
23645   * | Day of month                    |  90 | d       | 1, 2, ..., 31                     |       |
23646   * |                                 |     | do      | 1st, 2nd, ..., 31st               | 5     |
23647   * |                                 |     | dd      | 01, 02, ..., 31                   |       |
23648   * | Day of year                     |  90 | D       | 1, 2, ..., 365, 366               | 7     |
23649   * |                                 |     | Do      | 1st, 2nd, ..., 365th, 366th       | 5     |
23650   * |                                 |     | DD      | 01, 02, ..., 365, 366             | 7     |
23651   * |                                 |     | DDD     | 001, 002, ..., 365, 366           |       |
23652   * |                                 |     | DDDD    | ...                               | 2     |
23653   * | Day of week (formatting)        |  90 | E..EEE  | Mon, Tue, Wed, ..., Sun           |       |
23654   * |                                 |     | EEEE    | Monday, Tuesday, ..., Sunday      | 2     |
23655   * |                                 |     | EEEEE   | M, T, W, T, F, S, S               |       |
23656   * |                                 |     | EEEEEE  | Mo, Tu, We, Th, Fr, Su, Sa        |       |
23657   * | ISO day of week (formatting)    |  90 | i       | 1, 2, 3, ..., 7                   | 5     |
23658   * |                                 |     | io      | 1st, 2nd, ..., 7th                | 5     |
23659   * |                                 |     | ii      | 01, 02, ..., 07                   | 5     |
23660   * |                                 |     | iii     | Mon, Tue, Wed, ..., Sun           | 5     |
23661   * |                                 |     | iiii    | Monday, Tuesday, ..., Sunday      | 2,5   |
23662   * |                                 |     | iiiii   | M, T, W, T, F, S, S               | 5     |
23663   * |                                 |     | iiiiii  | Mo, Tu, We, Th, Fr, Su, Sa        | 5     |
23664   * | Local day of week (formatting)  |  90 | e       | 2, 3, 4, ..., 1                   |       |
23665   * |                                 |     | eo      | 2nd, 3rd, ..., 1st                | 5     |
23666   * |                                 |     | ee      | 02, 03, ..., 01                   |       |
23667   * |                                 |     | eee     | Mon, Tue, Wed, ..., Sun           |       |
23668   * |                                 |     | eeee    | Monday, Tuesday, ..., Sunday      | 2     |
23669   * |                                 |     | eeeee   | M, T, W, T, F, S, S               |       |
23670   * |                                 |     | eeeeee  | Mo, Tu, We, Th, Fr, Su, Sa        |       |
23671   * | Local day of week (stand-alone) |  90 | c       | 2, 3, 4, ..., 1                   |       |
23672   * |                                 |     | co      | 2nd, 3rd, ..., 1st                | 5     |
23673   * |                                 |     | cc      | 02, 03, ..., 01                   |       |
23674   * |                                 |     | ccc     | Mon, Tue, Wed, ..., Sun           |       |
23675   * |                                 |     | cccc    | Monday, Tuesday, ..., Sunday      | 2     |
23676   * |                                 |     | ccccc   | M, T, W, T, F, S, S               |       |
23677   * |                                 |     | cccccc  | Mo, Tu, We, Th, Fr, Su, Sa        |       |
23678   * | AM, PM                          |  80 | a..aaa  | AM, PM                            |       |
23679   * |                                 |     | aaaa    | a.m., p.m.                        | 2     |
23680   * |                                 |     | aaaaa   | a, p                              |       |
23681   * | AM, PM, noon, midnight          |  80 | b..bbb  | AM, PM, noon, midnight            |       |
23682   * |                                 |     | bbbb    | a.m., p.m., noon, midnight        | 2     |
23683   * |                                 |     | bbbbb   | a, p, n, mi                       |       |
23684   * | Flexible day period             |  80 | B..BBB  | at night, in the morning, ...     |       |
23685   * |                                 |     | BBBB    | at night, in the morning, ...     | 2     |
23686   * |                                 |     | BBBBB   | at night, in the morning, ...     |       |
23687   * | Hour [1-12]                     |  70 | h       | 1, 2, ..., 11, 12                 |       |
23688   * |                                 |     | ho      | 1st, 2nd, ..., 11th, 12th         | 5     |
23689   * |                                 |     | hh      | 01, 02, ..., 11, 12               |       |
23690   * | Hour [0-23]                     |  70 | H       | 0, 1, 2, ..., 23                  |       |
23691   * |                                 |     | Ho      | 0th, 1st, 2nd, ..., 23rd          | 5     |
23692   * |                                 |     | HH      | 00, 01, 02, ..., 23               |       |
23693   * | Hour [0-11]                     |  70 | K       | 1, 2, ..., 11, 0                  |       |
23694   * |                                 |     | Ko      | 1st, 2nd, ..., 11th, 0th          | 5     |
23695   * |                                 |     | KK      | 01, 02, ..., 11, 00               |       |
23696   * | Hour [1-24]                     |  70 | k       | 24, 1, 2, ..., 23                 |       |
23697   * |                                 |     | ko      | 24th, 1st, 2nd, ..., 23rd         | 5     |
23698   * |                                 |     | kk      | 24, 01, 02, ..., 23               |       |
23699   * | Minute                          |  60 | m       | 0, 1, ..., 59                     |       |
23700   * |                                 |     | mo      | 0th, 1st, ..., 59th               | 5     |
23701   * |                                 |     | mm      | 00, 01, ..., 59                   |       |
23702   * | Second                          |  50 | s       | 0, 1, ..., 59                     |       |
23703   * |                                 |     | so      | 0th, 1st, ..., 59th               | 5     |
23704   * |                                 |     | ss      | 00, 01, ..., 59                   |       |
23705   * | Seconds timestamp               |  40 | t       | 512969520                         |       |
23706   * |                                 |     | tt      | ...                               | 2     |
23707   * | Fraction of second              |  30 | S       | 0, 1, ..., 9                      |       |
23708   * |                                 |     | SS      | 00, 01, ..., 99                   |       |
23709   * |                                 |     | SSS     | 000, 0001, ..., 999               |       |
23710   * |                                 |     | SSSS    | ...                               | 2     |
23711   * | Milliseconds timestamp          |  20 | T       | 512969520900                      |       |
23712   * |                                 |     | TT      | ...                               | 2     |
23713   * | Timezone (ISO-8601 w/ Z)        |  10 | X       | -08, +0530, Z                     |       |
23714   * |                                 |     | XX      | -0800, +0530, Z                   |       |
23715   * |                                 |     | XXX     | -08:00, +05:30, Z                 |       |
23716   * |                                 |     | XXXX    | -0800, +0530, Z, +123456          | 2     |
23717   * |                                 |     | XXXXX   | -08:00, +05:30, Z, +12:34:56      |       |
23718   * | Timezone (ISO-8601 w/o Z)       |  10 | x       | -08, +0530, +00                   |       |
23719   * |                                 |     | xx      | -0800, +0530, +0000               |       |
23720   * |                                 |     | xxx     | -08:00, +05:30, +00:00            | 2     |
23721   * |                                 |     | xxxx    | -0800, +0530, +0000, +123456      |       |
23722   * |                                 |     | xxxxx   | -08:00, +05:30, +00:00, +12:34:56 |       |
23723   * | Long localized date             |  NA | P       | 05/29/1453                        | 5,8   |
23724   * |                                 |     | PP      | May 29, 1453                      |       |
23725   * |                                 |     | PPP     | May 29th, 1453                    |       |
23726   * |                                 |     | PPPP    | Sunday, May 29th, 1453            | 2,5,8 |
23727   * | Long localized time             |  NA | p       | 12:00 AM                          | 5,8   |
23728   * |                                 |     | pp      | 12:00:00 AM                       |       |
23729   * | Combination of date and time    |  NA | Pp      | 05/29/1453, 12:00 AM              |       |
23730   * |                                 |     | PPpp    | May 29, 1453, 12:00:00 AM         |       |
23731   * |                                 |     | PPPpp   | May 29th, 1453 at ...             |       |
23732   * |                                 |     | PPPPpp  | Sunday, May 29th, 1453 at ...     | 2,5,8 |
23733   * Notes:
23734   * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
23735   *    are the same as "stand-alone" units, but are different in some languages.
23736   *    "Formatting" units are declined according to the rules of the language
23737   *    in the context of a date. "Stand-alone" units are always nominative singular.
23738   *    In `format` function, they will produce different result:
23739   *
23740   *    `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
23741   *
23742   *    `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
23743   *
23744   *    `parse` will try to match both formatting and stand-alone units interchangably.
23745   *
23746   * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
23747   *    the single quote characters (see below).
23748   *    If the sequence is longer than listed in table:
23749   *    - for numerical units (`yyyyyyyy`) `parse` will try to match a number
23750   *      as wide as the sequence
23751   *    - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit.
23752   *      These variations are marked with "2" in the last column of the table.
23753   *
23754   * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
23755   *    These tokens represent the shortest form of the quarter.
23756   *
23757   * 4. The main difference between `y` and `u` patterns are B.C. years:
23758   *
23759   *    | Year | `y` | `u` |
23760   *    |------|-----|-----|
23761   *    | AC 1 |   1 |   1 |
23762   *    | BC 1 |   1 |   0 |
23763   *    | BC 2 |   2 |  -1 |
23764   *
23765   *    Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`:
23766   *
23767   *    `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00`
23768   *
23769   *    `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00`
23770   *
23771   *    while `uu` will just assign the year as is:
23772   *
23773   *    `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00`
23774   *
23775   *    `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00`
23776   *
23777   *    The same difference is true for local and ISO week-numbering years (`Y` and `R`),
23778   *    except local week-numbering years are dependent on `options.weekStartsOn`
23779   *    and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear}
23780   *    and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}).
23781   *
23782   * 5. These patterns are not in the Unicode Technical Standard #35:
23783   *    - `i`: ISO day of week
23784   *    - `I`: ISO week of year
23785   *    - `R`: ISO week-numbering year
23786   *    - `o`: ordinal number modifier
23787   *    - `P`: long localized date
23788   *    - `p`: long localized time
23789   *
23790   * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
23791   *    You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://git.io/fxCyr
23792   *
23793   * 7. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month.
23794   *    You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://git.io/fxCyr
23795   *
23796   * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based
23797   *    on the given locale.
23798   *
23799   *    using `en-US` locale: `P` => `MM/dd/yyyy`
23800   *    using `en-US` locale: `p` => `hh:mm a`
23801   *    using `pt-BR` locale: `P` => `dd/MM/yyyy`
23802   *    using `pt-BR` locale: `p` => `HH:mm`
23803   *
23804   * Values will be assigned to the date in the descending order of its unit's priority.
23805   * Units of an equal priority overwrite each other in the order of appearance.
23806   *
23807   * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year),
23808   * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing.
23809   *
23810   * `referenceDate` must be passed for correct work of the function.
23811   * If you're not sure which `referenceDate` to supply, create a new instance of Date:
23812   * `parse('02/11/2014', 'MM/dd/yyyy', new Date())`
23813   * In this case parsing will be done in the context of the current date.
23814   * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`,
23815   * then `Invalid Date` will be returned.
23816   *
23817   * The result may vary by locale.
23818   *
23819   * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned.
23820   *
23821   * If parsing failed, `Invalid Date` will be returned.
23822   * Invalid Date is a Date, whose time value is NaN.
23823   * Time value of Date: http://es5.github.io/#x15.9.1.1
23824   *
23825   * ### v2.0.0 breaking changes:
23826   *
23827   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
23828   *
23829   * - Old `parse` was renamed to `toDate`.
23830   *   Now `parse` is a new function which parses a string using a provided format.
23831   *
23832   *   ```javascript
23833   *   // Before v2.0.0
23834   *   parse('2016-01-01')
23835   *
23836   *   // v2.0.0 onward (toDate no longer accepts a string)
23837   *   toDate(1392098430000) // Unix to timestamp
23838   *   toDate(new Date(2014, 1, 11, 11, 30, 30)) // Cloning the date
23839   *   parse('2016-01-01', 'yyyy-MM-dd', new Date())
23840   *   ```
23841   *
23842   * @param {String} dateString - the string to parse
23843   * @param {String} formatString - the string of tokens
23844   * @param {Date|Number} referenceDate - defines values missing from the parsed dateString
23845   * @param {Object} [options] - an object with options.
23846   * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
23847   * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
23848   * @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
23849   * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`;
23850   *   see: https://git.io/fxCyr
23851   * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`;
23852   *   see: https://git.io/fxCyr
23853   * @returns {Date} the parsed date
23854   * @throws {TypeError} 3 arguments required
23855   * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
23856   * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
23857   * @throws {RangeError} `options.locale` must contain `match` property
23858   * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://git.io/fxCyr
23859   * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://git.io/fxCyr
23860   * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://git.io/fxCyr
23861   * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://git.io/fxCyr
23862   * @throws {RangeError} format string contains an unescaped latin alphabet character
23863   *
23864   * @example
23865   * // Parse 11 February 2014 from middle-endian format:
23866   * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date())
23867   * //=> Tue Feb 11 2014 00:00:00
23868   *
23869   * @example
23870   * // Parse 28th of February in Esperanto locale in the context of 2010 year:
23871   * import eo from 'date-fns/locale/eo'
23872   * var result = parse('28-a de februaro', "do 'de' MMMM", new Date(2010, 0, 1), {
23873   *   locale: eo
23874   * })
23875   * //=> Sun Feb 28 2010 00:00:00
23876   */
23877
23878  function parse(dirtyDateString, dirtyFormatString, dirtyReferenceDate, dirtyOptions) {
23879    requiredArgs(3, arguments);
23880    var dateString = String(dirtyDateString);
23881    var formatString = String(dirtyFormatString);
23882    var options = dirtyOptions || {};
23883    var locale$1 = options.locale || locale;
23884
23885    if (!locale$1.match) {
23886      throw new RangeError('locale must contain match property');
23887    }
23888
23889    var localeFirstWeekContainsDate = locale$1.options && locale$1.options.firstWeekContainsDate;
23890    var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate);
23891    var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
23892
23893    if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
23894      throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
23895    }
23896
23897    var localeWeekStartsOn = locale$1.options && locale$1.options.weekStartsOn;
23898    var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
23899    var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
23900
23901    if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
23902      throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
23903    }
23904
23905    if (formatString === '') {
23906      if (dateString === '') {
23907        return toDate(dirtyReferenceDate);
23908      } else {
23909        return new Date(NaN);
23910      }
23911    }
23912
23913    var subFnOptions = {
23914      firstWeekContainsDate: firstWeekContainsDate,
23915      weekStartsOn: weekStartsOn,
23916      locale: locale$1 // If timezone isn't specified, it will be set to the system timezone
23917
23918    };
23919    var setters = [{
23920      priority: TIMEZONE_UNIT_PRIORITY,
23921      subPriority: -1,
23922      set: dateToSystemTimezone,
23923      index: 0
23924    }];
23925    var i;
23926    var tokens = formatString.match(longFormattingTokensRegExp
vendor: 22,059 bytes, lines 23926-24664
23926).map(function (substring) {
23927      var firstCharacter = substring[0];
23928
23929      if (firstCharacter === 'p' || firstCharacter === 'P') {
23930        var longFormatter = longFormatters[firstCharacter];
23931        return longFormatter(substring, locale$1.formatLong, subFnOptions);
23932      }
23933
23934      return substring;
23935    }).join('').match(formattingTokensRegExp);
23936    var usedTokens = [];
23937
23938    for (i = 0; i < tokens.length; i++) {
23939      var token = tokens[i];
23940
23941      if (!options.useAdditionalWeekYearTokens && isProtectedWeekYearToken(token)) {
23942        throwProtectedError(token, formatString, dirtyDateString);
23943      }
23944
23945      if (!options.useAdditionalDayOfYearTokens && isProtectedDayOfYearToken(token)) {
23946        throwProtectedError(token, formatString, dirtyDateString);
23947      }
23948
23949      var firstCharacter = token[0];
23950      var parser = parsers[firstCharacter];
23951
23952      if (parser) {
23953        var incompatibleTokens = parser.incompatibleTokens;
23954
23955        if (Array.isArray(incompatibleTokens)) {
23956          var incompatibleToken = void 0;
23957
23958          for (var _i = 0; _i < usedTokens.length; _i++) {
23959            var usedToken = usedTokens[_i].token;
23960
23961            if (incompatibleTokens.indexOf(usedToken) !== -1 || usedToken === firstCharacter) {
23962              incompatibleToken = usedTokens[_i];
23963              break;
23964            }
23965          }
23966
23967          if (incompatibleToken) {
23968            throw new RangeError("The format string mustn't contain `".concat(incompatibleToken.fullToken, "` and `").concat(token, "` at the same time"));
23969          }
23970        } else if (parser.incompatibleTokens === '*' && usedTokens.length) {
23971          throw new RangeError("The format string mustn't contain `".concat(token, "` and any other token at the same time"));
23972        }
23973
23974        usedTokens.push({
23975          token: firstCharacter,
23976          fullToken: token
23977        });
23978        var parseResult = parser.parse(dateString, token, locale$1.match, subFnOptions);
23979
23980        if (!parseResult) {
23981          return new Date(NaN);
23982        }
23983
23984        setters.push({
23985          priority: parser.priority,
23986          subPriority: parser.subPriority || 0,
23987          set: parser.set,
23988          validate: parser.validate,
23989          value: parseResult.value,
23990          index: setters.length
23991        });
23992        dateString = parseResult.rest;
23993      } else {
23994        if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
23995          throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`');
23996        } // Replace two single quote characters with one single quote character
23997
23998
23999        if (token === "''") {
24000          token = "'";
24001        } else if (firstCharacter === "'") {
24002          token = cleanEscapedString(token);
24003        } // Cut token from string, or, if string doesn't match the token, return Invalid Date
24004
24005
24006        if (dateString.indexOf(token) === 0) {
24007          dateString = dateString.slice(token.length);
24008        } else {
24009          return new Date(NaN);
24010        }
24011      }
24012    } // Check if the remaining input contains something other than whitespace
24013
24014
24015    if (dateString.length > 0 && notWhitespaceRegExp.test(dateString)) {
24016      return new Date(NaN);
24017    }
24018
24019    var uniquePrioritySetters = setters.map(function (setter) {
24020      return setter.priority;
24021    }).sort(function (a, b) {
24022      return b - a;
24023    }).filter(function (priority, index, array) {
24024      return array.indexOf(priority) === index;
24025    }).map(function (priority) {
24026      return setters.filter(function (setter) {
24027        return setter.priority === priority;
24028      }).sort(function (a, b) {
24029        return b.subPriority - a.subPriority;
24030      });
24031    }).map(function (setterArray) {
24032      return setterArray[0];
24033    });
24034    var date = toDate(dirtyReferenceDate);
24035
24036    if (isNaN(date)) {
24037      return new Date(NaN);
24038    } // Convert the date in system timezone to the same date in UTC+00:00 timezone.
24039    // This ensures that when UTC functions will be implemented, locales will be compatible with them.
24040    // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/37
24041
24042
24043    var utcDate = subMilliseconds(date, getTimezoneOffsetInMilliseconds(date));
24044    var flags = {};
24045
24046    for (i = 0; i < uniquePrioritySetters.length; i++) {
24047      var setter = uniquePrioritySetters[i];
24048
24049      if (setter.validate && !setter.validate(utcDate, setter.value, subFnOptions)) {
24050        return new Date(NaN);
24051      }
24052
24053      var result = setter.set(utcDate, flags, setter.value, subFnOptions); // Result is tuple (date, flags)
24054
24055      if (result[0]) {
24056        utcDate = result[0];
24057        assign(flags, result[1]); // Result is date
24058      } else {
24059        utcDate = result;
24060      }
24061    }
24062
24063    return utcDate;
24064  }
24065
24066  function dateToSystemTimezone(date, flags) {
24067    if (flags.timestampIsSet) {
24068      return date;
24069    }
24070
24071    var convertedDate = new Date(0);
24072    convertedDate.setFullYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
24073    convertedDate.setHours(date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
24074    return convertedDate;
24075  }
24076
24077  function cleanEscapedString(input) {
24078    return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'");
24079  }
24080
24081  /**
24082   * @name startOfHour
24083   * @category Hour Helpers
24084   * @summary Return the start of an hour for the given date.
24085   *
24086   * @description
24087   * Return the start of an hour for the given date.
24088   * The result will be in the local timezone.
24089   *
24090   * ### v2.0.0 breaking changes:
24091   *
24092   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
24093   *
24094   * @param {Date|Number} date - the original date
24095   * @returns {Date} the start of an hour
24096   * @throws {TypeError} 1 argument required
24097   *
24098   * @example
24099   * // The start of an hour for 2 September 2014 11:55:00:
24100   * const result = startOfHour(new Date(2014, 8, 2, 11, 55))
24101   * //=> Tue Sep 02 2014 11:00:00
24102   */
24103
24104  function startOfHour(dirtyDate) {
24105    requiredArgs(1, arguments);
24106    var date = toDate(dirtyDate);
24107    date.setMinutes(0, 0, 0);
24108    return date;
24109  }
24110
24111  /**
24112   * @name startOfSecond
24113   * @category Second Helpers
24114   * @summary Return the start of a second for the given date.
24115   *
24116   * @description
24117   * Return the start of a second for the given date.
24118   * The result will be in the local timezone.
24119   *
24120   * ### v2.0.0 breaking changes:
24121   *
24122   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
24123   *
24124   * @param {Date|Number} date - the original date
24125   * @returns {Date} the start of a second
24126   * @throws {TypeError} 1 argument required
24127   *
24128   * @example
24129   * // The start of a second for 1 December 2014 22:15:45.400:
24130   * const result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400))
24131   * //=> Mon Dec 01 2014 22:15:45.000
24132   */
24133
24134  function startOfSecond(dirtyDate) {
24135    requiredArgs(1, arguments);
24136    var date = toDate(dirtyDate);
24137    date.setMilliseconds(0);
24138    return date;
24139  }
24140
24141  var MILLISECONDS_IN_HOUR = 3600000;
24142  var MILLISECONDS_IN_MINUTE = 60000;
24143  var DEFAULT_ADDITIONAL_DIGITS = 2;
24144  var patterns = {
24145    dateTimeDelimiter: /[T ]/,
24146    timeZoneDelimiter: /[Z ]/i,
24147    timezone: /([Z+-].*)$/
24148  };
24149  var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
24150  var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
24151  var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
24152  /**
24153   * @name parseISO
24154   * @category Common Helpers
24155   * @summary Parse ISO string
24156   *
24157   * @description
24158   * Parse the given string in ISO 8601 format and return an instance of Date.
24159   *
24160   * Function accepts complete ISO 8601 formats as well as partial implementations.
24161   * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601
24162   *
24163   * If the argument isn't a string, the function cannot parse the string or
24164   * the values are invalid, it returns Invalid Date.
24165   *
24166   * ### v2.0.0 breaking changes:
24167   *
24168   * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
24169   *
24170   * - The previous `parse` implementation was renamed to `parseISO`.
24171   *
24172   *   ```javascript
24173   *   // Before v2.0.0
24174   *   parse('2016-01-01')
24175   *
24176   *   // v2.0.0 onward
24177   *   parseISO('2016-01-01')
24178   *   ```
24179   *
24180   * - `parseISO` now validates separate date and time values in ISO-8601 strings
24181   *   and returns `Invalid Date` if the date is invalid.
24182   *
24183   *   ```javascript
24184   *   parseISO('2018-13-32')
24185   *   //=> Invalid Date
24186   *   ```
24187   *
24188   * - `parseISO` now doesn't fall back to `new Date` constructor
24189   *   if it fails to parse a string argument. Instead, it returns `Invalid Date`.
24190   *
24191   * @param {String} argument - the value to convert
24192   * @param {Object} [options] - an object with options.
24193   * @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format
24194   * @returns {Date} the parsed date in the local time zone
24195   * @throws {TypeError} 1 argument required
24196   * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2
24197   *
24198   * @example
24199   * // Convert string '2014-02-11T11:30:30' to date:
24200   * var result = parseISO('2014-02-11T11:30:30')
24201   * //=> Tue Feb 11 2014 11:30:30
24202   *
24203   * @example
24204   * // Convert string '+02014101' to date,
24205   * // if the additional number of digits in the extended year format is 1:
24206   * var result = parseISO('+02014101', { additionalDigits: 1 })
24207   * //=> Fri Apr 11 2014 00:00:00
24208   */
24209
24210  function parseISO(argument, dirtyOptions) {
24211    requiredArgs(1, arguments);
24212    var options = dirtyOptions || {};
24213    var additionalDigits = options.additionalDigits == null ? DEFAULT_ADDITIONAL_DIGITS : toInteger(options.additionalDigits);
24214
24215    if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) {
24216      throw new RangeError('additionalDigits must be 0, 1 or 2');
24217    }
24218
24219    if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) {
24220      return new Date(NaN);
24221    }
24222
24223    var dateStrings = splitDateString(argument);
24224    var date;
24225
24226    if (dateStrings.date) {
24227      var parseYearResult = parseYear(dateStrings.date, additionalDigits);
24228      date = parseDate(parseYearResult.restDateString, parseYearResult.year);
24229    }
24230
24231    if (isNaN(date) || !date) {
24232      return new Date(NaN);
24233    }
24234
24235    var timestamp = date.getTime();
24236    var time = 0;
24237    var offset;
24238
24239    if (dateStrings.time) {
24240      time = parseTime(dateStrings.time);
24241
24242      if (isNaN(time) || time === null) {
24243        return new Date(NaN);
24244      }
24245    }
24246
24247    if (dateStrings.timezone) {
24248      offset = parseTimezone(dateStrings.timezone);
24249
24250      if (isNaN(offset)) {
24251        return new Date(NaN);
24252      }
24253    } else {
24254      var dirtyDate = new Date(timestamp + time); // js parsed string assuming it's in UTC timezone
24255      // but we need it to be parsed in our timezone
24256      // so we use utc values to build date in our timezone.
24257      // Year values from 0 to 99 map to the years 1900 to 1999
24258      // so set year explicitly with setFullYear.
24259
24260      var result = new Date(0);
24261      result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate());
24262      result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds());
24263      return result;
24264    }
24265
24266    return new Date(timestamp + time + offset);
24267  }
24268
24269  function splitDateString(dateString) {
24270    var dateStrings = {};
24271    var array = dateString.split(patterns.dateTimeDelimiter);
24272    var timeString; // The regex match should only return at maximum two array elements.
24273    // [date], [time], or [date, time].
24274
24275    if (array.length > 2) {
24276      return dateStrings;
24277    }
24278
24279    if (/:/.test(array[0])) {
24280      dateStrings.date = null;
24281      timeString = array[0];
24282    } else {
24283      dateStrings.date = array[0];
24284      timeString = array[1];
24285
24286      if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
24287        dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
24288        timeString = dateString.substr(dateStrings.date.length, dateString.length);
24289      }
24290    }
24291
24292    if (timeString) {
24293      var token = patterns.timezone.exec(timeString);
24294
24295      if (token) {
24296        dateStrings.time = timeString.replace(token[1], '');
24297        dateStrings.timezone = token[1];
24298      } else {
24299        dateStrings.time = timeString;
24300      }
24301    }
24302
24303    return dateStrings;
24304  }
24305
24306  function parseYear(dateString, additionalDigits) {
24307    var regex = new RegExp('^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)');
24308    var captures = dateString.match(regex); // Invalid ISO-formatted year
24309
24310    if (!captures) return {
24311      year: null
24312    };
24313    var year = captures[1] && parseInt(captures[1]);
24314    var century = captures[2] && parseInt(captures[2]);
24315    return {
24316      year: century == null ? year : century * 100,
24317      restDateString: dateString.slice((captures[1] || captures[2]).length)
24318    };
24319  }
24320
24321  function parseDate(dateString, year) {
24322    // Invalid ISO-formatted year
24323    if (year === null) return null;
24324    var captures = dateString.match(dateRegex); // Invalid ISO-formatted string
24325
24326    if (!captures) return null;
24327    var isWeekDate = !!captures[4];
24328    var dayOfYear = parseDateUnit(captures[1]);
24329    var month = parseDateUnit(captures[2]) - 1;
24330    var day = parseDateUnit(captures[3]);
24331    var week = parseDateUnit(captures[4]);
24332    var dayOfWeek = parseDateUnit(captures[5]) - 1;
24333
24334    if (isWeekDate) {
24335      if (!validateWeekDate(year, week, dayOfWeek)) {
24336        return new Date(NaN);
24337      }
24338
24339      return dayOfISOWeekYear(year, week, dayOfWeek);
24340    } else {
24341      var date = new Date(0);
24342
24343      if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) {
24344        return new Date(NaN);
24345      }
24346
24347      date.setUTCFullYear(year, month, Math.max(dayOfYear, day));
24348      return date;
24349    }
24350  }
24351
24352  function parseDateUnit(value) {
24353    return value ? parseInt(value) : 1;
24354  }
24355
24356  function parseTime(timeString) {
24357    var captures = timeString.match(timeRegex);
24358    if (!captures) return null; // Invalid ISO-formatted time
24359
24360    var hours = parseTimeUnit(captures[1]);
24361    var minutes = parseTimeUnit(captures[2]);
24362    var seconds = parseTimeUnit(captures[3]);
24363
24364    if (!validateTime(hours, minutes, seconds)) {
24365      return NaN;
24366    }
24367
24368    return hours * MILLISECONDS_IN_HOUR + minutes * MILLISECONDS_IN_MINUTE + seconds * 1000;
24369  }
24370
24371  function parseTimeUnit(value) {
24372    return value && parseFloat(value.replace(',', '.')) || 0;
24373  }
24374
24375  function parseTimezone(timezoneString) {
24376    if (timezoneString === 'Z') return 0;
24377    var captures = timezoneString.match(timezoneRegex);
24378    if (!captures) return 0;
24379    var sign = captures[1] === '+' ? -1 : 1;
24380    var hours = parseInt(captures[2]);
24381    var minutes = captures[3] && parseInt(captures[3]) || 0;
24382
24383    if (!validateTimezone(hours, minutes)) {
24384      return NaN;
24385    }
24386
24387    return sign * (hours * MILLISECONDS_IN_HOUR + minutes * MILLISECONDS_IN_MINUTE);
24388  }
24389
24390  function dayOfISOWeekYear(isoWeekYear, week, day) {
24391    var date = new Date(0);
24392    date.setUTCFullYear(isoWeekYear, 0, 4);
24393    var fourthOfJanuaryDay = date.getUTCDay() || 7;
24394    var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;
24395    date.setUTCDate(date.getUTCDate() + diff);
24396    return date;
24397  } // Validation functions
24398  // February is null to handle the leap year (using ||)
24399
24400
24401  var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
24402
24403  function isLeapYearIndex(year) {
24404    return year % 400 === 0 || year % 4 === 0 && year % 100;
24405  }
24406
24407  function validateDate(year, month, date) {
24408    return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28));
24409  }
24410
24411  function validateDayOfYearDate(year, dayOfYear) {
24412    return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);
24413  }
24414
24415  function validateWeekDate(_year, week, day) {
24416    return week >= 1 && week <= 53 && day >= 0 && day <= 6;
24417  }
24418
24419  function validateTime(hours, minutes, seconds) {
24420    if (hours === 24) {
24421      return minutes === 0 && seconds === 0;
24422    }
24423
24424    return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25;
24425  }
24426
24427  function validateTimezone(_hours, minutes) {
24428    return minutes >= 0 && minutes <= 59;
24429  }
24430
24431  var FORMATS = {
24432    datetime: 'MMM d, yyyy, h:mm:ss aaaa',
24433    millisecond: 'h:mm:ss.SSS aaaa',
24434    second: 'h:mm:ss aaaa',
24435    minute: 'h:mm aaaa',
24436    hour: 'ha',
24437    day: 'MMM d',
24438    week: 'PP',
24439    month: 'MMM yyyy',
24440    quarter: 'qqq - yyyy',
24441    year: 'yyyy'
24442  };
24443
24444  adapters._date.override({
24445    _id: 'date-fns',
24446    // DEBUG
24447    formats: function formats() {
24448      return FORMATS;
24449    },
24450    parse: function parse$1(value, fmt) {
24451      if (value === null || typeof value === 'undefined') {
24452        return null;
24453      }
24454
24455      var type = _typeof(value);
24456
24457      if (type === 'number' || value instanceof Date) {
24458        value = toDate(value);
24459      } else if (type === 'string') {
24460        if (typeof fmt === 'string') {
24461          value = parse(value, fmt, new Date(), this.options);
24462        } else {
24463          value = parseISO(value, this.options);
24464        }
24465      }
24466
24467      return isValid(value) ? value.getTime() : null;
24468    },
24469    format: function format$1(time, fmt) {
24470      return format(time, fmt, this.options);
24471    },
24472    add: function add(time, amount, unit) {
24473      switch (unit) {
24474        case 'millisecond':
24475          return addMilliseconds(time, amount);
24476
24477        case 'second':
24478          return addSeconds(time, amount);
24479
24480        case 'minute':
24481          return addMinutes(time, amount);
24482
24483        case 'hour':
24484          return addHours(time, amount);
24485
24486        case 'day':
24487          return addDays(time, amount);
24488
24489        case 'week':
24490          return addWeeks(time, amount);
24491
24492        case 'month':
24493          return addMonths(time, amount);
24494
24495        case 'quarter':
24496          return addQuarters(time, amount);
24497
24498        case 'year':
24499          return addYears(time, amount);
24500
24501        default:
24502          return time;
24503      }
24504    },
24505    diff: function diff(max, min, unit) {
24506      switch (unit) {
24507        case 'millisecond':
24508          return differenceInMilliseconds(max, min);
24509
24510        case 'second':
24511          return differenceInSeconds(max, min);
24512
24513        case 'minute':
24514          return differenceInMinutes(max, min);
24515
24516        case 'hour':
24517          return differenceInHours(max, min);
24518
24519        case 'day':
24520          return differenceInDays(max, min);
24521
24522        case 'week':
24523          return differenceInWeeks(max, min);
24524
24525        case 'month':
24526          return differenceInMonths(max, min);
24527
24528        case 'quarter':
24529          return differenceInQuarters(max, min);
24530
24531        case 'year':
24532          return differenceInYears(max, min);
24533
24534        default:
24535          return 0;
24536      }
24537    },
24538    startOf: function startOf(time, unit, weekday) {
24539      switch (unit) {
24540        case 'second':
24541          return startOfSecond(time);
24542
24543        case 'minute':
24544          return startOfMinute(time);
24545
24546        case 'hour':
24547          return startOfHour(time);
24548
24549        case 'day':
24550          return startOfDay(time);
24551
24552        case 'week':
24553          return startOfWeek(time);
24554
24555        case 'isoWeek':
24556          return startOfWeek(time, {
24557            weekStartsOn: +weekday
24558          });
24559
24560        case 'month':
24561          return startOfMonth(time);
24562
24563        case 'quarter':
24564          return startOfQuarter(time);
24565
24566        case 'year':
24567          return startOfYear(time);
24568
24569        default:
24570          return time;
24571      }
24572    },
24573    endOf: function endOf(time, unit) {
24574      switch (unit) {
24575        case 'second':
24576          return endOfSecond(time);
24577
24578        case 'minute':
24579          return endOfMinute(time);
24580
24581        case 'hour':
24582          return endOfHour(time);
24583
24584        case 'day':
24585          return endOfDay(time);
24586
24587        case 'week':
24588          return endOfWeek(time);
24589
24590        case 'month':
24591          return endOfMonth(time);
24592
24593        case 'quarter':
24594          return endOfQuarter(time);
24595
24596        case 'year':
24597          return endOfYear(time);
24598
24599        default:
24600          return time;
24601      }
24602    }
24603  });
24604
24605  return Chart;
24606
24607})));
24608/*!
24609 * Chartkick.js
24610 * Create beautiful charts with one line of JavaScript
24611 * https://github.com/ankane/chartkick.js
24612 * v4.0.5
24613 * MIT License
24614 */
24615
24616(function (global, factory) {
24617  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
24618  typeof define === 'function' && define.amd ? define(factory) :
24619  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Chartkick = factory());
24620}(this, (function () { 'use strict';
24621
24622  function isArray(variable) {
24623    return Object.prototype.toString.call(variable) === "[object Array]";
24624  }
24625
24626  function isFunction(variable) {
24627    return variable instanceof Function;
24628  }
24629
24630  function isPlainObject(variable) {
24631    // protect against prototype pollution, defense 2
24632    return Object.prototype.toString.call(variable) === "[object Object]" && !isFunction(variable) && variable instanceof Object;
24633  }
24634
24635  // https://github.com/madrobby/zepto/blob/master/src/zepto.js
24636  function extend(target, source) {
24637    var key;
24638    for (key in source) {
24639      // protect against prototype pollution, defense 1
24640      if (key === "__proto__") { continue; }
24641
24642      if (isPlainObject(source[key]) || isArray(source[key])) {
24643        if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
24644          target[key] = {};
24645        }
24646        if (isArray(source[key]) && !isArray(target[key])) {
24647          target[key] = [];
24648        }
24649        extend(target[key], source[key]);
24650      } else if (source[key] !== undefined) {
24651        target[key] = source[key];
24652      }
24653    }
24654  }
24655
24656  function merge(obj1, obj2) {
24657    var target = {};
24658    extend(target, obj1);
24659    extend(target, obj2);
24660    return target;
24661  }
24662
24663  var DATE_PATTERN = /^(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)$/i;
24664
24665  function negativeValues(series) {
24666    var i, j, data;
24667    for (i = 0; i < series.length; i++) {
24668      data = series[i].data;
24669      for (j = 0; j < data.length; j++) {
24670        if (data[j][1] < 0) {
24671          return true;
24672        }
24673      }
24674    }
24675    return false;
24676  }
24677
24678  function toStr(n) {
24679    return "" + n;
24680  }
24681
24682  function toFloat(n) {
24683    return parseFloat(n);
24684  }
24685
24686  function toDate(n) {
24687    var matches, year, month, day;
24688    if (typeof n !== "object") {
24689      if (typeof n === "number") {
24690        n = new Date(n * 1000); // ms
24691      } else {
24692        n = toStr(n);
24693        if ((matches = n.match(DATE_PATTERN))) {
24694          year = parseInt(matches[1], 10);
24695          month = parseInt(matches[3], 10) - 1;
24696          day = parseInt(matches[5], 10);
24697          return new Date(year, month, day);
24698        } else {
24699          // try our best to get the str into iso8601
24700          // TODO be smarter about this
24701          var str = n.replace(/ /, "T").replace(" ", "").replace("UTC", "Z");
24702          // Date.parse returns milliseconds if valid and NaN if invalid
24703          n = new Date(Date.parse(str) || n);
24704        }
24705      }
24706    }
24707    return n;
24708  }
24709
24710  function toArr(n) {
24711    if (!isArray(n)) {
24712      var arr = [], i;
24713      for (i in n) {
24714        if (n.hasOwnProperty(i)) {
24715          arr.push([i, n[i]]);
24716        }
24717      }
24718      n = arr;
24719    }
24720    return n;
24721  }
24722
24723  function jsOptionsFunc(defaultOptions, hideLegend, setTitle, setMin, setMax, setStacked, setXtitle, setYtitle) {
24724    return function (chart, opts, chartOptions) {
24725      var series = chart.data;
24726      var options = merge({}, defaultOptions);
24727      options = merge(options, chartOptions || {});
24728
24729      if (chart.singleSeriesFormat || "legend" in opts) {
24730        hideLegend(options, opts.legend, chart.singleSeriesFormat);
24731      }
24732
24733      if (opts.title) {
24734        setTitle(options, opts.title);
24735      }
24736
24737      // min
24738      if ("min" in opts) {
24739        setMin(options, opts.min);
24740      } else if (!negativeValues(series)) {
24741        setMin(options, 0);
24742      }
24743
24744      // max
24745      if (opts.max) {
24746        setMax(options, opts.max);
24747      }
24748
24749      if ("stacked" in opts) {
24750        setStacked(options, opts.stacked);
24751      }
24752
24753      if (opts.colors) {
24754        options.colors = opts.colors;
24755      }
24756
24757      if (opts.xtitle) {
24758        setXtitle(options, opts.xtitle);
24759      }
24760
24761      if (opts.ytitle) {
24762        setYtitle(options, opts.ytitle);
24763      }
24764
24765      // merge library last
24766      options = merge(options, opts.library || {});
24767
24768      return options;
24769    };
24770  }
24771
24772  function sortByTime(a, b) {
24773    return a[0].getTime() - b[0].getTime();
24774  }
24775
24776  function sortByNumberSeries(a, b) {
24777    return a[0] - b[0];
24778  }
24779
24780  function sortByNumber(a, b) {
24781    return a - b;
24782  }
24783
24784  function isMinute(d) {
24785    return d.getMilliseconds() === 0 && d.getSeconds() === 0;
24786  }
24787
24788  function isHour(d) {
24789    return isMinute(d) && d.getMinutes() === 0;
24790  }
24791
24792  function isDay(d) {
24793    return isHour(d) && d.getHours() === 0;
24794  }
24795
24796  function isWeek(d, dayOfWeek) {
24797    return isDay(d) && d.getDay() === dayOfWeek;
24798  }
24799
24800  function isMonth(d) {
24801    return isDay(d) && d.getDate() === 1;
24802  }
24803
24804  function isYear(d) {
24805    return isMonth(d) && d.getMonth() === 0;
24806  }
24807
24808  function isDate(obj) {
24809    return !isNaN(toDate(obj)) && toStr(obj).length >= 6;
24810  }
24811
24812  function isNumber(obj) {
24813    return typeof obj === "number";
24814  }
24815
24816  var byteSuffixes = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB"];
24817
24818  function formatValue(pre, value, options, axis) {
24819    pre = pre || "";
24820    if (options.prefix) {
24821      if (value < 0) {
24822        value = value * -1;
24823        pre += "-";
24824      }
24825      pre += options.prefix;
24826    }
24827
24828    var suffix = options.suffix || "";
24829    var precision = options.precision;
24830    var round = options.round;
24831
24832    if (options.byteScale) {
24833      var suffixIdx;
24834      var baseValue = axis ? options.byteScale : value;
24835
24836      if (baseValue >= 1152921504606846976) {
24837        value /= 1152921504606846976;
24838        suffixIdx = 6;
24839      } else if (baseValue >= 1125899906842624) {
24840        value /= 1125899906842624;
24841        suffixIdx = 5;
24842      } else if (baseValue >= 1099511627776) {
24843        value /= 1099511627776;
24844        suffixIdx = 4;
24845      } else if (baseValue >= 1073741824) {
24846        value /= 1073741824;
24847        suffixIdx = 3;
24848      } else if (baseValue >= 1048576) {
24849        value /= 1048576;
24850        suffixIdx = 2;
24851      } else if (baseValue >= 1024) {
24852        value /= 1024;
24853        suffixIdx = 1;
24854      } else {
24855        suffixIdx = 0;
24856      }
24857
24858      // TODO handle manual precision case
24859      if (precision === undefined && round === undefined) {
24860        if (value >= 1023.5) {
24861          if (suffixIdx < byteSuffixes.length - 1) {
24862            value = 1.0;
24863            suffixIdx += 1;
24864          }
24865        }
24866        precision = value >= 1000 ? 4 : 3;
24867      }
24868      suffix = " " + byteSuffixes[suffixIdx];
24869    }
24870
24871    if (precision !== undefined && round !== undefined) {
24872      throw Error("Use either round or precision, not both");
24873    }
24874
24875    if (!axis) {
24876      if (precision !== undefined) {
24877        value = value.toPrecision(precision);
24878        if (!options.zeros) {
24879          value = parseFloat(value);
24880        }
24881      }
24882
24883      if (round !== undefined) {
24884        if (round < 0) {
24885          var num = Math.pow(10, -1 * round);
24886          value = parseInt((1.0 * value / num).toFixed(0)) * num;
24887        } else {
24888          value = value.toFixed(round);
24889          if (!options.zeros) {
24890            value = parseFloat(value);
24891          }
24892        }
24893      }
24894    }
24895
24896    if (options.thousands || options.decimal) {
24897      value = toStr(value);
24898      var parts = value.split(".");
24899      value = parts[0];
24900      if (options.thousands) {
24901        value = value.replace(/\B(?=(\d{3})+(?!\d))/g, options.thousands);
24902      }
24903      if (parts.length > 1) {
24904        value += (options.decimal || ".") + parts[1];
24905      }
24906    }
24907
24908    return pre + value + suffix;
24909  }
24910
24911  function seriesOption(chart, series, option) {
24912    if (option in series) {
24913      return series[option];
24914    } else if (option in chart.options) {
24915      return chart.options[option];
24916    }
24917    return null;
24918  }
24919
24920  function allZeros(data) {
24921    var i, j, d;
24922    for (i = 0; i < data.length; i++) {
24923      d = data[i].data;
24924      for (j = 0; j < d.length; j++) {
24925        if (d[j][1] != 0) {
24926          return false;
24927        }
24928      }
24929    }
24930    return true;
24931  }
24932
24933  var baseOptions = {
24934    maintainAspectRatio: false,
24935    animation: false,
24936    plugins: {
24937      legend: {},
24938      tooltip: {
24939        displayColors: false,
24940        callbacks: {}
24941      },
24942      title: {
24943        font: {
24944          size: 20
24945        },
24946        color: "#333"
24947      }
24948    },
24949    interaction: {}
24950  };
24951
24952  var defaultOptions$2 = {
24953    scales: {
24954      y: {
24955        ticks: {
24956          maxTicksLimit: 4
24957        },
24958        title: {
24959          font: {
24960            size: 16
24961          },
24962          color: "#333"
24963        },
24964        grid: {}
24965      },
24966      x: {
24967        grid: {
24968          drawOnChartArea: false
24969        },
24970        title: {
24971          font: {
24972            size: 16
24973          },
24974          color: "#333"
24975        },
24976        time: {},
24977        ticks: {}
24978      }
24979    }
24980  };
24981
24982  // http://there4.io/2012/05/02/google-chart-color-list/
24983  var defaultColors = [
24984    "#3366CC", "#DC3912", "#FF9900", "#109618", "#990099", "#3B3EAC", "#0099C6",
24985    "#DD4477", "#66AA00", "#B82E2E", "#316395", "#994499", "#22AA99", "#AAAA11",
24986    "#6633CC", "#E67300", "#8B0707", "#329262", "#5574A6", "#651067"
24987  ];
24988
24989  var hideLegend$2 = function (options, legend, hideLegend) {
24990    if (legend !== undefined) {
24991      options.plugins.legend.display = !!legend;
24992      if (legend && legend !== true) {
24993        options.plugins.legend.position = legend;
24994      }
24995    } else if (hideLegend) {
24996      options.plugins.legend.display = false;
24997    }
24998  };
24999
25000  var setTitle$2 = function (options, title) {
25001    options.plugins.title.display = true;
25002    options.plugins.title.text = title;
25003  };
25004
25005  var setMin$2 = function (options, min) {
25006    if (min !== null) {
25007      options.scales.y.min = toFloat(min);
25008    }
25009  };
25010
25011  var setMax$2 = function (options, max) {
25012    options.scales.y.max = toFloat(max);
25013  };
25014
25015  var setBarMin$1 = function (options, min) {
25016    if (min !== null) {
25017      options.scales.x.min = toFloat(min);
25018    }
25019  };
25020
25021  var setBarMax$1 = function (options, max) {
25022    options.scales.x.max = toFloat(max);
25023  };
25024
25025  var setStacked$2 = function (options, stacked) {
25026    options.scales.x.stacked = !!stacked;
25027    options.scales.y.stacked = !!stacked;
25028  };
25029
25030  var setXtitle$2 = function (options, title) {
25031    options.scales.x.title.display = true;
25032    options.scales.x.title.text = title;
25033  };
25034
25035  var setYtitle$2 = function (options, title) {
25036    options.scales.y.title.display = true;
25037    options.scales.y.title.text = title;
25038  };
25039
25040  // https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
25041  var addOpacity = function (hex, opacity) {
25042    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
25043    return result ? "rgba(" + parseInt(result[1], 16) + ", " + parseInt(result[2], 16) + ", " + parseInt(result[3], 16) + ", " + opacity + ")" : hex;
25044  };
25045
25046  // check if not null or undefined
25047  // https://stackoverflow.com/a/27757708/1177228
25048  var notnull = function (x) {
25049    return x != null;
25050  };
25051
25052  var setLabelSize = function (chart, data, options) {
25053    var maxLabelSize = Math.ceil(chart.element.offsetWidth / 4.0 / data.labels.length);
25054    if (maxLabelSize > 25) {
25055      maxLabelSize = 25;
25056    } else if (maxLabelSize < 10) {
25057      maxLabelSize = 10;
25058    }
25059    if (!options.scales.x.ticks.callback) {
25060      options.scales.x.ticks.callback = function (value) {
25061        value = toStr(this.getLabelForValue(value));
25062        if (value.length > maxLabelSize) {
25063          return value.substring(0, maxLabelSize - 2) + "...";
25064        } else {
25065          return value;
25066        }
25067      };
25068    }
25069  };
25070
25071  var setFormatOptions$1 = function (chart, options, chartType) {
25072    var formatOptions = {
25073      prefix: chart.options.prefix,
25074      suffix: chart.options.suffix,
25075      thousands: chart.options.thousands,
25076      decimal: chart.options.decimal,
25077      precision: chart.options.precision,
25078      round: chart.options.round,
25079      zeros: chart.options.zeros
25080    };
25081
25082    if (chart.options.bytes) {
25083      var series = chart.data;
25084      if (chartType === "pie") {
25085        series = [{data: series}];
25086      }
25087
25088      // calculate max
25089      var max = 0;
25090      for (var i = 0; i < series.length; i++) {
25091        var s = series[i];
25092        for (var j = 0; j < s.data.length; j++) {
25093          if (s.data[j][1] > max) {
25094            max = s.data[j][1];
25095          }
25096        }
25097      }
25098
25099      // calculate scale
25100      var scale = 1;
25101      while (max >= 1024) {
25102        scale *= 1024;
25103        max /= 1024;
25104      }
25105
25106      // set step size
25107      formatOptions.byteScale = scale;
25108    }
25109
25110    if (chartType !== "pie") {
25111      var axis = options.scales.y;
25112      if (chartType === "bar") {
25113        axis = options.scales.x;
25114      }
25115
25116      if (formatOptions.byteScale) {
25117        if (!axis.ticks.stepSize) {
25118          axis.ticks.stepSize = formatOptions.byteScale / 2;
25119        }
25120        if (!axis.ticks.maxTicksLimit) {
25121          axis.ticks.maxTicksLimit = 4;
25122        }
25123      }
25124
25125      if (!axis.ticks.callback) {
25126        axis.ticks.callback = function (value) {
25127          return formatValue("", value, formatOptions, true);
25128        };
25129      }
25130    }
25131
25132    if (!options.plugins.tooltip.callbacks.label) {
25133      if (chartType === "scatter") {
25134        options.plugins.tooltip.callbacks.label = function (context) {
25135          var label = context.dataset.label || '';
25136          if (label) {
25137            label += ': ';
25138          }
25139          return label + '(' + context.label + ', ' + context.formattedValue + ')';
25140        };
25141      } else if (chartType === "bubble") {
25142        options.plugins.tooltip.callbacks.label = function (context) {
25143          var label = context.dataset.label || '';
25144          if (label) {
25145            label += ': ';
25146          }
25147          var dataPoint = context.raw;
25148          return label + '(' + dataPoint.x + ', ' + dataPoint.y + ', ' + dataPoint.v + ')';
25149        };
25150      } else if (chartType === "pie") {
25151        // need to use separate label for pie charts
25152        options.plugins.tooltip.callbacks.label = function (context) {
25153          var dataLabel = context.label;
25154          var value = ': ';
25155
25156          if (isArray(dataLabel)) {
25157            // show value on first line of multiline label
25158            // need to clone because we are changing the value
25159            dataLabel = dataLabel.slice();
25160            dataLabel[0] += value;
25161          } else {
25162            dataLabel += value;
25163          }
25164
25165          return formatValue(dataLabel, context.parsed, formatOptions);
25166        };
25167      } else {
25168        var valueLabel = chartType === "bar" ? "x" : "y";
25169        options.plugins.tooltip.callbacks.label = function (context) {
25170          // don't show null values for stacked charts
25171          if (context.parsed[valueLabel] === null) {
25172            return;
25173          }
25174
25175          var label = context.dataset.label || '';
25176          if (label) {
25177            label += ': ';
25178          }
25179          return formatValue(label, context.parsed[valueLabel], formatOptions);
25180        };
25181      }
25182    }
25183  };
25184
25185  var jsOptions$2 = jsOptionsFunc(merge(baseOptions, defaultOptions$2), hideLegend$2, setTitle$2, setMin$2, setMax$2, setStacked$2, setXtitle$2, setYtitle$2);
25186
25187  var createDataTable = function (chart, options, chartType) {
25188    var datasets = [];
25189    var labels = [];
25190
25191    var colors = chart.options.colors || defaultColors;
25192
25193    var day = true;
25194    var week = true;
25195    var dayOfWeek;
25196    var month = true;
25197    var year = true;
25198    var hour = true;
25199    var minute = true;
25200
25201    var series = chart.data;
25202
25203    var max = 0;
25204    if (chartType === "bubble") {
25205      for (var i$1 = 0; i$1 < series.length; i$1++) {
25206        var s$1 = series[i$1];
25207        for (var j$1 = 0; j$1 < s$1.data.length; j$1++) {
25208          if (s$1.data[j$1][2] > max) {
25209            max = s$1.data[j$1][2];
25210          }
25211        }
25212      }
25213    }
25214
25215    var i, j, s, d, key, rows = [], rows2 = [];
25216
25217    if (chartType === "bar" || chartType === "column" || (chart.xtype !== "number" && chart.xtype !== "bubble")) {
25218      var sortedLabels = [];
25219
25220      for (i = 0; i < series.length; i++) {
25221        s = series[i];
25222
25223        for (j = 0; j < s.data.length; j++) {
25224          d = s.data[j];
25225          key = chart.xtype == "datetime" ? d[0].getTime() : d[0];
25226          if (!rows[key]) {
25227            rows[key] = new Array(series.length);
25228          }
25229          rows[key][i] = toFloat(d[1]);
25230          if (sortedLabels.indexOf(key) === -1) {
25231            sortedLabels.push(key);
25232          }
25233        }
25234      }
25235
25236      if (chart.xtype === "datetime" || chart.xtype === "number") {
25237        sortedLabels.sort(sortByNumber);
25238      }
25239
25240      for (j = 0; j < series.length; j++) {
25241        rows2.push([]);
25242      }
25243
25244      var value;
25245      var k;
25246      for (k = 0; k < sortedLabels.length; k++) {
25247        i = sortedLabels[k];
25248        if (chart.xtype === "datetime") {
25249          value = new Date(toFloat(i));
25250          // TODO make this efficient
25251          day = day && isDay(value);
25252          if (!dayOfWeek) {
25253            dayOfWeek = value.getDay();
25254          }
25255          week = week && isWeek(value, dayOfWeek);
25256          month = month && isMonth(value);
25257          year = year && isYear(value);
25258          hour = hour && isHour(value);
25259          minute = minute && isMinute(value);
25260        } else {
25261          value = i;
25262        }
25263        labels.push(value);
25264        for (j = 0; j < series.length; j++) {
25265          // Chart.js doesn't like undefined
25266          rows2[j].push(rows[i][j] === undefined ? null : rows[i][j]);
25267        }
25268      }
25269    } else {
25270      for (var i$2 = 0; i$2 < series.length; i$2++) {
25271        var s$2 = series[i$2];
25272        var d$1 = [];
25273        for (var j$2 = 0; j$2 < s$2.data.length; j$2++) {
25274          var point = {
25275            x: toFloat(s$2.data[j$2][0]),
25276            y: toFloat(s$2.data[j$2][1])
25277          };
25278          if (chartType === "bubble") {
25279            point.r = toFloat(s$2.data[j$2][2]) * 20 / max;
25280            // custom attribute, for tooltip
25281            point.v = s$2.data[j$2][2];
25282          }
25283          d$1.push(point);
25284        }
25285        rows2.push(d$1);
25286      }
25287    }
25288
25289    var color;
25290    var backgroundColor;
25291
25292    for (i = 0; i < series.length; i++) {
25293      s = series[i];
25294
25295      // use colors for each bar for single series format
25296      if (chart.options.colors && chart.singleSeriesFormat && (chartType === "bar" || chartType === "column") && !s.color && isArray(chart.options.colors) && !isArray(chart.options.colors[0])) {
25297        color = colors;
25298        backgroundColor = [];
25299        for (var j$3 = 0; j$3 < colors.length; j$3++) {
25300          backgroundColor[j$3] = addOpacity(color[j$3], 0.5);
25301        }
25302      } else {
25303        color = s.color || colors[i];
25304        backgroundColor = chartType !== "line" ? addOpacity(color, 0.5) : color;
25305      }
25306
25307      var dataset = {
25308        label: s.name || "",
25309        data: rows2[i],
25310        fill: chartType === "area",
25311        borderColor: color,
25312        backgroundColor: backgroundColor,
25313        borderWidth: 2
25314      };
25315
25316      var pointChart = chartType === "line" || chartType === "area" || chartType === "scatter" || chartType === "bubble";
25317      if (pointChart) {
vendor: 28,133 bytes, lines 25318-26322
25318        dataset.pointBackgroundColor = color;
25319        dataset.pointHoverBackgroundColor = color;
25320        dataset.pointHitRadius = 50;
25321      }
25322
25323      if (chartType === "bubble") {
25324        dataset.pointBackgroundColor = backgroundColor;
25325        dataset.pointHoverBackgroundColor = backgroundColor;
25326        dataset.pointHoverBorderWidth = 2;
25327      }
25328
25329      if (s.stack) {
25330        dataset.stack = s.stack;
25331      }
25332
25333      var curve = seriesOption(chart, s, "curve");
25334      if (curve === false) {
25335        dataset.tension = 0;
25336      } else if (pointChart) {
25337        dataset.tension = 0.4;
25338      }
25339
25340      var points = seriesOption(chart, s, "points");
25341      if (points === false) {
25342        dataset.pointRadius = 0;
25343        dataset.pointHoverRadius = 0;
25344      }
25345
25346      dataset = merge(dataset, chart.options.dataset || {});
25347      dataset = merge(dataset, s.library || {});
25348      dataset = merge(dataset, s.dataset || {});
25349
25350      datasets.push(dataset);
25351    }
25352
25353    var xmin = chart.options.xmin;
25354    var xmax = chart.options.xmax;
25355
25356    if (chart.xtype === "datetime") {
25357      if (notnull(xmin)) {
25358        options.scales.x.ticks.min = toDate(xmin).getTime();
25359      }
25360      if (notnull(xmax)) {
25361        options.scales.x.ticks.max = toDate(xmax).getTime();
25362      }
25363    } else if (chart.xtype === "number") {
25364      if (notnull(xmin)) {
25365        options.scales.x.ticks.min = xmin;
25366      }
25367      if (notnull(xmax)) {
25368        options.scales.x.ticks.max = xmax;
25369      }
25370    }
25371
25372    // for empty datetime chart
25373    if (chart.xtype === "datetime" && labels.length === 0) {
25374      if (notnull(xmin)) {
25375        labels.push(toDate(xmin));
25376      }
25377      if (notnull(xmax)) {
25378        labels.push(toDate(xmax));
25379      }
25380      day = false;
25381      week = false;
25382      month = false;
25383      year = false;
25384      hour = false;
25385      minute = false;
25386    }
25387
25388    if (chart.xtype === "datetime" && labels.length > 0) {
25389      var minTime = (notnull(xmin) ? toDate(xmin) : labels[0]).getTime();
25390      var maxTime = (notnull(xmax) ? toDate(xmax) : labels[0]).getTime();
25391
25392      for (i = 1; i < labels.length; i++) {
25393        var value$1 = labels[i].getTime();
25394        if (value$1 < minTime) {
25395          minTime = value$1;
25396        }
25397        if (value$1 > maxTime) {
25398          maxTime = value$1;
25399        }
25400      }
25401
25402      var timeDiff = (maxTime - minTime) / (86400 * 1000.0);
25403
25404      if (!options.scales.x.time.unit) {
25405        var step;
25406        if (year || timeDiff > 365 * 10) {
25407          options.scales.x.time.unit = "year";
25408          step = 365;
25409        } else if (month || timeDiff > 30 * 10) {
25410          options.scales.x.time.unit = "month";
25411          step = 30;
25412        } else if (day || timeDiff > 10) {
25413          options.scales.x.time.unit = "day";
25414          step = 1;
25415        } else if (hour || timeDiff > 0.5) {
25416          options.scales.x.time.displayFormats = {hour: "MMM d, h a"};
25417          options.scales.x.time.unit = "hour";
25418          step = 1 / 24.0;
25419        } else if (minute) {
25420          options.scales.x.time.displayFormats = {minute: "h:mm a"};
25421          options.scales.x.time.unit = "minute";
25422          step = 1 / 24.0 / 60.0;
25423        }
25424
25425        if (step && timeDiff > 0) {
25426          // width not available for hidden elements
25427          var width = chart.element.offsetWidth;
25428          if (width > 0) {
25429            var unitStepSize = Math.ceil(timeDiff / step / (width / 100.0));
25430            if (week && step === 1) {
25431              unitStepSize = Math.ceil(unitStepSize / 7.0) * 7;
25432            }
25433            options.scales.x.time.stepSize = unitStepSize;
25434          }
25435        }
25436      }
25437
25438      if (!options.scales.x.time.tooltipFormat) {
25439        if (day) {
25440          options.scales.x.time.tooltipFormat = "PP";
25441        } else if (hour) {
25442          options.scales.x.time.tooltipFormat = "MMM d, h a";
25443        } else if (minute) {
25444          options.scales.x.time.tooltipFormat = "h:mm a";
25445        }
25446      }
25447    }
25448
25449    var data = {
25450      labels: labels,
25451      datasets: datasets
25452    };
25453
25454    return data;
25455  };
25456
25457  var defaultExport$2 = function defaultExport(library) {
25458    this.name = "chartjs";
25459    this.library = library;
25460  };
25461
25462  defaultExport$2.prototype.renderLineChart = function renderLineChart (chart, chartType) {
25463    var chartOptions = {};
25464    // fix for https://github.com/chartjs/Chart.js/issues/2441
25465    if (!chart.options.max && allZeros(chart.data)) {
25466      chartOptions.max = 1;
25467    }
25468
25469    var options = jsOptions$2(chart, merge(chartOptions, chart.options));
25470    setFormatOptions$1(chart, options, chartType);
25471
25472    var data = createDataTable(chart, options, chartType || "line");
25473
25474    if (chart.xtype === "number") {
25475      options.scales.x.type = options.scales.x.type || "linear";
25476      options.scales.x.position = options.scales.x.position ||"bottom";
25477    } else {
25478      options.scales.x.type = chart.xtype === "string" ? "category" : "time";
25479    }
25480
25481    this.drawChart(chart, "line", data, options);
25482  };
25483
25484  defaultExport$2.prototype.renderPieChart = function renderPieChart (chart) {
25485    var options = merge({}, baseOptions);
25486    if (chart.options.donut) {
25487      options.cutout = "50%";
25488    }
25489
25490    if ("legend" in chart.options) {
25491      hideLegend$2(options, chart.options.legend);
25492    }
25493
25494    if (chart.options.title) {
25495      setTitle$2(options, chart.options.title);
25496    }
25497
25498    options = merge(options, chart.options.library || {});
25499    setFormatOptions$1(chart, options, "pie");
25500
25501    var labels = [];
25502    var values = [];
25503    for (var i = 0; i < chart.data.length; i++) {
25504      var point = chart.data[i];
25505      labels.push(point[0]);
25506      values.push(point[1]);
25507    }
25508
25509    var dataset = {
25510      data: values,
25511      backgroundColor: chart.options.colors || defaultColors
25512    };
25513    dataset = merge(dataset, chart.options.dataset || {});
25514
25515    var data = {
25516      labels: labels,
25517      datasets: [dataset]
25518    };
25519
25520    this.drawChart(chart, "pie", data, options);
25521  };
25522
25523  defaultExport$2.prototype.renderColumnChart = function renderColumnChart (chart, chartType) {
25524    var options;
25525    if (chartType === "bar") {
25526      var barOptions = merge(baseOptions, defaultOptions$2);
25527      barOptions.indexAxis = "y";
25528
25529      // ensure gridlines have proper orientation
25530      barOptions.scales.x.grid.drawOnChartArea = true;
25531      barOptions.scales.y.grid.drawOnChartArea = false;
25532      delete barOptions.scales.y.ticks.maxTicksLimit;
25533
25534      options = jsOptionsFunc(barOptions, hideLegend$2, setTitle$2, setBarMin$1, setBarMax$1, setStacked$2, setXtitle$2, setYtitle$2)(chart, chart.options);
25535    } else {
25536      options = jsOptions$2(chart, chart.options);
25537    }
25538    setFormatOptions$1(chart, options, chartType);
25539    var data = createDataTable(chart, options, "column");
25540    if (chartType !== "bar") {
25541      setLabelSize(chart, data, options);
25542    }
25543    this.drawChart(chart, "bar", data, options);
25544  };
25545
25546  defaultExport$2.prototype.renderAreaChart = function renderAreaChart (chart) {
25547    this.renderLineChart(chart, "area");
25548  };
25549
25550  defaultExport$2.prototype.renderBarChart = function renderBarChart (chart) {
25551    this.renderColumnChart(chart, "bar");
25552  };
25553
25554  defaultExport$2.prototype.renderScatterChart = function renderScatterChart (chart, chartType) {
25555    chartType = chartType || "scatter";
25556
25557    var options = jsOptions$2(chart, chart.options);
25558    setFormatOptions$1(chart, options, chartType);
25559
25560    if (!("showLine" in options)) {
25561      options.showLine = false;
25562    }
25563
25564    var data = createDataTable(chart, options, chartType);
25565
25566    options.scales.x.type = options.scales.x.type || "linear";
25567    options.scales.x.position = options.scales.x.position || "bottom";
25568
25569    // prevent grouping hover and tooltips
25570    if (!("mode" in options.interaction)) {
25571      options.interaction.mode = "nearest";
25572    }
25573
25574    this.drawChart(chart, chartType, data, options);
25575  };
25576
25577  defaultExport$2.prototype.renderBubbleChart = function renderBubbleChart (chart) {
25578    this.renderScatterChart(chart, "bubble");
25579  };
25580
25581  defaultExport$2.prototype.destroy = function destroy (chart) {
25582    if (chart.chart) {
25583      chart.chart.destroy();
25584    }
25585  };
25586
25587  defaultExport$2.prototype.drawChart = function drawChart (chart, type, data, options) {
25588    this.destroy(chart);
25589    if (chart.destroyed) { return; }
25590
25591    var chartOptions = {
25592      type: type,
25593      data: data,
25594      options: options
25595    };
25596
25597    if (chart.options.code) {
25598      window.console.log("new Chart(ctx, " + JSON.stringify(chartOptions) + ");");
25599    }
25600
25601    chart.element.innerHTML = "<canvas></canvas>";
25602    var ctx = chart.element.getElementsByTagName("CANVAS")[0];
25603    chart.chart = new this.library(ctx, chartOptions);
25604  };
25605
25606  var defaultOptions$1 = {
25607    chart: {},
25608    xAxis: {
25609      title: {
25610        text: null
25611      },
25612      labels: {
25613        style: {
25614          fontSize: "12px"
25615        }
25616      }
25617    },
25618    yAxis: {
25619      title: {
25620        text: null
25621      },
25622      labels: {
25623        style: {
25624          fontSize: "12px"
25625        }
25626      }
25627    },
25628    title: {
25629      text: null
25630    },
25631    credits: {
25632      enabled: false
25633    },
25634    legend: {
25635      borderWidth: 0
25636    },
25637    tooltip: {
25638      style: {
25639        fontSize: "12px"
25640      }
25641    },
25642    plotOptions: {
25643      areaspline: {},
25644      area: {},
25645      series: {
25646        marker: {}
25647      }
25648    },
25649    time: {
25650      useUTC: false
25651    }
25652  };
25653
25654  var hideLegend$1 = function (options, legend, hideLegend) {
25655    if (legend !== undefined) {
25656      options.legend.enabled = !!legend;
25657      if (legend && legend !== true) {
25658        if (legend === "top" || legend === "bottom") {
25659          options.legend.verticalAlign = legend;
25660        } else {
25661          options.legend.layout = "vertical";
25662          options.legend.verticalAlign = "middle";
25663          options.legend.align = legend;
25664        }
25665      }
25666    } else if (hideLegend) {
25667      options.legend.enabled = false;
25668    }
25669  };
25670
25671  var setTitle$1 = function (options, title) {
25672    options.title.text = title;
25673  };
25674
25675  var setMin$1 = function (options, min) {
25676    options.yAxis.min = min;
25677  };
25678
25679  var setMax$1 = function (options, max) {
25680    options.yAxis.max = max;
25681  };
25682
25683  var setStacked$1 = function (options, stacked) {
25684    var stackedValue = stacked ? (stacked === true ? "normal" : stacked) : null;
25685    options.plotOptions.series.stacking = stackedValue;
25686    options.plotOptions.area.stacking = stackedValue;
25687    options.plotOptions.areaspline.stacking = stackedValue;
25688  };
25689
25690  var setXtitle$1 = function (options, title) {
25691    options.xAxis.title.text = title;
25692  };
25693
25694  var setYtitle$1 = function (options, title) {
25695    options.yAxis.title.text = title;
25696  };
25697
25698  var jsOptions$1 = jsOptionsFunc(defaultOptions$1, hideLegend$1, setTitle$1, setMin$1, setMax$1, setStacked$1, setXtitle$1, setYtitle$1);
25699
25700  var setFormatOptions = function(chart, options, chartType) {
25701    var formatOptions = {
25702      prefix: chart.options.prefix,
25703      suffix: chart.options.suffix,
25704      thousands: chart.options.thousands,
25705      decimal: chart.options.decimal,
25706      precision: chart.options.precision,
25707      round: chart.options.round,
25708      zeros: chart.options.zeros
25709    };
25710
25711    if (chartType !== "pie" && !options.yAxis.labels.formatter) {
25712      options.yAxis.labels.formatter = function () {
25713        return formatValue("", this.value, formatOptions);
25714      };
25715    }
25716
25717    if (!options.tooltip.pointFormatter && !options.tooltip.pointFormat) {
25718      options.tooltip.pointFormatter = function () {
25719        return '<span style="color:' + this.color + '">\u25CF</span> ' + formatValue(this.series.name + ': <b>', this.y, formatOptions) + '</b><br/>';
25720      };
25721    }
25722  };
25723
25724  var defaultExport$1 = function defaultExport(library) {
25725    this.name = "highcharts";
25726    this.library = library;
25727  };
25728
25729  defaultExport$1.prototype.renderLineChart = function renderLineChart (chart, chartType) {
25730    chartType = chartType || "spline";
25731    var chartOptions = {};
25732    if (chartType === "areaspline") {
25733      chartOptions = {
25734        plotOptions: {
25735          areaspline: {
25736            stacking: "normal"
25737          },
25738          area: {
25739            stacking: "normal"
25740          },
25741          series: {
25742            marker: {
25743              enabled: false
25744            }
25745          }
25746        }
25747      };
25748    }
25749
25750    if (chart.options.curve === false) {
25751      if (chartType === "areaspline") {
25752        chartType = "area";
25753      } else if (chartType === "spline") {
25754        chartType = "line";
25755      }
25756    }
25757
25758    var options = jsOptions$1(chart, chart.options, chartOptions), data, i, j;
25759    if (chart.xtype === "number") {
25760      options.xAxis.type = options.xAxis.type || "linear";
25761    } else {
25762      options.xAxis.type = chart.xtype === "string" ? "category" : "datetime";
25763    }
25764    if (!options.chart.type) {
25765      options.chart.type = chartType;
25766    }
25767    setFormatOptions(chart, options, chartType);
25768
25769    var series = chart.data;
25770    for (i = 0; i < series.length; i++) {
25771      series[i].name = series[i].name || "Value";
25772      data = series[i].data;
25773      if (chart.xtype === "datetime") {
25774        for (j = 0; j < data.length; j++) {
25775          data[j][0] = data[j][0].getTime();
25776        }
25777      }
25778      series[i].marker = {symbol: "circle"};
25779      if (chart.options.points === false) {
25780        series[i].marker.enabled = false;
25781      }
25782    }
25783
25784    this.drawChart(chart, series, options);
25785  };
25786
25787  defaultExport$1.prototype.renderScatterChart = function renderScatterChart (chart) {
25788    var options = jsOptions$1(chart, chart.options, {});
25789    options.chart.type = "scatter";
25790    this.drawChart(chart, chart.data, options);
25791  };
25792
25793  defaultExport$1.prototype.renderPieChart = function renderPieChart (chart) {
25794    var chartOptions = merge(defaultOptions$1, {});
25795
25796    if (chart.options.colors) {
25797      chartOptions.colors = chart.options.colors;
25798    }
25799    if (chart.options.donut) {
25800      chartOptions.plotOptions = {pie: {innerSize: "50%"}};
25801    }
25802
25803    if ("legend" in chart.options) {
25804      hideLegend$1(chartOptions, chart.options.legend);
25805    }
25806
25807    if (chart.options.title) {
25808      setTitle$1(chartOptions, chart.options.title);
25809    }
25810
25811    var options = merge(chartOptions, chart.options.library || {});
25812    setFormatOptions(chart, options, "pie");
25813    var series = [{
25814      type: "pie",
25815      name: chart.options.label || "Value",
25816      data: chart.data
25817    }];
25818
25819    this.drawChart(chart, series, options);
25820  };
25821
25822  defaultExport$1.prototype.renderColumnChart = function renderColumnChart (chart, chartType) {
25823    chartType = chartType || "column";
25824    var series = chart.data;
25825    var options = jsOptions$1(chart, chart.options), i, j, s, d, rows = [], categories = [];
25826    options.chart.type = chartType;
25827    setFormatOptions(chart, options, chartType);
25828
25829    for (i = 0; i < series.length; i++) {
25830      s = series[i];
25831
25832      for (j = 0; j < s.data.length; j++) {
25833        d = s.data[j];
25834        if (!rows[d[0]]) {
25835          rows[d[0]] = new Array(series.length);
25836          categories.push(d[0]);
25837        }
25838        rows[d[0]][i] = d[1];
25839      }
25840    }
25841
25842    if (chart.xtype === "number") {
25843      categories.sort(sortByNumber);
25844    }
25845
25846    options.xAxis.categories = categories;
25847
25848    var newSeries = [], d2;
25849    for (i = 0; i < series.length; i++) {
25850      d = [];
25851      for (j = 0; j < categories.length; j++) {
25852        d.push(rows[categories[j]][i] || 0);
25853      }
25854
25855      d2 = {
25856        name: series[i].name || "Value",
25857        data: d
25858      };
25859      if (series[i].stack) {
25860        d2.stack = series[i].stack;
25861      }
25862
25863      newSeries.push(d2);
25864    }
25865
25866    this.drawChart(chart, newSeries, options);
25867  };
25868
25869  defaultExport$1.prototype.renderBarChart = function renderBarChart (chart) {
25870    this.renderColumnChart(chart, "bar");
25871  };
25872
25873  defaultExport$1.prototype.renderAreaChart = function renderAreaChart (chart) {
25874    this.renderLineChart(chart, "areaspline");
25875  };
25876
25877  defaultExport$1.prototype.destroy = function destroy (chart) {
25878    if (chart.chart) {
25879      chart.chart.destroy();
25880    }
25881  };
25882
25883  defaultExport$1.prototype.drawChart = function drawChart (chart, data, options) {
25884    this.destroy(chart);
25885    if (chart.destroyed) { return; }
25886
25887    options.chart.renderTo = chart.element.id;
25888    options.series = data;
25889
25890    if (chart.options.code) {
25891      window.console.log("new Highcharts.Chart(" + JSON.stringify(options) + ");");
25892    }
25893
25894    chart.chart = new this.library.Chart(options);
25895  };
25896
25897  var loaded = {};
25898  var callbacks = [];
25899
25900  // Set chart options
25901  var defaultOptions = {
25902    chartArea: {},
25903    fontName: "'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif",
25904    pointSize: 6,
25905    legend: {
25906      textStyle: {
25907        fontSize: 12,
25908        color: "#444"
25909      },
25910      alignment: "center",
25911      position: "right"
25912    },
25913    curveType: "function",
25914    hAxis: {
25915      textStyle: {
25916        color: "#666",
25917        fontSize: 12
25918      },
25919      titleTextStyle: {},
25920      gridlines: {
25921        color: "transparent"
25922      },
25923      baselineColor: "#ccc",
25924      viewWindow: {}
25925    },
25926    vAxis: {
25927      textStyle: {
25928        color: "#666",
25929        fontSize: 12
25930      },
25931      titleTextStyle: {},
25932      baselineColor: "#ccc",
25933      viewWindow: {}
25934    },
25935    tooltip: {
25936      textStyle: {
25937        color: "#666",
25938        fontSize: 12
25939      }
25940    }
25941  };
25942
25943  var hideLegend = function (options, legend, hideLegend) {
25944    if (legend !== undefined) {
25945      var position;
25946      if (!legend) {
25947        position = "none";
25948      } else if (legend === true) {
25949        position = "right";
25950      } else {
25951        position = legend;
25952      }
25953      options.legend.position = position;
25954    } else if (hideLegend) {
25955      options.legend.position = "none";
25956    }
25957  };
25958
25959  var setTitle = function (options, title) {
25960    options.title = title;
25961    options.titleTextStyle = {color: "#333", fontSize: "20px"};
25962  };
25963
25964  var setMin = function (options, min) {
25965    options.vAxis.viewWindow.min = min;
25966  };
25967
25968  var setMax = function (options, max) {
25969    options.vAxis.viewWindow.max = max;
25970  };
25971
25972  var setBarMin = function (options, min) {
25973    options.hAxis.viewWindow.min = min;
25974  };
25975
25976  var setBarMax = function (options, max) {
25977    options.hAxis.viewWindow.max = max;
25978  };
25979
25980  var setStacked = function (options, stacked) {
25981    options.isStacked = stacked ? stacked : false;
25982  };
25983
25984  var setXtitle = function (options, title) {
25985    options.hAxis.title = title;
25986    options.hAxis.titleTextStyle.italic = false;
25987  };
25988
25989  var setYtitle = function (options, title) {
25990    options.vAxis.title = title;
25991    options.vAxis.titleTextStyle.italic = false;
25992  };
25993
25994  var jsOptions = jsOptionsFunc(defaultOptions, hideLegend, setTitle, setMin, setMax, setStacked, setXtitle, setYtitle);
25995
25996  var resize = function (callback) {
25997    if (window.attachEvent) {
25998      window.attachEvent("onresize", callback);
25999    } else if (window.addEventListener) {
26000      window.addEventListener("resize", callback, true);
26001    }
26002    callback();
26003  };
26004
26005  var defaultExport = function defaultExport(library) {
26006    this.name = "google";
26007    this.library = library;
26008  };
26009
26010  defaultExport.prototype.renderLineChart = function renderLineChart (chart) {
26011      var this$1 = this;
26012
26013    this.waitForLoaded(chart, function () {
26014      var chartOptions = {};
26015
26016      if (chart.options.curve === false) {
26017        chartOptions.curveType = "none";
26018      }
26019
26020      if (chart.options.points === false) {
26021        chartOptions.pointSize = 0;
26022      }
26023
26024      var options = jsOptions(chart, chart.options, chartOptions);
26025      var data = this$1.createDataTable(chart.data, chart.xtype);
26026
26027      this$1.drawChart(chart, "LineChart", data, options);
26028    });
26029  };
26030
26031  defaultExport.prototype.renderPieChart = function renderPieChart (chart) {
26032      var this$1 = this;
26033
26034    this.waitForLoaded(chart, function () {
26035      var chartOptions = {
26036        chartArea: {
26037          top: "10%",
26038          height: "80%"
26039        },
26040        legend: {}
26041      };
26042      if (chart.options.colors) {
26043        chartOptions.colors = chart.options.colors;
26044      }
26045      if (chart.options.donut) {
26046        chartOptions.pieHole = 0.5;
26047      }
26048      if ("legend" in chart.options) {
26049        hideLegend(chartOptions, chart.options.legend);
26050      }
26051      if (chart.options.title) {
26052        setTitle(chartOptions, chart.options.title);
26053      }
26054      var options = merge(merge(defaultOptions, chartOptions), chart.options.library || {});
26055
26056      var data = new this$1.library.visualization.DataTable();
26057      data.addColumn("string", "");
26058      data.addColumn("number", "Value");
26059      data.addRows(chart.data);
26060
26061      this$1.drawChart(chart, "PieChart", data, options);
26062    });
26063  };
26064
26065  defaultExport.prototype.renderColumnChart = function renderColumnChart (chart) {
26066      var this$1 = this;
26067
26068    this.waitForLoaded(chart, function () {
26069      var options = jsOptions(chart, chart.options);
26070      var data = this$1.createDataTable(chart.data, chart.xtype);
26071
26072      this$1.drawChart(chart, "ColumnChart", data, options);
26073    });
26074  };
26075
26076  defaultExport.prototype.renderBarChart = function renderBarChart (chart) {
26077      var this$1 = this;
26078
26079    this.waitForLoaded(chart, function () {
26080      var chartOptions = {
26081        hAxis: {
26082          gridlines: {
26083            color: "#ccc"
26084          }
26085        }
26086      };
26087      var options = jsOptionsFunc(defaultOptions, hideLegend, setTitle, setBarMin, setBarMax, setStacked, setXtitle, setYtitle)(chart, chart.options, chartOptions);
26088      var data = this$1.createDataTable(chart.data, chart.xtype);
26089
26090      this$1.drawChart(chart, "BarChart", data, options);
26091    });
26092  };
26093
26094  defaultExport.prototype.renderAreaChart = function renderAreaChart (chart) {
26095      var this$1 = this;
26096
26097    this.waitForLoaded(chart, function () {
26098      var chartOptions = {
26099        isStacked: true,
26100        pointSize: 0,
26101        areaOpacity: 0.5
26102      };
26103
26104      var options = jsOptions(chart, chart.options, chartOptions);
26105      var data = this$1.createDataTable(chart.data, chart.xtype);
26106
26107      this$1.drawChart(chart, "AreaChart", data, options);
26108    });
26109  };
26110
26111  defaultExport.prototype.renderGeoChart = function renderGeoChart (chart) {
26112      var this$1 = this;
26113
26114    this.waitForLoaded(chart, "geochart", function () {
26115      var chartOptions = {
26116        legend: "none",
26117        colorAxis: {
26118          colors: chart.options.colors || ["#f6c7b6", "#ce502d"]
26119        }
26120      };
26121      var options = merge(merge(defaultOptions, chartOptions), chart.options.library || {});
26122
26123      var data = new this$1.library.visualization.DataTable();
26124      data.addColumn("string", "");
26125      data.addColumn("number", chart.options.label || "Value");
26126      data.addRows(chart.data);
26127
26128      this$1.drawChart(chart, "GeoChart", data, options);
26129    });
26130  };
26131
26132  defaultExport.prototype.renderScatterChart = function renderScatterChart (chart) {
26133      var this$1 = this;
26134
26135    this.waitForLoaded(chart, function () {
26136      var chartOptions = {};
26137      var options = jsOptions(chart, chart.options, chartOptions);
26138
26139      var series = chart.data, rows2 = [], i, j, data, d;
26140      for (i = 0; i < series.length; i++) {
26141        series[i].name = series[i].name || "Value";
26142        d = series[i].data;
26143        for (j = 0; j < d.length; j++) {
26144          var row = new Array(series.length + 1);
26145          row[0] = d[j][0];
26146          row[i + 1] = d[j][1];
26147          rows2.push(row);
26148        }
26149      }
26150
26151      data = new this$1.library.visualization.DataTable();
26152      data.addColumn("number", "");
26153      for (i = 0; i < series.length; i++) {
26154        data.addColumn("number", series[i].name);
26155      }
26156      data.addRows(rows2);
26157
26158      this$1.drawChart(chart, "ScatterChart", data, options);
26159    });
26160  };
26161
26162  defaultExport.prototype.renderTimeline = function renderTimeline (chart) {
26163      var this$1 = this;
26164
26165    this.waitForLoaded(chart, "timeline", function () {
26166      var chartOptions = {
26167        legend: "none"
26168      };
26169
26170      if (chart.options.colors) {
26171        chartOptions.colors = chart.options.colors;
26172      }
26173      var options = merge(merge(defaultOptions, chartOptions), chart.options.library || {});
26174
26175      var data = new this$1.library.visualization.DataTable();
26176      data.addColumn({type: "string", id: "Name"});
26177      data.addColumn({type: "date", id: "Start"});
26178      data.addColumn({type: "date", id: "End"});
26179      data.addRows(chart.data);
26180
26181      chart.element.style.lineHeight = "normal";
26182
26183      this$1.drawChart(chart, "Timeline", data, options);
26184    });
26185  };
26186
26187  // TODO remove resize events
26188  defaultExport.prototype.destroy = function destroy (chart) {
26189    if (chart.chart) {
26190      chart.chart.clearChart();
26191    }
26192  };
26193
26194  defaultExport.prototype.drawChart = function drawChart (chart, type, data, options) {
26195    this.destroy(chart);
26196    if (chart.destroyed) { return; }
26197
26198    if (chart.options.code) {
26199      window.console.log("var data = new google.visualization.DataTable(" + data.toJSON() + ");\nvar chart = new google.visualization." + type + "(element);\nchart.draw(data, " + JSON.stringify(options) + ");");
26200    }
26201
26202    chart.chart = new this.library.visualization[type](chart.element);
26203    resize(function () {
26204      chart.chart.draw(data, options);
26205    });
26206  };
26207
26208  defaultExport.prototype.waitForLoaded = function waitForLoaded (chart, pack, callback) {
26209      var this$1 = this;
26210
26211    if (!callback) {
26212      callback = pack;
26213      pack = "corechart";
26214    }
26215
26216    callbacks.push({pack: pack, callback: callback});
26217
26218    if (loaded[pack]) {
26219      this.runCallbacks();
26220    } else {
26221      loaded[pack] = true;
26222
26223      // https://groups.google.com/forum/#!topic/google-visualization-api/fMKJcyA2yyI
26224      var loadOptions = {
26225        packages: [pack],
26226        callback: function () { this$1.runCallbacks(); }
26227      };
26228      var config = chart.__config();
26229      if (config.language) {
26230        loadOptions.language = config.language;
26231      }
26232      if (pack === "geochart" && config.mapsApiKey) {
26233        loadOptions.mapsApiKey = config.mapsApiKey;
26234      }
26235
26236      this.library.charts.load("current", loadOptions);
26237    }
26238  };
26239
26240  defaultExport.prototype.runCallbacks = function runCallbacks () {
26241    var cb, call;
26242    for (var i = 0; i < callbacks.length; i++) {
26243      cb = callbacks[i];
26244      call = this.library.visualization && ((cb.pack === "corechart" && this.library.visualization.LineChart) || (cb.pack === "timeline" && this.library.visualization.Timeline) || (cb.pack === "geochart" && this.library.visualization.GeoChart));
26245      if (call) {
26246        cb.callback();
26247        callbacks.splice(i, 1);
26248        i--;
26249      }
26250    }
26251  };
26252
26253  // cant use object as key
26254  defaultExport.prototype.createDataTable = function createDataTable (series, columnType) {
26255    var i, j, s, d, key, rows = [], sortedLabels = [];
26256    for (i = 0; i < series.length; i++) {
26257      s = series[i];
26258      series[i].name = series[i].name || "Value";
26259
26260      for (j = 0; j < s.data.length; j++) {
26261        d = s.data[j];
26262        key = (columnType === "datetime") ? d[0].getTime() : d[0];
26263        if (!rows[key]) {
26264          rows[key] = new Array(series.length);
26265          sortedLabels.push(key);
26266        }
26267        rows[key][i] = toFloat(d[1]);
26268      }
26269    }
26270
26271    var rows2 = [];
26272    var day = true;
26273    var value;
26274    for (j = 0; j < sortedLabels.length; j++) {
26275      i = sortedLabels[j];
26276      if (columnType === "datetime") {
26277        value = new Date(toFloat(i));
26278        day = day && isDay(value);
26279      } else if (columnType === "number") {
26280        value = toFloat(i);
26281      } else {
26282        value = i;
26283      }
26284      rows2.push([value].concat(rows[i]));
26285    }
26286    if (columnType === "datetime") {
26287      rows2.sort(sortByTime);
26288    } else if (columnType === "number") {
26289      rows2.sort(sortByNumberSeries);
26290
26291      for (i = 0; i < rows2.length; i++) {
26292        rows2[i][0] = toStr(rows2[i][0]);
26293      }
26294
26295      columnType = "string";
26296    }
26297
26298    // create datatable
26299    var data = new this.library.visualization.DataTable();
26300    columnType = columnType === "datetime" && day ? "date" : columnType;
26301    data.addColumn(columnType, "");
26302    for (i = 0; i < series.length; i++) {
26303      data.addColumn("number", series[i].name);
26304    }
26305    data.addRows(rows2);
26306
26307    return data;
26308  };
26309
26310  function formatSeriesData(data, keyType) {
26311    var r = [], j, keyFunc;
26312
26313    if (keyType === "number") {
26314      keyFunc = toFloat;
26315    } else if (keyType === "datetime") {
26316      keyFunc = toDate;
26317    } else {
26318      keyFunc = toStr;
26319    }
26320
26321    if (keyType === "bubble") {
26322      for (j = 0; j < data.length; j++) {
26323        r.push([toFloat(data[j][0]), toFloat(data[j][1]), toFloat(data[j][2])]);
26324      }
26325    } else {
26326      for (j = 0; j < data.length; j++) {
26327        r.push([keyFunc(data[j][0]), toFloat(data[j][1])]);
26328      }
26329    }
26330
26331    if (keyType === "datetime") {
26332      r.sort(sortByTime);
26333    } else if (keyType === "number") {
26334      r.sort(sortByNumberSeries);
26335    }
26336
26337    return r;
26338  }
26339
26340  function detectXType(series, noDatetime, options) {
26341    if (dataEmpty(series)) {
26342      if ((options.xmin || options.xmax) && (!options.xmin || isDate(options.xmin)) && (!options.xmax || isDate(options.xmax))) {
26343        return "datetime";
26344      } else {
26345        return "number";
26346      }
26347    } else if (detectXTypeWithFunction(series, isNumber)) {
26348      return "number";
26349    } else if (!noDatetime && detectXTypeWithFunction(series, isDate)) {
26350      return "datetime";
26351    } else {
26352      return "string";
26353    }
26354  }
26355
26356  function detectXTypeWithFunction(series, func) {
26357    var i, j, data;
26358    for (i = 0; i < series.length; i++) {
26359      data = toArr(series[i].data);
26360      for (j = 0; j < data.length; j++) {
26361        if (!func(data[j][0])) {
26362          return false;
26363        }
26364      }
26365    }
26366    return true;
26367  }
26368
26369  // creates a shallow copy of each element of the array
26370  // elements are expected to be objects
26371  function copySeries(series) {
26372    var newSeries = [], i, j;
26373    for (i = 0; i < series.length; i++) {
26374      var copy = {};
26375      for (j in series[i]) {
26376        if (series[i].hasOwnProperty(j)) {
26377          copy[j] = series[i][j];
26378        }
26379      }
26380      newSeries.push(copy);
26381    }
26382    return newSeries;
26383  }
26384
26385  function processSeries(chart, keyType, noDatetime) {
26386    var i;
26387
26388    var opts = chart.options;
26389    var series = chart.rawData;
26390
26391    // see if one series or multiple
26392    chart.singleSeriesFormat = (!isArray(series) || typeof series[0] !== "object" || isArray(series[0]));
26393    if (chart.singleSeriesFormat) {
26394      series = [{name: opts.label, data: series}];
26395    }
26396
26397    // convert to array
26398    // must come before dataEmpty check
26399    series = copySeries(series);
26400    for (i = 0; i < series.length; i++) {
26401      series[i].data = toArr(series[i].data);
26402    }
26403
26404    chart.xtype = keyType ? keyType : (opts.discrete ? "string" : detectXType(series, noDatetime, opts));
26405
26406    // right format
26407    for (i = 0; i < series.length; i++) {
26408      series[i].data = formatSeriesData(series[i].data, chart.xtype);
26409    }
26410
26411    return series;
26412  }
26413
26414  function processSimple(chart) {
26415    var perfectData = toArr(chart.rawData), i;
26416    for (i = 0; i < perfectData.length; i++) {
26417      perfectData[i] = [toStr(perfectData[i][0]), toFloat(perfectData[i][1])];
26418    }
26419    return perfectData;
26420  }
26421
26422  function dataEmpty(data, chartType) {
26423    if (chartType === "PieChart" || chartType === "GeoChart" || chartType === "Timeline") {
26424      return data.length === 0;
26425    } else {
26426      for (var i = 0; i < data.length; i++) {
26427        if (data[i].data.length > 0) {
26428          return false;
26429        }
26430      }
26431      return true;
26432    }
26433  }
26434
26435  function addDownloadButton(chart) {
26436    var element = chart.element;
26437    var link = document.createElement("a");
26438
26439    var download = chart.options.download;
26440    if (download === true) {
26441      download = {};
26442    } else if (typeof download === "string") {
26443      download = {filename: download};
26444    }
26445    link.download = download.filename || "chart.png"; // https://caniuse.com/download
26446
26447    link.style.position = "absolute";
26448    link.style.top = "20px";
26449    link.style.right = "20px";
26450    link.style.zIndex = 1000;
26451    link.style.lineHeight = "20px";
26452    link.target = "_blank"; // for safari
26453    var image = document.createElement("img");
26454    image.alt = "Download";
26455    image.style.border = "none";
26456    // icon from font-awesome
26457    // http://fa2png.io/
26458    image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAMAAAC6V+0/AAABCFBMVEUAAADMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMywEsqxAAAAV3RSTlMAAQIDBggJCgsMDQ4PERQaHB0eISIjJCouLzE0OTo/QUJHSUpLTU5PUllhYmltcHh5foWLjI+SlaCio6atr7S1t7m6vsHHyM7R2tze5Obo7fHz9ff5+/1hlxK2AAAA30lEQVQYGUXBhVYCQQBA0TdYWAt2d3d3YWAHyur7/z9xgD16Lw0DW+XKx+1GgX+FRzM3HWQWrHl5N/oapW5RPe0PkBu+UYeICvozTWZVK23Ao04B79oJrOsJDOoxkZoQPWgX29pHpCZEk7rEvQYiNSFq1UMqvlCjJkRBS1R8hb00Vb/TajtBL7nTHE1X1vyMQF732dQhyF2o6SAwrzP06iUQzvwsArlnzcOdrgBhJyHa1QOgO9U1GsKuvjUTjavliZYQ8nNPapG6sap/3nrIdJ6bOWzmX/fy0XVpfzZP3S8OJT3g9EEiJwAAAABJRU5ErkJggg==";
26459    link.appendChild(image);
26460    element.style.position = "relative";
26461
26462    chart.__downloadAttached = true;
26463
26464    // mouseenter
26465    chart.__enterEvent = addEvent(element, "mouseover", function(e) {
26466      var related = e.relatedTarget;
26467      // check download option again to ensure it wasn't changed
26468      if ((!related || (related !== this && !childOf(this, related))) && chart.options.download) {
26469        link.href = chart.toImage(download);
26470        element.appendChild(link);
26471      }
26472    });
26473
26474    // mouseleave
26475    chart.__leaveEvent = addEvent(element, "mouseout", function(e) {
26476      var related = e.relatedTarget;
26477      if (!related || (related !== this && !childOf(this, related))) {
26478        if (link.parentNode) {
26479          link.parentNode.removeChild(link);
26480        }
26481      }
26482    });
26483  }
26484
26485  // https://stackoverflow.com/questions/10149963/adding-event-listener-cross-browser
26486  function addEvent(elem, event, fn) {
26487    if (elem.addEventListener) {
26488      elem.addEventListener(event, fn, false);
26489      return fn;
26490    } else {
26491      var fn2 = function() {
26492        // set the this pointer same as addEventListener when fn is called
26493        return(fn.call(elem, window.event));
26494      };
26495      elem.attachEvent("on" + event, fn2);
26496      return fn2;
26497    }
26498  }
26499
26500  function removeEvent(elem, event, fn) {
26501    if (elem.removeEventListener) {
26502      elem.removeEventListener(event, fn, false);
26503    } else {
26504      elem.detachEvent("on" + event, fn);
26505    }
26506  }
26507
26508  // https://gist.github.com/shawnbot/4166283
26509  function childOf(p, c) {
26510    if (p === c) { return false; }
26511    while (c && c !== p) { c = c.parentNode; }
26512    return c === p;
26513  }
26514
26515  var pendingRequests = [], runningRequests = 0, maxRequests = 4;
26516
26517  function pushRequest(url, success, error) {
26518    pendingRequests.push([url, success, error]);
26519    runNext();
26520  }
26521
26522  function runNext() {
26523    if (runningRequests < maxRequests) {
26524      var request = pendingRequests.shift();
26525      if (request) {
26526        runningRequests++;
26527        getJSON(request[0], request[1], request[2]);
vendor: 4,433 bytes, lines 26528-26698
26528        runNext();
26529      }
26530    }
26531  }
26532
26533  function requestComplete() {
26534    runningRequests--;
26535    runNext();
26536  }
26537
26538  function getJSON(url, success, error) {
26539    ajaxCall(url, success, function (jqXHR, textStatus, errorThrown) {
26540      var message = (typeof errorThrown === "string") ? errorThrown : errorThrown.message;
26541      error(message);
26542    });
26543  }
26544
26545  function ajaxCall(url, success, error) {
26546    var $ = window.jQuery || window.Zepto || window.$;
26547
26548    if ($ && $.ajax) {
26549      $.ajax({
26550        dataType: "json",
26551        url: url,
26552        success: success,
26553        error: error,
26554        complete: requestComplete
26555      });
26556    } else {
26557      var xhr = new XMLHttpRequest();
26558      xhr.open("GET", url, true);
26559      xhr.setRequestHeader("Content-Type", "application/json");
26560      xhr.onload = function () {
26561        requestComplete();
26562        if (xhr.status === 200) {
26563          success(JSON.parse(xhr.responseText), xhr.statusText, xhr);
26564        } else {
26565          error(xhr, "error", xhr.statusText);
26566        }
26567      };
26568      xhr.send();
26569    }
26570  }
26571
26572  var config = {};
26573  var adapters = [];
26574
26575  // helpers
26576
26577  function setText(element, text) {
26578    if (document.body.innerText) {
26579      element.innerText = text;
26580    } else {
26581      element.textContent = text;
26582    }
26583  }
26584
26585  // TODO remove prefix for all messages
26586  function chartError(element, message, noPrefix) {
26587    if (!noPrefix) {
26588      message = "Error Loading Chart: " + message;
26589    }
26590    setText(element, message);
26591    element.style.color = "#ff0000";
26592  }
26593
26594  function errorCatcher(chart) {
26595    try {
26596      chart.__render();
26597    } catch (err) {
26598      chartError(chart.element, err.message);
26599      throw err;
26600    }
26601  }
26602
26603  function fetchDataSource(chart, dataSource, showLoading) {
26604    // only show loading message for urls and callbacks
26605    if (showLoading && chart.options.loading && (typeof dataSource === "string" || typeof dataSource === "function")) {
26606      setText(chart.element, chart.options.loading);
26607    }
26608
26609    if (typeof dataSource === "string") {
26610      pushRequest(dataSource, function (data) {
26611        chart.rawData = data;
26612        errorCatcher(chart);
26613      }, function (message) {
26614        chartError(chart.element, message);
26615      });
26616    } else if (typeof dataSource === "function") {
26617      try {
26618        dataSource(function (data) {
26619          chart.rawData = data;
26620          errorCatcher(chart);
26621        }, function (message) {
26622          chartError(chart.element, message, true);
26623        });
26624      } catch (err) {
26625        chartError(chart.element, err, true);
26626      }
26627    } else {
26628      chart.rawData = dataSource;
26629      errorCatcher(chart);
26630    }
26631  }
26632
26633  function getAdapterType(library) {
26634    if (library) {
26635      if (library.product === "Highcharts") {
26636        return defaultExport$1;
26637      } else if (library.charts) {
26638        return defaultExport;
26639      } else if (isFunction(library)) {
26640        return defaultExport$2;
26641      }
26642    }
26643    throw new Error("Unknown adapter");
26644  }
26645
26646  function addAdapter(library) {
26647    var adapterType = getAdapterType(library);
26648    var adapter = new adapterType(library);
26649
26650    if (adapters.indexOf(adapter) === -1) {
26651      adapters.push(adapter);
26652    }
26653  }
26654
26655  function loadAdapters() {
26656    if ("Chart" in window) {
26657      addAdapter(window.Chart);
26658    }
26659
26660    if ("Highcharts" in window) {
26661      addAdapter(window.Highcharts);
26662    }
26663
26664    if (window.google && window.google.charts) {
26665      addAdapter(window.google);
26666    }
26667  }
26668
26669  function renderChart(chartType, chart) {
26670    if (dataEmpty(chart.data, chartType)) {
26671      var message = chart.options.empty || (chart.options.messages && chart.options.messages.empty) || "No data";
26672      setText(chart.element, message);
26673    } else {
26674      callAdapter(chartType, chart);
26675      if (chart.options.download && !chart.__downloadAttached && chart.adapter === "chartjs") {
26676        addDownloadButton(chart);
26677      }
26678    }
26679  }
26680
26681  // TODO remove chartType if cross-browser way
26682  // to get the name of the chart class
26683  function callAdapter(chartType, chart) {
26684    var i, adapter, fnName, adapterName;
26685    fnName = "render" + chartType;
26686    adapterName = chart.options.adapter;
26687
26688    loadAdapters();
26689
26690    for (i = 0; i < adapters.length; i++) {
26691      adapter = adapters[i];
26692      if ((!adapterName || adapterName === adapter.name) && isFunction(adapter[fnName])) {
26693        chart.adapter = adapter.name;
26694        chart.__adapterObject = adapter;
26695        return adapter[fnName](chart);
26696      }
26697    }
26698
vendor: 11,519 bytes, lines 26699-27118
26699    if (adapters.length > 0) {
26700      throw new Error("No charting library found for " + chartType);
26701    } else {
26702      throw new Error("No charting libraries found - be sure to include one before your charts");
26703    }
26704  }
26705
26706  // define classes
26707
26708  var Chart = function Chart(element, dataSource, options) {
26709    var elementId;
26710    if (typeof element === "string") {
26711      elementId = element;
26712      element = document.getElementById(element);
26713      if (!element) {
26714        throw new Error("No element with id " + elementId);
26715      }
26716    }
26717    this.element = element;
26718    this.options = merge(Chartkick.options, options || {});
26719    this.dataSource = dataSource;
26720
26721    Chartkick.charts[element.id] = this;
26722
26723    fetchDataSource(this, dataSource, true);
26724
26725    if (this.options.refresh) {
26726      this.startRefresh();
26727    }
26728  };
26729
26730  Chart.prototype.getElement = function getElement () {
26731    return this.element;
26732  };
26733
26734  Chart.prototype.getDataSource = function getDataSource () {
26735    return this.dataSource;
26736  };
26737
26738  Chart.prototype.getData = function getData () {
26739    return this.data;
26740  };
26741
26742  Chart.prototype.getOptions = function getOptions () {
26743    return this.options;
26744  };
26745
26746  Chart.prototype.getChartObject = function getChartObject () {
26747    return this.chart;
26748  };
26749
26750  Chart.prototype.getAdapter = function getAdapter () {
26751    return this.adapter;
26752  };
26753
26754  Chart.prototype.updateData = function updateData (dataSource, options) {
26755    this.dataSource = dataSource;
26756    if (options) {
26757      this.__updateOptions(options);
26758    }
26759    fetchDataSource(this, dataSource, true);
26760  };
26761
26762  Chart.prototype.setOptions = function setOptions (options) {
26763    this.__updateOptions(options);
26764    this.redraw();
26765  };
26766
26767  Chart.prototype.redraw = function redraw () {
26768    fetchDataSource(this, this.rawData);
26769  };
26770
26771  Chart.prototype.refreshData = function refreshData () {
26772    if (typeof this.dataSource === "string") {
26773      // prevent browser from caching
26774      var sep = this.dataSource.indexOf("?") === -1 ? "?" : "&";
26775      var url = this.dataSource + sep + "_=" + (new Date()).getTime();
26776      fetchDataSource(this, url);
26777    } else if (typeof this.dataSource === "function") {
26778      fetchDataSource(this, this.dataSource);
26779    }
26780  };
26781
26782  Chart.prototype.startRefresh = function startRefresh () {
26783      var this$1 = this;
26784
26785    var refresh = this.options.refresh;
26786
26787    if (refresh && typeof this.dataSource !== "string" && typeof this.dataSource !== "function") {
26788      throw new Error("Data source must be a URL or callback for refresh");
26789    }
26790
26791    if (!this.intervalId) {
26792      if (refresh) {
26793        this.intervalId = setInterval( function () {
26794          this$1.refreshData();
26795        }, refresh * 1000);
26796      } else {
26797        throw new Error("No refresh interval");
26798      }
26799    }
26800  };
26801
26802  Chart.prototype.stopRefresh = function stopRefresh () {
26803    if (this.intervalId) {
26804      clearInterval(this.intervalId);
26805      this.intervalId = null;
26806    }
26807  };
26808
26809  Chart.prototype.toImage = function toImage (download) {
26810    if (this.adapter === "chartjs") {
26811      if (download && download.background && download.background !== "transparent") {
26812        // https://stackoverflow.com/questions/30464750/chartjs-line-chart-set-background-color
26813        var canvas = this.chart.canvas;
26814        var ctx = this.chart.ctx;
26815        var tmpCanvas = document.createElement("canvas");
26816        var tmpCtx = tmpCanvas.getContext("2d");
26817        tmpCanvas.width = ctx.canvas.width;
26818        tmpCanvas.height = ctx.canvas.height;
26819        tmpCtx.fillStyle = download.background;
26820        tmpCtx.fillRect(0, 0, tmpCanvas.width, tmpCanvas.height);
26821        tmpCtx.drawImage(canvas, 0, 0);
26822        return tmpCanvas.toDataURL("image/png");
26823      } else {
26824        return this.chart.toBase64Image();
26825      }
26826    } else {
26827      throw new Error("Feature only available for Chart.js");
26828    }
26829  };
26830
26831  Chart.prototype.destroy = function destroy () {
26832    this.destroyed = true;
26833    this.stopRefresh();
26834
26835    if (this.__adapterObject) {
26836      this.__adapterObject.destroy(this);
26837    }
26838
26839    if (this.__enterEvent) {
26840      removeEvent(this.element, "mouseover", this.__enterEvent);
26841    }
26842
26843    if (this.__leaveEvent) {
26844      removeEvent(this.element, "mouseout", this.__leaveEvent);
26845    }
26846  };
26847
26848  Chart.prototype.__updateOptions = function __updateOptions (options) {
26849    var updateRefresh = options.refresh && options.refresh !== this.options.refresh;
26850    this.options = merge(Chartkick.options, options);
26851    if (updateRefresh) {
26852      this.stopRefresh();
26853      this.startRefresh();
26854    }
26855  };
26856
26857  Chart.prototype.__render = function __render () {
26858    this.data = this.__processData();
26859    renderChart(this.__chartName(), this);
26860  };
26861
26862  Chart.prototype.__config = function __config () {
26863    return config;
26864  };
26865
26866  var LineChart = /*@__PURE__*/(function (Chart) {
26867    function LineChart () {
26868      Chart.apply(this, arguments);
26869    }
26870
26871    if ( Chart ) LineChart.__proto__ = Chart;
26872    LineChart.prototype = Object.create( Chart && Chart.prototype );
26873    LineChart.prototype.constructor = LineChart;
26874
26875    LineChart.prototype.__processData = function __processData () {
26876      return processSeries(this);
26877    };
26878
26879    LineChart.prototype.__chartName = function __chartName () {
26880      return "LineChart";
26881    };
26882
26883    return LineChart;
26884  }(Chart));
26885
26886  var PieChart = /*@__PURE__*/(function (Chart) {
26887    function PieChart () {
26888      Chart.apply(this, arguments);
26889    }
26890
26891    if ( Chart ) PieChart.__proto__ = Chart;
26892    PieChart.prototype = Object.create( Chart && Chart.prototype );
26893    PieChart.prototype.constructor = PieChart;
26894
26895    PieChart.prototype.__processData = function __processData () {
26896      return processSimple(this);
26897    };
26898
26899    PieChart.prototype.__chartName = function __chartName () {
26900      return "PieChart";
26901    };
26902
26903    return PieChart;
26904  }(Chart));
26905
26906  var ColumnChart = /*@__PURE__*/(function (Chart) {
26907    function ColumnChart () {
26908      Chart.apply(this, arguments);
26909    }
26910
26911    if ( Chart ) ColumnChart.__proto__ = Chart;
26912    ColumnChart.prototype = Object.create( Chart && Chart.prototype );
26913    ColumnChart.prototype.constructor = ColumnChart;
26914
26915    ColumnChart.prototype.__processData = function __processData () {
26916      return processSeries(this, null, true);
26917    };
26918
26919    ColumnChart.prototype.__chartName = function __chartName () {
26920      return "ColumnChart";
26921    };
26922
26923    return ColumnChart;
26924  }(Chart));
26925
26926  var BarChart = /*@__PURE__*/(function (Chart) {
26927    function BarChart () {
26928      Chart.apply(this, arguments);
26929    }
26930
26931    if ( Chart ) BarChart.__proto__ = Chart;
26932    BarChart.prototype = Object.create( Chart && Chart.prototype );
26933    BarChart.prototype.constructor = BarChart;
26934
26935    BarChart.prototype.__processData = function __processData () {
26936      return processSeries(this, null, true);
26937    };
26938
26939    BarChart.prototype.__chartName = function __chartName () {
26940      return "BarChart";
26941    };
26942
26943    return BarChart;
26944  }(Chart));
26945
26946  var AreaChart = /*@__PURE__*/(function (Chart) {
26947    function AreaChart () {
26948      Chart.apply(this, arguments);
26949    }
26950
26951    if ( Chart ) AreaChart.__proto__ = Chart;
26952    AreaChart.prototype = Object.create( Chart && Chart.prototype );
26953    AreaChart.prototype.constructor = AreaChart;
26954
26955    AreaChart.prototype.__processData = function __processData () {
26956      return processSeries(this);
26957    };
26958
26959    AreaChart.prototype.__chartName = function __chartName () {
26960      return "AreaChart";
26961    };
26962
26963    return AreaChart;
26964  }(Chart));
26965
26966  var GeoChart = /*@__PURE__*/(function (Chart) {
26967    function GeoChart () {
26968      Chart.apply(this, arguments);
26969    }
26970
26971    if ( Chart ) GeoChart.__proto__ = Chart;
26972    GeoChart.prototype = Object.create( Chart && Chart.prototype );
26973    GeoChart.prototype.constructor = GeoChart;
26974
26975    GeoChart.prototype.__processData = function __processData () {
26976      return processSimple(this);
26977    };
26978
26979    GeoChart.prototype.__chartName = function __chartName () {
26980      return "GeoChart";
26981    };
26982
26983    return GeoChart;
26984  }(Chart));
26985
26986  var ScatterChart = /*@__PURE__*/(function (Chart) {
26987    function ScatterChart () {
26988      Chart.apply(this, arguments);
26989    }
26990
26991    if ( Chart ) ScatterChart.__proto__ = Chart;
26992    ScatterChart.prototype = Object.create( Chart && Chart.prototype );
26993    ScatterChart.prototype.constructor = ScatterChart;
26994
26995    ScatterChart.prototype.__processData = function __processData () {
26996      return processSeries(this, "number");
26997    };
26998
26999    ScatterChart.prototype.__chartName = function __chartName () {
27000      return "ScatterChart";
27001    };
27002
27003    return ScatterChart;
27004  }(Chart));
27005
27006  var BubbleChart = /*@__PURE__*/(function (Chart) {
27007    function BubbleChart () {
27008      Chart.apply(this, arguments);
27009    }
27010
27011    if ( Chart ) BubbleChart.__proto__ = Chart;
27012    BubbleChart.prototype = Object.create( Chart && Chart.prototype );
27013    BubbleChart.prototype.constructor = BubbleChart;
27014
27015    BubbleChart.prototype.__processData = function __processData () {
27016      return processSeries(this, "bubble");
27017    };
27018
27019    BubbleChart.prototype.__chartName = function __chartName () {
27020      return "BubbleChart";
27021    };
27022
27023    return BubbleChart;
27024  }(Chart));
27025
27026  var Timeline = /*@__PURE__*/(function (Chart) {
27027    function Timeline () {
27028      Chart.apply(this, arguments);
27029    }
27030
27031    if ( Chart ) Timeline.__proto__ = Chart;
27032    Timeline.prototype = Object.create( Chart && Chart.prototype );
27033    Timeline.prototype.constructor = Timeline;
27034
27035    Timeline.prototype.__processData = function __processData () {
27036      var i, data = this.rawData;
27037      for (i = 0; i < data.length; i++) {
27038        data[i][1] = toDate(data[i][1]);
27039        data[i][2] = toDate(data[i][2]);
27040      }
27041      return data;
27042    };
27043
27044    Timeline.prototype.__chartName = function __chartName () {
27045      return "Timeline";
27046    };
27047
27048    return Timeline;
27049  }(Chart));
27050
27051  var Chartkick = {
27052    LineChart: LineChart,
27053    PieChart: PieChart,
27054    ColumnChart: ColumnChart,
27055    BarChart: BarChart,
27056    AreaChart: AreaChart,
27057    GeoChart: GeoChart,
27058    ScatterChart: ScatterChart,
27059    BubbleChart: BubbleChart,
27060    Timeline: Timeline,
27061    charts: {},
27062    configure: function (options) {
27063      for (var key in options) {
27064        if (options.hasOwnProperty(key)) {
27065          config[key] = options[key];
27066        }
27067      }
27068    },
27069    setDefaultOptions: function (opts) {
27070      Chartkick.options = opts;
27071    },
27072    eachChart: function (callback) {
27073      for (var chartId in Chartkick.charts) {
27074        if (Chartkick.charts.hasOwnProperty(chartId)) {
27075          callback(Chartkick.charts[chartId]);
27076        }
27077      }
27078    },
27079    destroyAll: function() {
27080      for (var chartId in Chartkick.charts) {
27081        if (Chartkick.charts.hasOwnProperty(chartId)) {
27082          Chartkick.charts[chartId].destroy();
27083          delete Chartkick.charts[chartId];
27084        }
27085      }
27086    },
27087    config: config,
27088    options: {},
27089    adapters: adapters,
27090    addAdapter: addAdapter,
27091    use: function(adapter) {
27092      addAdapter(adapter);
27093      return Chartkick;
27094    }
27095  };
27096
27097  // not ideal, but allows for simpler integration
27098  if (typeof window !== "undefined" && !window.Chartkick) {
27099    window.Chartkick = Chartkick;
27100
27101    // clean up previous charts before Turbolinks loads new page
27102    document.addEventListener("turbolinks:before-render", function() {
27103      Chartkick.destroyAll();
27104    });
27105
27106    // use setTimeout so charting library can come later in same JS file
27107    setTimeout(function() {
27108      window.dispatchEvent(new Event("chartkick:load"));
27109    }, 0);
27110  }
27111
27112  // backwards compatibility for esm require
27113  Chartkick.default = Chartkick;
27114
27115  return Chartkick;
27116
27117})));
27118

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.