Debian Codegraph @

vendor/static/chart.js/dist/chunks/helpers.dataset.js

raw
1 /*!
2 * Chart.js v4.5.1
3 * https://www.chartjs.org
4 * (c) 2025 Chart.js Contributors
5 * Released under the MIT License
6 */
7 import { Color } from '@kurkle/color';
8
9 /**
10 * @namespace Chart.helpers
11 */ /**
12 * An empty function that can be used, for example, for optional callback.
13 */ function noop() {
14 /* noop */ }
15 /**
16 * Returns a unique id, sequentially generated from a global variable.
17 */ const uid = (()=>{
18 let id = 0;
19 return ()=>id++;
20 })();
21 /**
22 * Returns true if `value` is neither null nor undefined, else returns false.
23 * @param value - The value to test.
24 * @since 2.7.0
25 */ function isNullOrUndef(value) {
26 return value === null || value === undefined;
27 }
28 /**
29 * Returns true if `value` is an array (including typed arrays), else returns false.
30 * @param value - The value to test.
31 * @function
32 */ function isArray(value) {
33 if (Array.isArray && Array.isArray(value)) {
34 return true;
35 }
36 const type = Object.prototype.toString.call(value);
37 if (type.slice(0, 7) === '[object' && type.slice(-6) === 'Array]') {
38 return true;
39 }
40 return false;
41 }
42 /**
43 * Returns true if `value` is an object (excluding null), else returns false.
44 * @param value - The value to test.
45 * @since 2.7.0
46 */ function isObject(value) {
47 return value !== null && Object.prototype.toString.call(value) === '[object Object]';
48 }
49 /**
50 * Returns true if `value` is a finite number, else returns false
51 * @param value - The value to test.
52 */ function isNumberFinite(value) {
53 return (typeof value === 'number' || value instanceof Number) && isFinite(+value);
54 }
55 /**
56 * Returns `value` if finite, else returns `defaultValue`.
57 * @param value - The value to return if defined.
58 * @param defaultValue - The value to return if `value` is not finite.
59 */ function finiteOrDefault(value, defaultValue) {
60 return isNumberFinite(value) ? value : defaultValue;
61 }
62 /**
63 * Returns `value` if defined, else returns `defaultValue`.
64 * @param value - The value to return if defined.
65 * @param defaultValue - The value to return if `value` is undefined.
66 */ function valueOrDefault(value, defaultValue) {
67 return typeof value === 'undefined' ? defaultValue : value;
68 }
69 const toPercentage = (value, dimension)=>typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 : +value / dimension;
70 const toDimension = (value, dimension)=>typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 * dimension : +value;
71 /**
72 * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
73 * value returned by `fn`. If `fn` is not a function, this method returns undefined.
74 * @param fn - The function to call.
75 * @param args - The arguments with which `fn` should be called.
76 * @param [thisArg] - The value of `this` provided for the call to `fn`.
77 */ function callback(fn, args, thisArg) {
78 if (fn && typeof fn.call === 'function') {
79 return fn.apply(thisArg, args);
80 }
81 }
82 function each(loopable, fn, thisArg, reverse) {
83 let i, len, keys;
84 if (isArray(loopable)) {
85 len = loopable.length;
86 if (reverse) {
87 for(i = len - 1; i >= 0; i--){
88 fn.call(thisArg, loopable[i], i);
89 }
90 } else {
91 for(i = 0; i < len; i++){
92 fn.call(thisArg, loopable[i], i);
93 }
94 }
95 } else if (isObject(loopable)) {
96 keys = Object.keys(loopable);
97 len = keys.length;
98 for(i = 0; i < len; i++){
99 fn.call(thisArg, loopable[keys[i]], keys[i]);
100 }
101 }
102 }
103 /**
104 * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
105 * @param a0 - The array to compare
106 * @param a1 - The array to compare
107 * @private
108 */ function _elementsEqual(a0, a1) {
109 let i, ilen, v0, v1;
110 if (!a0 || !a1 || a0.length !== a1.length) {
111 return false;
112 }
113 for(i = 0, ilen = a0.length; i < ilen; ++i){
114 v0 = a0[i];
115 v1 = a1[i];
116 if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) {
117 return false;
118 }
119 }
120 return true;
121 }
122 /**
123 * Returns a deep copy of `source` without keeping references on objects and arrays.
124 * @param source - The value to clone.
125 */ function clone(source) {
126 if (isArray(source)) {
127 return source.map(clone);
128 }
129 if (isObject(source)) {
130 const target = Object.create(null);
131 const keys = Object.keys(source);
132 const klen = keys.length;
133 let k = 0;
134 for(; k < klen; ++k){
135 target[keys[k]] = clone(source[keys[k]]);
136 }
137 return target;
138 }
139 return source;
140 }
141 function isValidKey(key) {
142 return [
143 '__proto__',
144 'prototype',
145 'constructor'
146 ].indexOf(key) === -1;
147 }
148 /**
149 * The default merger when Chart.helpers.merge is called without merger option.
150 * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
151 * @private
152 */ function _merger(key, target, source, options) {
153 if (!isValidKey(key)) {
154 return;
155 }
156 const tval = target[key];
157 const sval = source[key];
158 if (isObject(tval) && isObject(sval)) {
159 // eslint-disable-next-line @typescript-eslint/no-use-before-define
160 merge(tval, sval, options);
161 } else {
162 target[key] = clone(sval);
163 }
164 }
165 function merge(target, source, options) {
166 const sources = isArray(source) ? source : [
167 source
168 ];
169 const ilen = sources.length;
170 if (!isObject(target)) {
171 return target;
172 }
173 options = options || {};
174 const merger = options.merger || _merger;
175 let current;
176 for(let i = 0; i < ilen; ++i){
177 current = sources[i];
178 if (!isObject(current)) {
179 continue;
180 }
181 const keys = Object.keys(current);
182 for(let k = 0, klen = keys.length; k < klen; ++k){
183 merger(keys[k], target, current, options);
184 }
185 }
186 return target;
187 }
188 function mergeIf(target, source) {
189 // eslint-disable-next-line @typescript-eslint/no-use-before-define
190 return merge(target, source, {
191 merger: _mergerIf
192 });
193 }
194 /**
195 * Merges source[key] in target[key] only if target[key] is undefined.
196 * @private
197 */ function _mergerIf(key, target, source) {
198 if (!isValidKey(key)) {
199 return;
200 }
201 const tval = target[key];
202 const sval = source[key];
203 if (isObject(tval) && isObject(sval)) {
204 mergeIf(tval, sval);
205 } else if (!Object.prototype.hasOwnProperty.call(target, key)) {
206 target[key] = clone(sval);
207 }
208 }
209 /**
210 * @private
211 */ function _deprecated(scope, value, previous, current) {
212 if (value !== undefined) {
213 console.warn(scope + ': "' + previous + '" is deprecated. Please use "' + current + '" instead');
214 }
215 }
216 // resolveObjectKey resolver cache
217 const keyResolvers = {
218 // Chart.helpers.core resolveObjectKey should resolve empty key to root object
219 '': (v)=>v,
220 // default resolvers
221 x: (o)=>o.x,
222 y: (o)=>o.y
223 };
224 /**
225 * @private
226 */ function _splitKey(key) {
227 const parts = key.split('.');
228 const keys = [];
229 let tmp = '';
230 for (const part of parts){
231 tmp += part;
232 if (tmp.endsWith('\\')) {
233 tmp = tmp.slice(0, -1) + '.';
234 } else {
235 keys.push(tmp);
236 tmp = '';
237 }
238 }
239 return keys;
240 }
241 function _getKeyResolver(key) {
242 const keys = _splitKey(key);
243 return (obj)=>{
244 for (const k of keys){
245 if (k === '') {
246 break;
247 }
248 obj = obj && obj[k];
249 }
250 return obj;
251 };
252 }
253 function resolveObjectKey(obj, key) {
254 const resolver = keyResolvers[key] || (keyResolvers[key] = _getKeyResolver(key));
255 return resolver(obj);
256 }
257 /**
258 * @private
259 */ function _capitalize(str) {
260 return str.charAt(0).toUpperCase() + str.slice(1);
261 }
262 const defined = (value)=>typeof value !== 'undefined';
263 const isFunction = (value)=>typeof value === 'function';
264 // Adapted from https://stackoverflow.com/questions/31128855/comparing-ecma6-sets-for-equality#31129384
265 const setsEqual = (a, b)=>{
266 if (a.size !== b.size) {
267 return false;
268 }
269 for (const item of a){
270 if (!b.has(item)) {
271 return false;
272 }
273 }
274 return true;
275 };
276 /**
277 * @param e - The event
278 * @private
279 */ function _isClickEvent(e) {
280 return e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu';
281 }
282
283 /**
284 * @alias Chart.helpers.math
285 * @namespace
286 */ const PI = Math.PI;
287 const TAU = 2 * PI;
288 const PITAU = TAU + PI;
289 const INFINITY = Number.POSITIVE_INFINITY;
290 const RAD_PER_DEG = PI / 180;
291 const HALF_PI = PI / 2;
292 const QUARTER_PI = PI / 4;
293 const TWO_THIRDS_PI = PI * 2 / 3;
294 const log10 = Math.log10;
295 const sign = Math.sign;
296 function almostEquals(x, y, epsilon) {
297 return Math.abs(x - y) < epsilon;
298 }
299 /**
300 * Implementation of the nice number algorithm used in determining where axis labels will go
301 */ function niceNum(range) {
302 const roundedRange = Math.round(range);
303 range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range;
304 const niceRange = Math.pow(10, Math.floor(log10(range)));
305 const fraction = range / niceRange;
306 const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
307 return niceFraction * niceRange;
308 }
309 /**
310 * Returns an array of factors sorted from 1 to sqrt(value)
311 * @private
312 */ function _factorize(value) {
313 const result = [];
314 const sqrt = Math.sqrt(value);
315 let i;
316 for(i = 1; i < sqrt; i++){
317 if (value % i === 0) {
318 result.push(i);
319 result.push(value / i);
320 }
321 }
322 if (sqrt === (sqrt | 0)) {
323 result.push(sqrt);
324 }
325 result.sort((a, b)=>a - b).pop();
326 return result;
327 }
328 /**
329 * Verifies that attempting to coerce n to string or number won't throw a TypeError.
330 */ function isNonPrimitive(n) {
331 return typeof n === 'symbol' || typeof n === 'object' && n !== null && !(Symbol.toPrimitive in n || 'toString' in n || 'valueOf' in n);
332 }
333 function isNumber(n) {
334 return !isNonPrimitive(n) && !isNaN(parseFloat(n)) && isFinite(n);
335 }
336 function almostWhole(x, epsilon) {
337 const rounded = Math.round(x);
338 return rounded - epsilon <= x && rounded + epsilon >= x;
339 }
340 /**
341 * @private
342 */ function _setMinAndMaxByKey(array, target, property) {
343 let i, ilen, value;
344 for(i = 0, ilen = array.length; i < ilen; i++){
345 value = array[i][property];
346 if (!isNaN(value)) {
347 target.min = Math.min(target.min, value);
348 target.max = Math.max(target.max, value);
349 }
350 }
351 }
352 function toRadians(degrees) {
353 return degrees * (PI / 180);
354 }
355 function toDegrees(radians) {
356 return radians * (180 / PI);
357 }
358 /**
359 * Returns the number of decimal places
360 * i.e. the number of digits after the decimal point, of the value of this Number.
361 * @param x - A number.
362 * @returns The number of decimal places.
363 * @private
364 */ function _decimalPlaces(x) {
365 if (!isNumberFinite(x)) {
366 return;
367 }
368 let e = 1;
369 let p = 0;
370 while(Math.round(x * e) / e !== x){
371 e *= 10;
372 p++;
373 }
374 return p;
375 }
376 // Gets the angle from vertical upright to the point about a centre.
377 function getAngleFromPoint(centrePoint, anglePoint) {
378 const distanceFromXCenter = anglePoint.x - centrePoint.x;
379 const distanceFromYCenter = anglePoint.y - centrePoint.y;
380 const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
381 let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
382 if (angle < -0.5 * PI) {
383 angle += TAU; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
384 }
385 return {
386 angle,
387 distance: radialDistanceFromCenter
388 };
389 }
390 function distanceBetweenPoints(pt1, pt2) {
391 return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
392 }
393 /**
394 * Shortest distance between angles, in either direction.
395 * @private
396 */ function _angleDiff(a, b) {
397 return (a - b + PITAU) % TAU - PI;
398 }
399 /**
400 * Normalize angle to be between 0 and 2*PI
401 * @private
402 */ function _normalizeAngle(a) {
403 return (a % TAU + TAU) % TAU;
404 }
405 /**
406 * @private
407 */ function _angleBetween(angle, start, end, sameAngleIsFullCircle) {
408 const a = _normalizeAngle(angle);
409 const s = _normalizeAngle(start);
410 const e = _normalizeAngle(end);
411 const angleToStart = _normalizeAngle(s - a);
412 const angleToEnd = _normalizeAngle(e - a);
413 const startToAngle = _normalizeAngle(a - s);
414 const endToAngle = _normalizeAngle(a - e);
415 return a === s || a === e || sameAngleIsFullCircle && s === e || angleToStart > angleToEnd && startToAngle < endToAngle;
416 }
417 /**
418 * Limit `value` between `min` and `max`
419 * @param value
420 * @param min
421 * @param max
422 * @private
423 */ function _limitValue(value, min, max) {
424 return Math.max(min, Math.min(max, value));
425 }
426 /**
427 * @param {number} value
428 * @private
429 */ function _int16Range(value) {
430 return _limitValue(value, -32768, 32767);
431 }
432 /**
433 * @param value
434 * @param start
435 * @param end
436 * @param [epsilon]
437 * @private
438 */ function _isBetween(value, start, end, epsilon = 1e-6) {
439 return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon;
440 }
441
442 function _lookup(table, value, cmp) {
443 cmp = cmp || ((index)=>table[index] < value);
444 let hi = table.length - 1;
445 let lo = 0;
446 let mid;
447 while(hi - lo > 1){
448 mid = lo + hi >> 1;
449 if (cmp(mid)) {
450 lo = mid;
451 } else {
452 hi = mid;
453 }
454 }
455 return {
456 lo,
457 hi
458 };
459 }
460 /**
461 * Binary search
462 * @param table - the table search. must be sorted!
463 * @param key - property name for the value in each entry
464 * @param value - value to find
465 * @param last - lookup last index
466 * @private
467 */ const _lookupByKey = (table, key, value, last)=>_lookup(table, value, last ? (index)=>{
468 const ti = table[index][key];
469 return ti < value || ti === value && table[index + 1][key] === value;
470 } : (index)=>table[index][key] < value);
471 /**
472 * Reverse binary search
473 * @param table - the table search. must be sorted!
474 * @param key - property name for the value in each entry
475 * @param value - value to find
476 * @private
477 */ const _rlookupByKey = (table, key, value)=>_lookup(table, value, (index)=>table[index][key] >= value);
478 /**
479 * Return subset of `values` between `min` and `max` inclusive.
480 * Values are assumed to be in sorted order.
481 * @param values - sorted array of values
482 * @param min - min value
483 * @param max - max value
484 */ function _filterBetween(values, min, max) {
485 let start = 0;
486 let end = values.length;
487 while(start < end && values[start] < min){
488 start++;
489 }
490 while(end > start && values[end - 1] > max){
491 end--;
492 }
493 return start > 0 || end < values.length ? values.slice(start, end) : values;
494 }
495 const arrayEvents = [
496 'push',
497 'pop',
498 'shift',
499 'splice',
500 'unshift'
501 ];
502 function listenArrayEvents(array, listener) {
503 if (array._chartjs) {
504 array._chartjs.listeners.push(listener);
505 return;
506 }
507 Object.defineProperty(array, '_chartjs', {
508 configurable: true,
509 enumerable: false,
510 value: {
511 listeners: [
512 listener
513 ]
514 }
515 });
516 arrayEvents.forEach((key)=>{
517 const method = '_onData' + _capitalize(key);
518 const base = array[key];
519 Object.defineProperty(array, key, {
520 configurable: true,
521 enumerable: false,
522 value (...args) {
523 const res = base.apply(this, args);
524 array._chartjs.listeners.forEach((object)=>{
525 if (typeof object[method] === 'function') {
526 object[method](...args);
527 }
528 });
529 return res;
530 }
531 });
532 });
533 }
534 function unlistenArrayEvents(array, listener) {
535 const stub = array._chartjs;
536 if (!stub) {
537 return;
538 }
539 const listeners = stub.listeners;
540 const index = listeners.indexOf(listener);
541 if (index !== -1) {
542 listeners.splice(index, 1);
543 }
544 if (listeners.length > 0) {
545 return;
546 }
547 arrayEvents.forEach((key)=>{
548 delete array[key];
549 });
550 delete array._chartjs;
551 }
552 /**
553 * @param items
554 */ function _arrayUnique(items) {
555 const set = new Set(items);
556 if (set.size === items.length) {
557 return items;
558 }
559 return Array.from(set);
560 }
561
562 function fontString(pixelSize, fontStyle, fontFamily) {
563 return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
564 }
565 /**
566 * Request animation polyfill
567 */ const requestAnimFrame = function() {
568 if (typeof window === 'undefined') {
569 return function(callback) {
570 return callback();
571 };
572 }
573 return window.requestAnimationFrame;
574 }();
575 /**
576 * Throttles calling `fn` once per animation frame
577 * Latest arguments are used on the actual call
578 */ function throttled(fn, thisArg) {
579 let argsToUse = [];
580 let ticking = false;
581 return function(...args) {
582 // Save the args for use later
583 argsToUse = args;
584 if (!ticking) {
585 ticking = true;
586 requestAnimFrame.call(window, ()=>{
587 ticking = false;
588 fn.apply(thisArg, argsToUse);
589 });
590 }
591 };
592 }
593 /**
594 * Debounces calling `fn` for `delay` ms
595 */ function debounce(fn, delay) {
596 let timeout;
597 return function(...args) {
598 if (delay) {
599 clearTimeout(timeout);
600 timeout = setTimeout(fn, delay, args);
601 } else {
602 fn.apply(this, args);
603 }
604 return delay;
605 };
606 }
607 /**
608 * Converts 'start' to 'left', 'end' to 'right' and others to 'center'
609 * @private
610 */ const _toLeftRightCenter = (align)=>align === 'start' ? 'left' : align === 'end' ? 'right' : 'center';
611 /**
612 * Returns `start`, `end` or `(start + end) / 2` depending on `align`. Defaults to `center`
613 * @private
614 */ const _alignStartEnd = (align, start, end)=>align === 'start' ? start : align === 'end' ? end : (start + end) / 2;
615 /**
616 * Returns `left`, `right` or `(left + right) / 2` depending on `align`. Defaults to `left`
617 * @private
618 */ const _textX = (align, left, right, rtl)=>{
619 const check = rtl ? 'left' : 'right';
620 return align === check ? right : align === 'center' ? (left + right) / 2 : left;
621 };
622 /**
623 * Return start and count of visible points.
624 * @private
625 */ function _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) {
626 const pointCount = points.length;
627 let start = 0;
628 let count = pointCount;
629 if (meta._sorted) {
630 const { iScale , vScale , _parsed } = meta;
631 const spanGaps = meta.dataset ? meta.dataset.options ? meta.dataset.options.spanGaps : null : null;
632 const axis = iScale.axis;
633 const { min , max , minDefined , maxDefined } = iScale.getUserBounds();
634 if (minDefined) {
635 start = Math.min(// @ts-expect-error Need to type _parsed
636 _lookupByKey(_parsed, axis, min).lo, // @ts-expect-error Need to fix types on _lookupByKey
637 animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo);
638 if (spanGaps) {
639 const distanceToDefinedLo = _parsed.slice(0, start + 1).reverse().findIndex((point)=>!isNullOrUndef(point[vScale.axis]));
640 start -= Math.max(0, distanceToDefinedLo);
641 }
642 start = _limitValue(start, 0, pointCount - 1);
643 }
644 if (maxDefined) {
645 let end = Math.max(// @ts-expect-error Need to type _parsed
646 _lookupByKey(_parsed, iScale.axis, max, true).hi + 1, // @ts-expect-error Need to fix types on _lookupByKey
647 animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max), true).hi + 1);
648 if (spanGaps) {
649 const distanceToDefinedHi = _parsed.slice(end - 1).findIndex((point)=>!isNullOrUndef(point[vScale.axis]));
650 end += Math.max(0, distanceToDefinedHi);
651 }
652 count = _limitValue(end, start, pointCount) - start;
653 } else {
654 count = pointCount - start;
655 }
656 }
657 return {
658 start,
659 count
660 };
661 }
662 /**
663 * Checks if the scale ranges have changed.
664 * @param {object} meta - dataset meta.
665 * @returns {boolean}
666 * @private
667 */ function _scaleRangesChanged(meta) {
668 const { xScale , yScale , _scaleRanges } = meta;
669 const newRanges = {
670 xmin: xScale.min,
671 xmax: xScale.max,
672 ymin: yScale.min,
673 ymax: yScale.max
674 };
675 if (!_scaleRanges) {
676 meta._scaleRanges = newRanges;
677 return true;
678 }
679 const changed = _scaleRanges.xmin !== xScale.min || _scaleRanges.xmax !== xScale.max || _scaleRanges.ymin !== yScale.min || _scaleRanges.ymax !== yScale.max;
680 Object.assign(_scaleRanges, newRanges);
681 return changed;
682 }
683
684 const atEdge = (t)=>t === 0 || t === 1;
685 const elasticIn = (t, s, p)=>-(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p));
686 const elasticOut = (t, s, p)=>Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1;
687 /**
688 * Easing functions adapted from Robert Penner's easing equations.
689 * @namespace Chart.helpers.easing.effects
690 * @see http://www.robertpenner.com/easing/
691 */ const effects = {
692 linear: (t)=>t,
693 easeInQuad: (t)=>t * t,
694 easeOutQuad: (t)=>-t * (t - 2),
695 easeInOutQuad: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t : -0.5 * (--t * (t - 2) - 1),
696 easeInCubic: (t)=>t * t * t,
697 easeOutCubic: (t)=>(t -= 1) * t * t + 1,
698 easeInOutCubic: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t * t : 0.5 * ((t -= 2) * t * t + 2),
699 easeInQuart: (t)=>t * t * t * t,
700 easeOutQuart: (t)=>-((t -= 1) * t * t * t - 1),
701 easeInOutQuart: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t * t * t : -0.5 * ((t -= 2) * t * t * t - 2),
702 easeInQuint: (t)=>t * t * t * t * t,
703 easeOutQuint: (t)=>(t -= 1) * t * t * t * t + 1,
704 easeInOutQuint: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t * t * t * t : 0.5 * ((t -= 2) * t * t * t * t + 2),
705 easeInSine: (t)=>-Math.cos(t * HALF_PI) + 1,
706 easeOutSine: (t)=>Math.sin(t * HALF_PI),
707 easeInOutSine: (t)=>-0.5 * (Math.cos(PI * t) - 1),
708 easeInExpo: (t)=>t === 0 ? 0 : Math.pow(2, 10 * (t - 1)),
709 easeOutExpo: (t)=>t === 1 ? 1 : -Math.pow(2, -10 * t) + 1,
710 easeInOutExpo: (t)=>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),
711 easeInCirc: (t)=>t >= 1 ? t : -(Math.sqrt(1 - t * t) - 1),
712 easeOutCirc: (t)=>Math.sqrt(1 - (t -= 1) * t),
713 easeInOutCirc: (t)=>(t /= 0.5) < 1 ? -0.5 * (Math.sqrt(1 - t * t) - 1) : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1),
714 easeInElastic: (t)=>atEdge(t) ? t : elasticIn(t, 0.075, 0.3),
715 easeOutElastic: (t)=>atEdge(t) ? t : elasticOut(t, 0.075, 0.3),
716 easeInOutElastic (t) {
717 const s = 0.1125;
718 const p = 0.45;
719 return atEdge(t) ? t : t < 0.5 ? 0.5 * elasticIn(t * 2, s, p) : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p);
720 },
721 easeInBack (t) {
722 const s = 1.70158;
723 return t * t * ((s + 1) * t - s);
724 },
725 easeOutBack (t) {
726 const s = 1.70158;
727 return (t -= 1) * t * ((s + 1) * t + s) + 1;
728 },
729 easeInOutBack (t) {
730 let s = 1.70158;
731 if ((t /= 0.5) < 1) {
732 return 0.5 * (t * t * (((s *= 1.525) + 1) * t - s));
733 }
734 return 0.5 * ((t -= 2) * t * (((s *= 1.525) + 1) * t + s) + 2);
735 },
736 easeInBounce: (t)=>1 - effects.easeOutBounce(1 - t),
737 easeOutBounce (t) {
738 const m = 7.5625;
739 const d = 2.75;
740 if (t < 1 / d) {
741 return m * t * t;
742 }
743 if (t < 2 / d) {
744 return m * (t -= 1.5 / d) * t + 0.75;
745 }
746 if (t < 2.5 / d) {
747 return m * (t -= 2.25 / d) * t + 0.9375;
748 }
749 return m * (t -= 2.625 / d) * t + 0.984375;
750 },
751 easeInOutBounce: (t)=>t < 0.5 ? effects.easeInBounce(t * 2) * 0.5 : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5
752 };
753
754 function isPatternOrGradient(value) {
755 if (value && typeof value === 'object') {
756 const type = value.toString();
757 return type === '[object CanvasPattern]' || type === '[object CanvasGradient]';
758 }
759 return false;
760 }
761 function color(value) {
762 return isPatternOrGradient(value) ? value : new Color(value);
763 }
764 function getHoverColor(value) {
765 return isPatternOrGradient(value) ? value : new Color(value).saturate(0.5).darken(0.1).hexString();
766 }
767
768 const numbers = [
769 'x',
770 'y',
771 'borderWidth',
772 'radius',
773 'tension'
774 ];
775 const colors = [
776 'color',
777 'borderColor',
778 'backgroundColor'
779 ];
780 function applyAnimationsDefaults(defaults) {
781 defaults.set('animation', {
782 delay: undefined,
783 duration: 1000,
784 easing: 'easeOutQuart',
785 fn: undefined,
786 from: undefined,
787 loop: undefined,
788 to: undefined,
789 type: undefined
790 });
791 defaults.describe('animation', {
792 _fallback: false,
793 _indexable: false,
794 _scriptable: (name)=>name !== 'onProgress' && name !== 'onComplete' && name !== 'fn'
795 });
796 defaults.set('animations', {
797 colors: {
798 type: 'color',
799 properties: colors
800 },
801 numbers: {
802 type: 'number',
803 properties: numbers
804 }
805 });
806 defaults.describe('animations', {
807 _fallback: 'animation'
808 });
809 defaults.set('transitions', {
810 active: {
811 animation: {
812 duration: 400
813 }
814 },
815 resize: {
816 animation: {
817 duration: 0
818 }
819 },
820 show: {
821 animations: {
822 colors: {
823 from: 'transparent'
824 },
825 visible: {
826 type: 'boolean',
827 duration: 0
828 }
829 }
830 },
831 hide: {
832 animations: {
833 colors: {
834 to: 'transparent'
835 },
836 visible: {
837 type: 'boolean',
838 easing: 'linear',
839 fn: (v)=>v | 0
840 }
841 }
842 }
843 });
844 }
845
846 function applyLayoutsDefaults(defaults) {
847 defaults.set('layout', {
848 autoPadding: true,
849 padding: {
850 top: 0,
851 right: 0,
852 bottom: 0,
853 left: 0
854 }
855 });
856 }
857
858 const intlCache = new Map();
859 function getNumberFormat(locale, options) {
860 options = options || {};
861 const cacheKey = locale + JSON.stringify(options);
862 let formatter = intlCache.get(cacheKey);
863 if (!formatter) {
864 formatter = new Intl.NumberFormat(locale, options);
865 intlCache.set(cacheKey, formatter);
866 }
867 return formatter;
868 }
869 function formatNumber(num, locale, options) {
870 return getNumberFormat(locale, options).format(num);
871 }
872
873 const formatters = {
874 values (value) {
875 return isArray(value) ? value : '' + value;
876 },
877 numeric (tickValue, index, ticks) {
878 if (tickValue === 0) {
879 return '0';
880 }
881 const locale = this.chart.options.locale;
882 let notation;
883 let delta = tickValue;
884 if (ticks.length > 1) {
885 const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));
886 if (maxTick < 1e-4 || maxTick > 1e+15) {
887 notation = 'scientific';
888 }
889 delta = calculateDelta(tickValue, ticks);
890 }
891 const logDelta = log10(Math.abs(delta));
892 const numDecimal = isNaN(logDelta) ? 1 : Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);
893 const options = {
894 notation,
895 minimumFractionDigits: numDecimal,
896 maximumFractionDigits: numDecimal
897 };
898 Object.assign(options, this.options.ticks.format);
899 return formatNumber(tickValue, locale, options);
900 },
901 logarithmic (tickValue, index, ticks) {
902 if (tickValue === 0) {
903 return '0';
904 }
905 const remain = ticks[index].significand || tickValue / Math.pow(10, Math.floor(log10(tickValue)));
906 if ([
907 1,
908 2,
909 3,
910 5,
911 10,
912 15
913 ].includes(remain) || index > 0.8 * ticks.length) {
914 return formatters.numeric.call(this, tickValue, index, ticks);
915 }
916 return '';
917 }
918 };
919 function calculateDelta(tickValue, ticks) {
920 let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;
921 if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) {
922 delta = tickValue - Math.floor(tickValue);
923 }
924 return delta;
925 }
926 var Ticks = {
927 formatters
928 };
929
930 function applyScaleDefaults(defaults) {
931 defaults.set('scale', {
932 display: true,
933 offset: false,
934 reverse: false,
935 beginAtZero: false,
936 bounds: 'ticks',
937 clip: true,
938 grace: 0,
939 grid: {
940 display: true,
941 lineWidth: 1,
942 drawOnChartArea: true,
943 drawTicks: true,
944 tickLength: 8,
945 tickWidth: (_ctx, options)=>options.lineWidth,
946 tickColor: (_ctx, options)=>options.color,
947 offset: false
948 },
949 border: {
950 display: true,
951 dash: [],
952 dashOffset: 0.0,
953 width: 1
954 },
955 title: {
956 display: false,
957 text: '',
958 padding: {
959 top: 4,
960 bottom: 4
961 }
962 },
963 ticks: {
964 minRotation: 0,
965 maxRotation: 50,
966 mirror: false,
967 textStrokeWidth: 0,
968 textStrokeColor: '',
969 padding: 3,
970 display: true,
971 autoSkip: true,
972 autoSkipPadding: 3,
973 labelOffset: 0,
974 callback: Ticks.formatters.values,
975 minor: {},
976 major: {},
977 align: 'center',
978 crossAlign: 'near',
979 showLabelBackdrop: false,
980 backdropColor: 'rgba(255, 255, 255, 0.75)',
981 backdropPadding: 2
982 }
983 });
984 defaults.route('scale.ticks', 'color', '', 'color');
985 defaults.route('scale.grid', 'color', '', 'borderColor');
986 defaults.route('scale.border', 'color', '', 'borderColor');
987 defaults.route('scale.title', 'color', '', 'color');
988 defaults.describe('scale', {
989 _fallback: false,
990 _scriptable: (name)=>!name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser',
991 _indexable: (name)=>name !== 'borderDash' && name !== 'tickBorderDash' && name !== 'dash'
992 });
993 defaults.describe('scales', {
994 _fallback: 'scale'
995 });
996 defaults.describe('scale.ticks', {
997 _scriptable: (name)=>name !== 'backdropPadding' && name !== 'callback',
998 _indexable: (name)=>name !== 'backdropPadding'
999 });
1000 }
1001
1002 const overrides = Object.create(null);
1003 const descriptors = Object.create(null);
1004 function getScope$1(node, key) {
1005 if (!key) {
1006 return node;
1007 }
1008 const keys = key.split('.');
1009 for(let i = 0, n = keys.length; i < n; ++i){
1010 const k = keys[i];
1011 node = node[k] || (node[k] = Object.create(null));
1012 }
1013 return node;
1014 }
1015 function set(root, scope, values) {
1016 if (typeof scope === 'string') {
1017 return merge(getScope$1(root, scope), values);
1018 }
1019 return merge(getScope$1(root, ''), scope);
1020 }
1021 class Defaults {
1022 constructor(_descriptors, _appliers){
1023 this.animation = undefined;
1024 this.backgroundColor = 'rgba(0,0,0,0.1)';
1025 this.borderColor = 'rgba(0,0,0,0.1)';
1026 this.color = '#666';
1027 this.datasets = {};
1028 this.devicePixelRatio = (context)=>context.chart.platform.getDevicePixelRatio();
1029 this.elements = {};
1030 this.events = [
1031 'mousemove',
1032 'mouseout',
1033 'click',
1034 'touchstart',
1035 'touchmove'
1036 ];
1037 this.font = {
1038 family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
1039 size: 12,
1040 style: 'normal',
1041 lineHeight: 1.2,
1042 weight: null
1043 };
1044 this.hover = {};
1045 this.hoverBackgroundColor = (ctx, options)=>getHoverColor(options.backgroundColor);
1046 this.hoverBorderColor = (ctx, options)=>getHoverColor(options.borderColor);
1047 this.hoverColor = (ctx, options)=>getHoverColor(options.color);
1048 this.indexAxis = 'x';
1049 this.interaction = {
1050 mode: 'nearest',
1051 intersect: true,
1052 includeInvisible: false
1053 };
1054 this.maintainAspectRatio = true;
1055 this.onHover = null;
1056 this.onClick = null;
1057 this.parsing = true;
1058 this.plugins = {};
1059 this.responsive = true;
1060 this.scale = undefined;
1061 this.scales = {};
1062 this.showLine = true;
1063 this.drawActiveElementsOnTop = true;
1064 this.describe(_descriptors);
1065 this.apply(_appliers);
1066 }
1067 set(scope, values) {
1068 return set(this, scope, values);
1069 }
1070 get(scope) {
1071 return getScope$1(this, scope);
1072 }
1073 describe(scope, values) {
1074 return set(descriptors, scope, values);
1075 }
1076 override(scope, values) {
1077 return set(overrides, scope, values);
1078 }
1079 route(scope, name, targetScope, targetName) {
1080 const scopeObject = getScope$1(this, scope);
1081 const targetScopeObject = getScope$1(this, targetScope);
1082 const privateName = '_' + name;
1083 Object.defineProperties(scopeObject, {
1084 [privateName]: {
1085 value: scopeObject[name],
1086 writable: true
1087 },
1088 [name]: {
1089 enumerable: true,
1090 get () {
1091 const local = this[privateName];
1092 const target = targetScopeObject[targetName];
1093 if (isObject(local)) {
1094 return Object.assign({}, target, local);
1095 }
1096 return valueOrDefault(local, target);
1097 },
1098 set (value) {
1099 this[privateName] = value;
1100 }
1101 }
1102 });
1103 }
1104 apply(appliers) {
1105 appliers.forEach((apply)=>apply(this));
1106 }
1107 }
1108 var defaults = /* #__PURE__ */ new Defaults({
1109 _scriptable: (name)=>!name.startsWith('on'),
1110 _indexable: (name)=>name !== 'events',
1111 hover: {
1112 _fallback: 'interaction'
1113 },
1114 interaction: {
1115 _scriptable: false,
1116 _indexable: false
1117 }
1118 }, [
1119 applyAnimationsDefaults,
1120 applyLayoutsDefaults,
1121 applyScaleDefaults
1122 ]);
1123
1124 /**
1125 * Converts the given font object into a CSS font string.
1126 * @param font - A font object.
1127 * @return The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
1128 * @private
1129 */ function toFontString(font) {
1130 if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) {
1131 return null;
1132 }
1133 return (font.style ? font.style + ' ' : '') + (font.weight ? font.weight + ' ' : '') + font.size + 'px ' + font.family;
1134 }
1135 /**
1136 * @private
1137 */ function _measureText(ctx, data, gc, longest, string) {
1138 let textWidth = data[string];
1139 if (!textWidth) {
1140 textWidth = data[string] = ctx.measureText(string).width;
1141 gc.push(string);
1142 }
1143 if (textWidth > longest) {
1144 longest = textWidth;
1145 }
1146 return longest;
1147 }
1148 /**
1149 * @private
1150 */ // eslint-disable-next-line complexity
1151 function _longestText(ctx, font, arrayOfThings, cache) {
1152 cache = cache || {};
1153 let data = cache.data = cache.data || {};
1154 let gc = cache.garbageCollect = cache.garbageCollect || [];
1155 if (cache.font !== font) {
1156 data = cache.data = {};
1157 gc = cache.garbageCollect = [];
1158 cache.font = font;
1159 }
1160 ctx.save();
1161 ctx.font = font;
1162 let longest = 0;
1163 const ilen = arrayOfThings.length;
1164 let i, j, jlen, thing, nestedThing;
1165 for(i = 0; i < ilen; i++){
1166 thing = arrayOfThings[i];
1167 // Undefined strings and arrays should not be measured
1168 if (thing !== undefined && thing !== null && !isArray(thing)) {
1169 longest = _measureText(ctx, data, gc, longest, thing);
1170 } else if (isArray(thing)) {
1171 // if it is an array lets measure each element
1172 // to do maybe simplify this function a bit so we can do this more recursively?
1173 for(j = 0, jlen = thing.length; j < jlen; j++){
1174 nestedThing = thing[j];
1175 // Undefined strings and arrays should not be measured
1176 if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) {
1177 longest = _measureText(ctx, data, gc, longest, nestedThing);
1178 }
1179 }
1180 }
1181 }
1182 ctx.restore();
1183 const gcLen = gc.length / 2;
1184 if (gcLen > arrayOfThings.length) {
1185 for(i = 0; i < gcLen; i++){
1186 delete data[gc[i]];
1187 }
1188 gc.splice(0, gcLen);
1189 }
1190 return longest;
1191 }
1192 /**
1193 * Returns the aligned pixel value to avoid anti-aliasing blur
1194 * @param chart - The chart instance.
1195 * @param pixel - A pixel value.
1196 * @param width - The width of the element.
1197 * @returns The aligned pixel value.
1198 * @private
1199 */ function _alignPixel(chart, pixel, width) {
1200 const devicePixelRatio = chart.currentDevicePixelRatio;
1201 const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0;
1202 return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
1203 }
1204 /**
1205 * Clears the entire canvas.
1206 */ function clearCanvas(canvas, ctx) {
1207 if (!ctx && !canvas) {
1208 return;
1209 }
1210 ctx = ctx || canvas.getContext('2d');
1211 ctx.save();
1212 // canvas.width and canvas.height do not consider the canvas transform,
1213 // while clearRect does
1214 ctx.resetTransform();
1215 ctx.clearRect(0, 0, canvas.width, canvas.height);
1216 ctx.restore();
1217 }
1218 function drawPoint(ctx, options, x, y) {
1219 // eslint-disable-next-line @typescript-eslint/no-use-before-define
1220 drawPointLegend(ctx, options, x, y, null);
1221 }
1222 // eslint-disable-next-line complexity
1223 function drawPointLegend(ctx, options, x, y, w) {
1224 let type, xOffset, yOffset, size, cornerRadius, width, xOffsetW, yOffsetW;
1225 const style = options.pointStyle;
1226 const rotation = options.rotation;
1227 const radius = options.radius;
1228 let rad = (rotation || 0) * RAD_PER_DEG;
1229 if (style && typeof style === 'object') {
1230 type = style.toString();
1231 if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
1232 ctx.save();
1233 ctx.translate(x, y);
1234 ctx.rotate(rad);
1235 ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
1236 ctx.restore();
1237 return;
1238 }
1239 }
1240 if (isNaN(radius) || radius <= 0) {
1241 return;
1242 }
1243 ctx.beginPath();
1244 switch(style){
1245 // Default includes circle
1246 default:
1247 if (w) {
1248 ctx.ellipse(x, y, w / 2, radius, 0, 0, TAU);
1249 } else {
1250 ctx.arc(x, y, radius, 0, TAU);
1251 }
1252 ctx.closePath();
1253 break;
1254 case 'triangle':
1255 width = w ? w / 2 : radius;
1256 ctx.moveTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);
1257 rad += TWO_THIRDS_PI;
1258 ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);
1259 rad += TWO_THIRDS_PI;
1260 ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);
1261 ctx.closePath();
1262 break;
1263 case 'rectRounded':
1264 // NOTE: the rounded rect implementation changed to use `arc` instead of
1265 // `quadraticCurveTo` since it generates better results when rect is
1266 // almost a circle. 0.516 (instead of 0.5) produces results with visually
1267 // closer proportion to the previous impl and it is inscribed in the
1268 // circle with `radius`. For more details, see the following PRs:
1269 // https://github.com/chartjs/Chart.js/issues/5597
1270 // https://github.com/chartjs/Chart.js/issues/5858
1271 cornerRadius = radius * 0.516;
1272 size = radius - cornerRadius;
1273 xOffset = Math.cos(rad + QUARTER_PI) * size;
1274 xOffsetW = Math.cos(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);
1275 yOffset = Math.sin(rad + QUARTER_PI) * size;
1276 yOffsetW = Math.sin(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);
1277 ctx.arc(x - xOffsetW, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
1278 ctx.arc(x + yOffsetW, y - xOffset, cornerRadius, rad - HALF_PI, rad);
1279 ctx.arc(x + xOffsetW, y + yOffset, cornerRadius, rad, rad + HALF_PI);
1280 ctx.arc(x - yOffsetW, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
1281 ctx.closePath();
1282 break;
1283 case 'rect':
1284 if (!rotation) {
1285 size = Math.SQRT1_2 * radius;
1286 width = w ? w / 2 : size;
1287 ctx.rect(x - width, y - size, 2 * width, 2 * size);
1288 break;
1289 }
1290 rad += QUARTER_PI;
1291 /* falls through */ case 'rectRot':
1292 xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);
1293 xOffset = Math.cos(rad) * radius;
1294 yOffset = Math.sin(rad) * radius;
1295 yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);
1296 ctx.moveTo(x - xOffsetW, y - yOffset);
1297 ctx.lineTo(x + yOffsetW, y - xOffset);
1298 ctx.lineTo(x + xOffsetW, y + yOffset);
1299 ctx.lineTo(x - yOffsetW, y + xOffset);
1300 ctx.closePath();
1301 break;
1302 case 'crossRot':
1303 rad += QUARTER_PI;
1304 /* falls through */ case 'cross':
1305 xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);
1306 xOffset = Math.cos(rad) * radius;
1307 yOffset = Math.sin(rad) * radius;
1308 yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);
1309 ctx.moveTo(x - xOffsetW, y - yOffset);
1310 ctx.lineTo(x + xOffsetW, y + yOffset);
1311 ctx.moveTo(x + yOffsetW, y - xOffset);
1312 ctx.lineTo(x - yOffsetW, y + xOffset);
1313 break;
1314 case 'star':
1315 xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);
1316 xOffset = Math.cos(rad) * radius;
1317 yOffset = Math.sin(rad) * radius;
1318 yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);
1319 ctx.moveTo(x - xOffsetW, y - yOffset);
1320 ctx.lineTo(x + xOffsetW, y + yOffset);
1321 ctx.moveTo(x + yOffsetW, y - xOffset);
1322 ctx.lineTo(x - yOffsetW, y + xOffset);
1323 rad += QUARTER_PI;
1324 xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);
1325 xOffset = Math.cos(rad) * radius;
1326 yOffset = Math.sin(rad) * radius;
1327 yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);
1328 ctx.moveTo(x - xOffsetW, y - yOffset);
1329 ctx.lineTo(x + xOffsetW, y + yOffset);
1330 ctx.moveTo(x + yOffsetW, y - xOffset);
1331 ctx.lineTo(x - yOffsetW, y + xOffset);
1332 break;
1333 case 'line':
1334 xOffset = w ? w / 2 : Math.cos(rad) * radius;
1335 yOffset = Math.sin(rad) * radius;
1336 ctx.moveTo(x - xOffset, y - yOffset);
1337 ctx.lineTo(x + xOffset, y + yOffset);
1338 break;
1339 case 'dash':
1340 ctx.moveTo(x, y);
1341 ctx.lineTo(x + Math.cos(rad) * (w ? w / 2 : radius), y + Math.sin(rad) * radius);
1342 break;
1343 case false:
1344 ctx.closePath();
1345 break;
1346 }
1347 ctx.fill();
1348 if (options.borderWidth > 0) {
1349 ctx.stroke();
1350 }
1351 }
1352 /**
1353 * Returns true if the point is inside the rectangle
1354 * @param point - The point to test
1355 * @param area - The rectangle
1356 * @param margin - allowed margin
1357 * @private
1358 */ function _isPointInArea(point, area, margin) {
1359 margin = margin || 0.5; // margin - default is to match rounded decimals
1360 return !area || point && point.x > area.left - margin && point.x < area.right + margin && point.y > area.top - margin && point.y < area.bottom + margin;
1361 }
1362 function clipArea(ctx, area) {
1363 ctx.save();
1364 ctx.beginPath();
1365 ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
1366 ctx.clip();
1367 }
1368 function unclipArea(ctx) {
1369 ctx.restore();
1370 }
1371 /**
1372 * @private
1373 */ function _steppedLineTo(ctx, previous, target, flip, mode) {
1374 if (!previous) {
1375 return ctx.lineTo(target.x, target.y);
1376 }
1377 if (mode === 'middle') {
1378 const midpoint = (previous.x + target.x) / 2.0;
1379 ctx.lineTo(midpoint, previous.y);
1380 ctx.lineTo(midpoint, target.y);
1381 } else if (mode === 'after' !== !!flip) {
1382 ctx.lineTo(previous.x, target.y);
1383 } else {
1384 ctx.lineTo(target.x, previous.y);
1385 }
1386 ctx.lineTo(target.x, target.y);
1387 }
1388 /**
1389 * @private
1390 */ function _bezierCurveTo(ctx, previous, target, flip) {
1391 if (!previous) {
1392 return ctx.lineTo(target.x, target.y);
1393 }
1394 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);
1395 }
1396 function setRenderOpts(ctx, opts) {
1397 if (opts.translation) {
1398 ctx.translate(opts.translation[0], opts.translation[1]);
1399 }
1400 if (!isNullOrUndef(opts.rotation)) {
1401 ctx.rotate(opts.rotation);
1402 }
1403 if (opts.color) {
1404 ctx.fillStyle = opts.color;
1405 }
1406 if (opts.textAlign) {
1407 ctx.textAlign = opts.textAlign;
1408 }
1409 if (opts.textBaseline) {
1410 ctx.textBaseline = opts.textBaseline;
1411 }
1412 }
1413 function decorateText(ctx, x, y, line, opts) {
1414 if (opts.strikethrough || opts.underline) {
1415 /**
1416 * Now that IE11 support has been dropped, we can use more
1417 * of the TextMetrics object. The actual bounding boxes
1418 * are unflagged in Chrome, Firefox, Edge, and Safari so they
1419 * can be safely used.
1420 * See https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics#Browser_compatibility
1421 */ const metrics = ctx.measureText(line);
1422 const left = x - metrics.actualBoundingBoxLeft;
1423 const right = x + metrics.actualBoundingBoxRight;
1424 const top = y - metrics.actualBoundingBoxAscent;
1425 const bottom = y + metrics.actualBoundingBoxDescent;
1426 const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom;
1427 ctx.strokeStyle = ctx.fillStyle;
1428 ctx.beginPath();
1429 ctx.lineWidth = opts.decorationWidth || 2;
1430 ctx.moveTo(left, yDecoration);
1431 ctx.lineTo(right, yDecoration);
1432 ctx.stroke();
1433 }
1434 }
1435 function drawBackdrop(ctx, opts) {
1436 const oldColor = ctx.fillStyle;
1437 ctx.fillStyle = opts.color;
1438 ctx.fillRect(opts.left, opts.top, opts.width, opts.height);
1439 ctx.fillStyle = oldColor;
1440 }
1441 /**
1442 * Render text onto the canvas
1443 */ function renderText(ctx, text, x, y, font, opts = {}) {
1444 const lines = isArray(text) ? text : [
1445 text
1446 ];
1447 const stroke = opts.strokeWidth > 0 && opts.strokeColor !== '';
1448 let i, line;
1449 ctx.save();
1450 ctx.font = font.string;
1451 setRenderOpts(ctx, opts);
1452 for(i = 0; i < lines.length; ++i){
1453 line = lines[i];
1454 if (opts.backdrop) {
1455 drawBackdrop(ctx, opts.backdrop);
1456 }
1457 if (stroke) {
1458 if (opts.strokeColor) {
1459 ctx.strokeStyle = opts.strokeColor;
1460 }
1461 if (!isNullOrUndef(opts.strokeWidth)) {
1462 ctx.lineWidth = opts.strokeWidth;
1463 }
1464 ctx.strokeText(line, x, y, opts.maxWidth);
1465 }
1466 ctx.fillText(line, x, y, opts.maxWidth);
1467 decorateText(ctx, x, y, line, opts);
1468 y += Number(font.lineHeight);
1469 }
1470 ctx.restore();
1471 }
1472 /**
1473 * Add a path of a rectangle with rounded corners to the current sub-path
1474 * @param ctx - Context
1475 * @param rect - Bounding rect
1476 */ function addRoundedRectPath(ctx, rect) {
1477 const { x , y , w , h , radius } = rect;
1478 // top left arc
1479 ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, 1.5 * PI, PI, true);
1480 // line from top left to bottom left
1481 ctx.lineTo(x, y + h - radius.bottomLeft);
1482 // bottom left arc
1483 ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true);
1484 // line from bottom left to bottom right
1485 ctx.lineTo(x + w - radius.bottomRight, y + h);
1486 // bottom right arc
1487 ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true);
1488 // line from bottom right to top right
1489 ctx.lineTo(x + w, y + radius.topRight);
1490 // top right arc
1491 ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true);
1492 // line from top right to top left
1493 ctx.lineTo(x + radius.topLeft, y);
1494 }
1495
1496 const LINE_HEIGHT = /^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/;
1497 const FONT_STYLE = /^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;
1498 /**
1499 * @alias Chart.helpers.options
1500 * @namespace
1501 */ /**
1502 * Converts the given line height `value` in pixels for a specific font `size`.
1503 * @param value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
1504 * @param size - The font size (in pixels) used to resolve relative `value`.
1505 * @returns The effective line height in pixels (size * 1.2 if value is invalid).
1506 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
1507 * @since 2.7.0
1508 */ function toLineHeight(value, size) {
1509 const matches = ('' + value).match(LINE_HEIGHT);
1510 if (!matches || matches[1] === 'normal') {
1511 return size * 1.2;
1512 }
1513 value = +matches[2];
1514 switch(matches[3]){
1515 case 'px':
1516 return value;
1517 case '%':
1518 value /= 100;
1519 break;
1520 }
1521 return size * value;
1522 }
1523 const numberOrZero = (v)=>+v || 0;
1524 function _readValueToProps(value, props) {
1525 const ret = {};
1526 const objProps = isObject(props);
1527 const keys = objProps ? Object.keys(props) : props;
1528 const read = isObject(value) ? objProps ? (prop)=>valueOrDefault(value[prop], value[props[prop]]) : (prop)=>value[prop] : ()=>value;
1529 for (const prop of keys){
1530 ret[prop] = numberOrZero(read(prop));
1531 }
1532 return ret;
1533 }
1534 /**
1535 * Converts the given value into a TRBL object.
1536 * @param value - If a number, set the value to all TRBL component,
1537 * else, if an object, use defined properties and sets undefined ones to 0.
1538 * x / y are shorthands for same value for left/right and top/bottom.
1539 * @returns The padding values (top, right, bottom, left)
1540 * @since 3.0.0
1541 */ function toTRBL(value) {
1542 return _readValueToProps(value, {
1543 top: 'y',
1544 right: 'x',
1545 bottom: 'y',
1546 left: 'x'
1547 });
1548 }
1549 /**
1550 * Converts the given value into a TRBL corners object (similar with css border-radius).
1551 * @param value - If a number, set the value to all TRBL corner components,
1552 * else, if an object, use defined properties and sets undefined ones to 0.
1553 * @returns The TRBL corner values (topLeft, topRight, bottomLeft, bottomRight)
1554 * @since 3.0.0
1555 */ function toTRBLCorners(value) {
1556 return _readValueToProps(value, [
1557 'topLeft',
1558 'topRight',
1559 'bottomLeft',
1560 'bottomRight'
1561 ]);
1562 }
1563 /**
1564 * Converts the given value into a padding object with pre-computed width/height.
1565 * @param value - If a number, set the value to all TRBL component,
1566 * else, if an object, use defined properties and sets undefined ones to 0.
1567 * x / y are shorthands for same value for left/right and top/bottom.
1568 * @returns The padding values (top, right, bottom, left, width, height)
1569 * @since 2.7.0
1570 */ function toPadding(value) {
1571 const obj = toTRBL(value);
1572 obj.width = obj.left + obj.right;
1573 obj.height = obj.top + obj.bottom;
1574 return obj;
1575 }
1576 /**
1577 * Parses font options and returns the font object.
1578 * @param options - A object that contains font options to be parsed.
1579 * @param fallback - A object that contains fallback font options.
1580 * @return The font object.
1581 * @private
1582 */ function toFont(options, fallback) {
1583 options = options || {};
1584 fallback = fallback || defaults.font;
1585 let size = valueOrDefault(options.size, fallback.size);
1586 if (typeof size === 'string') {
1587 size = parseInt(size, 10);
1588 }
1589 let style = valueOrDefault(options.style, fallback.style);
1590 if (style && !('' + style).match(FONT_STYLE)) {
1591 console.warn('Invalid font style specified: "' + style + '"');
1592 style = undefined;
1593 }
1594 const font = {
1595 family: valueOrDefault(options.family, fallback.family),
1596 lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size),
1597 size,
1598 style,
1599 weight: valueOrDefault(options.weight, fallback.weight),
1600 string: ''
1601 };
1602 font.string = toFontString(font);
1603 return font;
1604 }
1605 /**
1606 * Evaluates the given `inputs` sequentially and returns the first defined value.
1607 * @param inputs - An array of values, falling back to the last value.
1608 * @param context - If defined and the current value is a function, the value
1609 * is called with `context` as first argument and the result becomes the new input.
1610 * @param index - If defined and the current value is an array, the value
1611 * at `index` become the new input.
1612 * @param info - object to return information about resolution in
1613 * @param info.cacheable - Will be set to `false` if option is not cacheable.
1614 * @since 2.7.0
1615 */ function resolve(inputs, context, index, info) {
1616 let cacheable = true;
1617 let i, ilen, value;
1618 for(i = 0, ilen = inputs.length; i < ilen; ++i){
1619 value = inputs[i];
1620 if (value === undefined) {
1621 continue;
1622 }
1623 if (context !== undefined && typeof value === 'function') {
1624 value = value(context);
1625 cacheable = false;
1626 }
1627 if (index !== undefined && isArray(value)) {
1628 value = value[index % value.length];
1629 cacheable = false;
1630 }
1631 if (value !== undefined) {
1632 if (info && !cacheable) {
1633 info.cacheable = false;
1634 }
1635 return value;
1636 }
1637 }
1638 }
1639 /**
1640 * @param minmax
1641 * @param grace
1642 * @param beginAtZero
1643 * @private
1644 */ function _addGrace(minmax, grace, beginAtZero) {
1645 const { min , max } = minmax;
1646 const change = toDimension(grace, (max - min) / 2);
1647 const keepZero = (value, add)=>beginAtZero && value === 0 ? 0 : value + add;
1648 return {
1649 min: keepZero(min, -Math.abs(change)),
1650 max: keepZero(max, change)
1651 };
1652 }
1653 function createContext(parentContext, context) {
1654 return Object.assign(Object.create(parentContext), context);
1655 }
1656
1657 /**
1658 * Creates a Proxy for resolving raw values for options.
1659 * @param scopes - The option scopes to look for values, in resolution order
1660 * @param prefixes - The prefixes for values, in resolution order.
1661 * @param rootScopes - The root option scopes
1662 * @param fallback - Parent scopes fallback
1663 * @param getTarget - callback for getting the target for changed values
1664 * @returns Proxy
1665 * @private
1666 */ function _createResolver(scopes, prefixes = [
1667 ''
1668 ], rootScopes, fallback, getTarget = ()=>scopes[0]) {
1669 const finalRootScopes = rootScopes || scopes;
1670 if (typeof fallback === 'undefined') {
1671 fallback = _resolve('_fallback', scopes);
1672 }
1673 const cache = {
1674 [Symbol.toStringTag]: 'Object',
1675 _cacheable: true,
1676 _scopes: scopes,
1677 _rootScopes: finalRootScopes,
1678 _fallback: fallback,
1679 _getTarget: getTarget,
1680 override: (scope)=>_createResolver([
1681 scope,
1682 ...scopes
1683 ], prefixes, finalRootScopes, fallback)
1684 };
1685 return new Proxy(cache, {
1686 /**
1687 * A trap for the delete operator.
1688 */ deleteProperty (target, prop) {
1689 delete target[prop]; // remove from cache
1690 delete target._keys; // remove cached keys
1691 delete scopes[0][prop]; // remove from top level scope
1692 return true;
1693 },
1694 /**
1695 * A trap for getting property values.
1696 */ get (target, prop) {
1697 return _cached(target, prop, ()=>_resolveWithPrefixes(prop, prefixes, scopes, target));
1698 },
1699 /**
1700 * A trap for Object.getOwnPropertyDescriptor.
1701 * Also used by Object.hasOwnProperty.
1702 */ getOwnPropertyDescriptor (target, prop) {
1703 return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop);
1704 },
1705 /**
1706 * A trap for Object.getPrototypeOf.
1707 */ getPrototypeOf () {
1708 return Reflect.getPrototypeOf(scopes[0]);
1709 },
1710 /**
1711 * A trap for the in operator.
1712 */ has (target, prop) {
1713 return getKeysFromAllScopes(target).includes(prop);
1714 },
1715 /**
1716 * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.
1717 */ ownKeys (target) {
1718 return getKeysFromAllScopes(target);
1719 },
1720 /**
1721 * A trap for setting property values.
1722 */ set (target, prop, value) {
1723 const storage = target._storage || (target._storage = getTarget());
1724 target[prop] = storage[prop] = value; // set to top level scope + cache
1725 delete target._keys; // remove cached keys
1726 return true;
1727 }
1728 });
1729 }
1730 /**
1731 * Returns an Proxy for resolving option values with context.
1732 * @param proxy - The Proxy returned by `_createResolver`
1733 * @param context - Context object for scriptable/indexable options
1734 * @param subProxy - The proxy provided for scriptable options
1735 * @param descriptorDefaults - Defaults for descriptors
1736 * @private
1737 */ function _attachContext(proxy, context, subProxy, descriptorDefaults) {
1738 const cache = {
1739 _cacheable: false,
1740 _proxy: proxy,
1741 _context: context,
1742 _subProxy: subProxy,
1743 _stack: new Set(),
1744 _descriptors: _descriptors(proxy, descriptorDefaults),
1745 setContext: (ctx)=>_attachContext(proxy, ctx, subProxy, descriptorDefaults),
1746 override: (scope)=>_attachContext(proxy.override(scope), context, subProxy, descriptorDefaults)
1747 };
1748 return new Proxy(cache, {
1749 /**
1750 * A trap for the delete operator.
1751 */ deleteProperty (target, prop) {
1752 delete target[prop]; // remove from cache
1753 delete proxy[prop]; // remove from proxy
1754 return true;
1755 },
1756 /**
1757 * A trap for getting property values.
1758 */ get (target, prop, receiver) {
1759 return _cached(target, prop, ()=>_resolveWithContext(target, prop, receiver));
1760 },
1761 /**
1762 * A trap for Object.getOwnPropertyDescriptor.
1763 * Also used by Object.hasOwnProperty.
1764 */ getOwnPropertyDescriptor (target, prop) {
1765 return target._descriptors.allKeys ? Reflect.has(proxy, prop) ? {
1766 enumerable: true,
1767 configurable: true
1768 } : undefined : Reflect.getOwnPropertyDescriptor(proxy, prop);
1769 },
1770 /**
1771 * A trap for Object.getPrototypeOf.
1772 */ getPrototypeOf () {
1773 return Reflect.getPrototypeOf(proxy);
1774 },
1775 /**
1776 * A trap for the in operator.
1777 */ has (target, prop) {
1778 return Reflect.has(proxy, prop);
1779 },
1780 /**
1781 * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.
1782 */ ownKeys () {
1783 return Reflect.ownKeys(proxy);
1784 },
1785 /**
1786 * A trap for setting property values.
1787 */ set (target, prop, value) {
1788 proxy[prop] = value; // set to proxy
1789 delete target[prop]; // remove from cache
1790 return true;
1791 }
1792 });
1793 }
1794 /**
1795 * @private
1796 */ function _descriptors(proxy, defaults = {
1797 scriptable: true,
1798 indexable: true
1799 }) {
1800 const { _scriptable =defaults.scriptable , _indexable =defaults.indexable , _allKeys =defaults.allKeys } = proxy;
1801 return {
1802 allKeys: _allKeys,
1803 scriptable: _scriptable,
1804 indexable: _indexable,
1805 isScriptable: isFunction(_scriptable) ? _scriptable : ()=>_scriptable,
1806 isIndexable: isFunction(_indexable) ? _indexable : ()=>_indexable
1807 };
1808 }
1809 const readKey = (prefix, name)=>prefix ? prefix + _capitalize(name) : name;
1810 const needsSubResolver = (prop, value)=>isObject(value) && prop !== 'adapters' && (Object.getPrototypeOf(value) === null || value.constructor === Object);
1811 function _cached(target, prop, resolve) {
1812 if (Object.prototype.hasOwnProperty.call(target, prop) || prop === 'constructor') {
1813 return target[prop];
1814 }
1815 const value = resolve();
1816 // cache the resolved value
1817 target[prop] = value;
1818 return value;
1819 }
1820 function _resolveWithContext(target, prop, receiver) {
1821 const { _proxy , _context , _subProxy , _descriptors: descriptors } = target;
1822 let value = _proxy[prop]; // resolve from proxy
1823 // resolve with context
1824 if (isFunction(value) && descriptors.isScriptable(prop)) {
1825 value = _resolveScriptable(prop, value, target, receiver);
1826 }
1827 if (isArray(value) && value.length) {
1828 value = _resolveArray(prop, value, target, descriptors.isIndexable);
1829 }
1830 if (needsSubResolver(prop, value)) {
1831 // if the resolved value is an object, create a sub resolver for it
1832 value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors);
1833 }
1834 return value;
1835 }
1836 function _resolveScriptable(prop, getValue, target, receiver) {
1837 const { _proxy , _context , _subProxy , _stack } = target;
1838 if (_stack.has(prop)) {
1839 throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop);
1840 }
1841 _stack.add(prop);
1842 let value = getValue(_context, _subProxy || receiver);
1843 _stack.delete(prop);
1844 if (needsSubResolver(prop, value)) {
1845 // When scriptable option returns an object, create a resolver on that.
1846 value = createSubResolver(_proxy._scopes, _proxy, prop, value);
1847 }
1848 return value;
1849 }
1850 function _resolveArray(prop, value, target, isIndexable) {
1851 const { _proxy , _context , _subProxy , _descriptors: descriptors } = target;
1852 if (typeof _context.index !== 'undefined' && isIndexable(prop)) {
1853 return value[_context.index % value.length];
1854 } else if (isObject(value[0])) {
1855 // Array of objects, return array or resolvers
1856 const arr = value;
1857 const scopes = _proxy._scopes.filter((s)=>s !== arr);
1858 value = [];
1859 for (const item of arr){
1860 const resolver = createSubResolver(scopes, _proxy, prop, item);
1861 value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors));
1862 }
1863 }
1864 return value;
1865 }
1866 function resolveFallback(fallback, prop, value) {
1867 return isFunction(fallback) ? fallback(prop, value) : fallback;
1868 }
1869 const getScope = (key, parent)=>key === true ? parent : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined;
1870 function addScopes(set, parentScopes, key, parentFallback, value) {
1871 for (const parent of parentScopes){
1872 const scope = getScope(key, parent);
1873 if (scope) {
1874 set.add(scope);
1875 const fallback = resolveFallback(scope._fallback, key, value);
1876 if (typeof fallback !== 'undefined' && fallback !== key && fallback !== parentFallback) {
1877 // When we reach the descriptor that defines a new _fallback, return that.
1878 // The fallback will resume to that new scope.
1879 return fallback;
1880 }
1881 } else if (scope === false && typeof parentFallback !== 'undefined' && key !== parentFallback) {
1882 // Fallback to `false` results to `false`, when falling back to different key.
1883 // For example `interaction` from `hover` or `plugins.tooltip` and `animation` from `animations`
1884 return null;
1885 }
1886 }
1887 return false;
1888 }
1889 function createSubResolver(parentScopes, resolver, prop, value) {
1890 const rootScopes = resolver._rootScopes;
1891 const fallback = resolveFallback(resolver._fallback, prop, value);
1892 const allScopes = [
1893 ...parentScopes,
1894 ...rootScopes
1895 ];
1896 const set = new Set();
1897 set.add(value);
1898 let key = addScopesFromKey(set, allScopes, prop, fallback || prop, value);
1899 if (key === null) {
1900 return false;
1901 }
1902 if (typeof fallback !== 'undefined' && fallback !== prop) {
1903 key = addScopesFromKey(set, allScopes, fallback, key, value);
1904 if (key === null) {
1905 return false;
1906 }
1907 }
1908 return _createResolver(Array.from(set), [
1909 ''
1910 ], rootScopes, fallback, ()=>subGetTarget(resolver, prop, value));
1911 }
1912 function addScopesFromKey(set, allScopes, key, fallback, item) {
1913 while(key){
1914 key = addScopes(set, allScopes, key, fallback, item);
1915 }
1916 return key;
1917 }
1918 function subGetTarget(resolver, prop, value) {
1919 const parent = resolver._getTarget();
1920 if (!(prop in parent)) {
1921 parent[prop] = {};
1922 }
1923 const target = parent[prop];
1924 if (isArray(target) && isObject(value)) {
1925 // For array of objects, the object is used to store updated values
1926 return value;
1927 }
1928 return target || {};
1929 }
1930 function _resolveWithPrefixes(prop, prefixes, scopes, proxy) {
1931 let value;
1932 for (const prefix of prefixes){
1933 value = _resolve(readKey(prefix, prop), scopes);
1934 if (typeof value !== 'undefined') {
1935 return needsSubResolver(prop, value) ? createSubResolver(scopes, proxy, prop, value) : value;
1936 }
1937 }
1938 }
1939 function _resolve(key, scopes) {
1940 for (const scope of scopes){
1941 if (!scope) {
1942 continue;
1943 }
1944 const value = scope[key];
1945 if (typeof value !== 'undefined') {
1946 return value;
1947 }
1948 }
1949 }
1950 function getKeysFromAllScopes(target) {
1951 let keys = target._keys;
1952 if (!keys) {
1953 keys = target._keys = resolveKeysFromAllScopes(target._scopes);
1954 }
1955 return keys;
1956 }
1957 function resolveKeysFromAllScopes(scopes) {
1958 const set = new Set();
1959 for (const scope of scopes){
1960 for (const key of Object.keys(scope).filter((k)=>!k.startsWith('_'))){
1961 set.add(key);
1962 }
1963 }
1964 return Array.from(set);
1965 }
1966 function _parseObjectDataRadialScale(meta, data, start, count) {
1967 const { iScale } = meta;
1968 const { key ='r' } = this._parsing;
1969 const parsed = new Array(count);
1970 let i, ilen, index, item;
1971 for(i = 0, ilen = count; i < ilen; ++i){
1972 index = i + start;
1973 item = data[index];
1974 parsed[i] = {
1975 r: iScale.parse(resolveObjectKey(item, key), index)
1976 };
1977 }
1978 return parsed;
1979 }
1980
1981 const EPSILON = Number.EPSILON || 1e-14;
1982 const getPoint = (points, i)=>i < points.length && !points[i].skip && points[i];
1983 const getValueAxis = (indexAxis)=>indexAxis === 'x' ? 'y' : 'x';
1984 function splineCurve(firstPoint, middlePoint, afterPoint, t) {
1985 // Props to Rob Spencer at scaled innovation for his post on splining between points
1986 // http://scaledinnovation.com/analytics/splines/aboutSplines.html
1987 // This function must also respect "skipped" points
1988 const previous = firstPoint.skip ? middlePoint : firstPoint;
1989 const current = middlePoint;
1990 const next = afterPoint.skip ? middlePoint : afterPoint;
1991 const d01 = distanceBetweenPoints(current, previous);
1992 const d12 = distanceBetweenPoints(next, current);
1993 let s01 = d01 / (d01 + d12);
1994 let s12 = d12 / (d01 + d12);
1995 // If all points are the same, s01 & s02 will be inf
1996 s01 = isNaN(s01) ? 0 : s01;
1997 s12 = isNaN(s12) ? 0 : s12;
1998 const fa = t * s01; // scaling factor for triangle Ta
1999 const fb = t * s12;
2000 return {
2001 previous: {
2002 x: current.x - fa * (next.x - previous.x),
2003 y: current.y - fa * (next.y - previous.y)
2004 },
2005 next: {
2006 x: current.x + fb * (next.x - previous.x),
2007 y: current.y + fb * (next.y - previous.y)
2008 }
2009 };
2010 }
2011 /**
2012 * Adjust tangents to ensure monotonic properties
2013 */ function monotoneAdjust(points, deltaK, mK) {
2014 const pointsLen = points.length;
2015 let alphaK, betaK, tauK, squaredMagnitude, pointCurrent;
2016 let pointAfter = getPoint(points, 0);
2017 for(let i = 0; i < pointsLen - 1; ++i){
2018 pointCurrent = pointAfter;
2019 pointAfter = getPoint(points, i + 1);
2020 if (!pointCurrent || !pointAfter) {
2021 continue;
2022 }
2023 if (almostEquals(deltaK[i], 0, EPSILON)) {
2024 mK[i] = mK[i + 1] = 0;
2025 continue;
2026 }
2027 alphaK = mK[i] / deltaK[i];
2028 betaK = mK[i + 1] / deltaK[i];
2029 squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
2030 if (squaredMagnitude <= 9) {
2031 continue;
2032 }
2033 tauK = 3 / Math.sqrt(squaredMagnitude);
2034 mK[i] = alphaK * tauK * deltaK[i];
2035 mK[i + 1] = betaK * tauK * deltaK[i];
2036 }
2037 }
2038 function monotoneCompute(points, mK, indexAxis = 'x') {
2039 const valueAxis = getValueAxis(indexAxis);
2040 const pointsLen = points.length;
2041 let delta, pointBefore, pointCurrent;
2042 let pointAfter = getPoint(points, 0);
2043 for(let i = 0; i < pointsLen; ++i){
2044 pointBefore = pointCurrent;
2045 pointCurrent = pointAfter;
2046 pointAfter = getPoint(points, i + 1);
2047 if (!pointCurrent) {
2048 continue;
2049 }
2050 const iPixel = pointCurrent[indexAxis];
2051 const vPixel = pointCurrent[valueAxis];
2052 if (pointBefore) {
2053 delta = (iPixel - pointBefore[indexAxis]) / 3;
2054 pointCurrent[`cp1${indexAxis}`] = iPixel - delta;
2055 pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i];
2056 }
2057 if (pointAfter) {
2058 delta = (pointAfter[indexAxis] - iPixel) / 3;
2059 pointCurrent[`cp2${indexAxis}`] = iPixel + delta;
2060 pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i];
2061 }
2062 }
2063 }
2064 /**
2065 * This function calculates Bézier control points in a similar way than |splineCurve|,
2066 * but preserves monotonicity of the provided data and ensures no local extremums are added
2067 * between the dataset discrete points due to the interpolation.
2068 * See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
2069 */ function splineCurveMonotone(points, indexAxis = 'x') {
2070 const valueAxis = getValueAxis(indexAxis);
2071 const pointsLen = points.length;
2072 const deltaK = Array(pointsLen).fill(0);
2073 const mK = Array(pointsLen);
2074 // Calculate slopes (deltaK) and initialize tangents (mK)
2075 let i, pointBefore, pointCurrent;
2076 let pointAfter = getPoint(points, 0);
2077 for(i = 0; i < pointsLen; ++i){
2078 pointBefore = pointCurrent;
2079 pointCurrent = pointAfter;
2080 pointAfter = getPoint(points, i + 1);
2081 if (!pointCurrent) {
2082 continue;
2083 }
2084 if (pointAfter) {
2085 const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis];
2086 // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
2087 deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0;
2088 }
2089 mK[i] = !pointBefore ? deltaK[i] : !pointAfter ? deltaK[i - 1] : sign(deltaK[i - 1]) !== sign(deltaK[i]) ? 0 : (deltaK[i - 1] + deltaK[i]) / 2;
2090 }
2091 monotoneAdjust(points, deltaK, mK);
2092 monotoneCompute(points, mK, indexAxis);
2093 }
2094 function capControlPoint(pt, min, max) {
2095 return Math.max(Math.min(pt, max), min);
2096 }
2097 function capBezierPoints(points, area) {
2098 let i, ilen, point, inArea, inAreaPrev;
2099 let inAreaNext = _isPointInArea(points[0], area);
2100 for(i = 0, ilen = points.length; i < ilen; ++i){
2101 inAreaPrev = inArea;
2102 inArea = inAreaNext;
2103 inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area);
2104 if (!inArea) {
2105 continue;
2106 }
2107 point = points[i];
2108 if (inAreaPrev) {
2109 point.cp1x = capControlPoint(point.cp1x, area.left, area.right);
2110 point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom);
2111 }
2112 if (inAreaNext) {
2113 point.cp2x = capControlPoint(point.cp2x, area.left, area.right);
2114 point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom);
2115 }
2116 }
2117 }
2118 /**
2119 * @private
2120 */ function _updateBezierControlPoints(points, options, area, loop, indexAxis) {
2121 let i, ilen, point, controlPoints;
2122 // Only consider points that are drawn in case the spanGaps option is used
2123 if (options.spanGaps) {
2124 points = points.filter((pt)=>!pt.skip);
2125 }
2126 if (options.cubicInterpolationMode === 'monotone') {
2127 splineCurveMonotone(points, indexAxis);
2128 } else {
2129 let prev = loop ? points[points.length - 1] : points[0];
2130 for(i = 0, ilen = points.length; i < ilen; ++i){
2131 point = points[i];
2132 controlPoints = splineCurve(prev, point, points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen], options.tension);
2133 point.cp1x = controlPoints.previous.x;
2134 point.cp1y = controlPoints.previous.y;
2135 point.cp2x = controlPoints.next.x;
2136 point.cp2y = controlPoints.next.y;
2137 prev = point;
2138 }
2139 }
2140 if (options.capBezierPoints) {
2141 capBezierPoints(points, area);
2142 }
2143 }
2144
2145 /**
2146 * @private
2147 */ function _isDomSupported() {
2148 return typeof window !== 'undefined' && typeof document !== 'undefined';
2149 }
2150 /**
2151 * @private
2152 */ function _getParentNode(domNode) {
2153 let parent = domNode.parentNode;
2154 if (parent && parent.toString() === '[object ShadowRoot]') {
2155 parent = parent.host;
2156 }
2157 return parent;
2158 }
2159 /**
2160 * convert max-width/max-height values that may be percentages into a number
2161 * @private
2162 */ function parseMaxStyle(styleValue, node, parentProperty) {
2163 let valueInPixels;
2164 if (typeof styleValue === 'string') {
2165 valueInPixels = parseInt(styleValue, 10);
2166 if (styleValue.indexOf('%') !== -1) {
2167 // percentage * size in dimension
2168 valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
2169 }
2170 } else {
2171 valueInPixels = styleValue;
2172 }
2173 return valueInPixels;
2174 }
2175 const getComputedStyle = (element)=>element.ownerDocument.defaultView.getComputedStyle(element, null);
2176 function getStyle(el, property) {
2177 return getComputedStyle(el).getPropertyValue(property);
2178 }
2179 const positions = [
2180 'top',
2181 'right',
2182 'bottom',
2183 'left'
2184 ];
2185 function getPositionedStyle(styles, style, suffix) {
2186 const result = {};
2187 suffix = suffix ? '-' + suffix : '';
2188 for(let i = 0; i < 4; i++){
2189 const pos = positions[i];
2190 result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0;
2191 }
2192 result.width = result.left + result.right;
2193 result.height = result.top + result.bottom;
2194 return result;
2195 }
2196 const useOffsetPos = (x, y, target)=>(x > 0 || y > 0) && (!target || !target.shadowRoot);
2197 /**
2198 * @param e
2199 * @param canvas
2200 * @returns Canvas position
2201 */ function getCanvasPosition(e, canvas) {
2202 const touches = e.touches;
2203 const source = touches && touches.length ? touches[0] : e;
2204 const { offsetX , offsetY } = source;
2205 let box = false;
2206 let x, y;
2207 if (useOffsetPos(offsetX, offsetY, e.target)) {
2208 x = offsetX;
2209 y = offsetY;
2210 } else {
2211 const rect = canvas.getBoundingClientRect();
2212 x = source.clientX - rect.left;
2213 y = source.clientY - rect.top;
2214 box = true;
2215 }
2216 return {
2217 x,
2218 y,
2219 box
2220 };
2221 }
2222 /**
2223 * Gets an event's x, y coordinates, relative to the chart area
2224 * @param event
2225 * @param chart
2226 * @returns x and y coordinates of the event
2227 */ function getRelativePosition(event, chart) {
2228 if ('native' in event) {
2229 return event;
2230 }
2231 const { canvas , currentDevicePixelRatio } = chart;
2232 const style = getComputedStyle(canvas);
2233 const borderBox = style.boxSizing === 'border-box';
2234 const paddings = getPositionedStyle(style, 'padding');
2235 const borders = getPositionedStyle(style, 'border', 'width');
2236 const { x , y , box } = getCanvasPosition(event, canvas);
2237 const xOffset = paddings.left + (box && borders.left);
2238 const yOffset = paddings.top + (box && borders.top);
2239 let { width , height } = chart;
2240 if (borderBox) {
2241 width -= paddings.width + borders.width;
2242 height -= paddings.height + borders.height;
2243 }
2244 return {
2245 x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio),
2246 y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio)
2247 };
2248 }
2249 function getContainerSize(canvas, width, height) {
2250 let maxWidth, maxHeight;
2251 if (width === undefined || height === undefined) {
2252 const container = canvas && _getParentNode(canvas);
2253 if (!container) {
2254 width = canvas.clientWidth;
2255 height = canvas.clientHeight;
2256 } else {
2257 const rect = container.getBoundingClientRect(); // this is the border box of the container
2258 const containerStyle = getComputedStyle(container);
2259 const containerBorder = getPositionedStyle(containerStyle, 'border', 'width');
2260 const containerPadding = getPositionedStyle(containerStyle, 'padding');
2261 width = rect.width - containerPadding.width - containerBorder.width;
2262 height = rect.height - containerPadding.height - containerBorder.height;
2263 maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth');
2264 maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight');
2265 }
2266 }
2267 return {
2268 width,
2269 height,
2270 maxWidth: maxWidth || INFINITY,
2271 maxHeight: maxHeight || INFINITY
2272 };
2273 }
2274 const round1 = (v)=>Math.round(v * 10) / 10;
2275 // eslint-disable-next-line complexity
2276 function getMaximumSize(canvas, bbWidth, bbHeight, aspectRatio) {
2277 const style = getComputedStyle(canvas);
2278 const margins = getPositionedStyle(style, 'margin');
2279 const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY;
2280 const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY;
2281 const containerSize = getContainerSize(canvas, bbWidth, bbHeight);
2282 let { width , height } = containerSize;
2283 if (style.boxSizing === 'content-box') {
2284 const borders = getPositionedStyle(style, 'border', 'width');
2285 const paddings = getPositionedStyle(style, 'padding');
2286 width -= paddings.width + borders.width;
2287 height -= paddings.height + borders.height;
2288 }
2289 width = Math.max(0, width - margins.width);
2290 height = Math.max(0, aspectRatio ? width / aspectRatio : height - margins.height);
2291 width = round1(Math.min(width, maxWidth, containerSize.maxWidth));
2292 height = round1(Math.min(height, maxHeight, containerSize.maxHeight));
2293 if (width && !height) {
2294 // https://github.com/chartjs/Chart.js/issues/4659
2295 // If the canvas has width, but no height, default to aspectRatio of 2 (canvas default)
2296 height = round1(width / 2);
2297 }
2298 const maintainHeight = bbWidth !== undefined || bbHeight !== undefined;
2299 if (maintainHeight && aspectRatio && containerSize.height && height > containerSize.height) {
2300 height = containerSize.height;
2301 width = round1(Math.floor(height * aspectRatio));
2302 }
2303 return {
2304 width,
2305 height
2306 };
2307 }
2308 /**
2309 * @param chart
2310 * @param forceRatio
2311 * @param forceStyle
2312 * @returns True if the canvas context size or transformation has changed.
2313 */ function retinaScale(chart, forceRatio, forceStyle) {
2314 const pixelRatio = forceRatio || 1;
2315 const deviceHeight = round1(chart.height * pixelRatio);
2316 const deviceWidth = round1(chart.width * pixelRatio);
2317 chart.height = round1(chart.height);
2318 chart.width = round1(chart.width);
2319 const canvas = chart.canvas;
2320 // If no style has been set on the canvas, the render size is used as display size,
2321 // making the chart visually bigger, so let's enforce it to the "correct" values.
2322 // See https://github.com/chartjs/Chart.js/issues/3575
2323 if (canvas.style && (forceStyle || !canvas.style.height && !canvas.style.width)) {
2324 canvas.style.height = `${chart.height}px`;
2325 canvas.style.width = `${chart.width}px`;
2326 }
2327 if (chart.currentDevicePixelRatio !== pixelRatio || canvas.height !== deviceHeight || canvas.width !== deviceWidth) {
2328 chart.currentDevicePixelRatio = pixelRatio;
2329 canvas.height = deviceHeight;
2330 canvas.width = deviceWidth;
2331 chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
2332 return true;
2333 }
2334 return false;
2335 }
2336 /**
2337 * Detects support for options object argument in addEventListener.
2338 * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
2339 * @private
2340 */ const supportsEventListenerOptions = function() {
2341 let passiveSupported = false;
2342 try {
2343 const options = {
2344 get passive () {
2345 passiveSupported = true;
2346 return false;
2347 }
2348 };
2349 if (_isDomSupported()) {
2350 window.addEventListener('test', null, options);
2351 window.removeEventListener('test', null, options);
2352 }
2353 } catch (e) {
2354 // continue regardless of error
2355 }
2356 return passiveSupported;
2357 }();
2358 /**
2359 * The "used" size is the final value of a dimension property after all calculations have
2360 * been performed. This method uses the computed style of `element` but returns undefined
2361 * if the computed style is not expressed in pixels. That can happen in some cases where
2362 * `element` has a size relative to its parent and this last one is not yet displayed,
2363 * for example because of `display: none` on a parent node.
2364 * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
2365 * @returns Size in pixels or undefined if unknown.
2366 */ function readUsedSize(element, property) {
2367 const value = getStyle(element, property);
2368 const matches = value && value.match(/^(\d+)(\.\d+)?px$/);
2369 return matches ? +matches[1] : undefined;
2370 }
2371
2372 /**
2373 * @private
2374 */ function _pointInLine(p1, p2, t, mode) {
2375 return {
2376 x: p1.x + t * (p2.x - p1.x),
2377 y: p1.y + t * (p2.y - p1.y)
2378 };
2379 }
2380 /**
2381 * @private
2382 */ function _steppedInterpolation(p1, p2, t, mode) {
2383 return {
2384 x: p1.x + t * (p2.x - p1.x),
2385 y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y : mode === 'after' ? t < 1 ? p1.y : p2.y : t > 0 ? p2.y : p1.y
2386 };
2387 }
2388 /**
2389 * @private
2390 */ function _bezierInterpolation(p1, p2, t, mode) {
2391 const cp1 = {
2392 x: p1.cp2x,
2393 y: p1.cp2y
2394 };
2395 const cp2 = {
2396 x: p2.cp1x,
2397 y: p2.cp1y
2398 };
2399 const a = _pointInLine(p1, cp1, t);
2400 const b = _pointInLine(cp1, cp2, t);
2401 const c = _pointInLine(cp2, p2, t);
2402 const d = _pointInLine(a, b, t);
2403 const e = _pointInLine(b, c, t);
2404 return _pointInLine(d, e, t);
2405 }
2406
2407 const getRightToLeftAdapter = function(rectX, width) {
2408 return {
2409 x (x) {
2410 return rectX + rectX + width - x;
2411 },
2412 setWidth (w) {
2413 width = w;
2414 },
2415 textAlign (align) {
2416 if (align === 'center') {
2417 return align;
2418 }
2419 return align === 'right' ? 'left' : 'right';
2420 },
2421 xPlus (x, value) {
2422 return x - value;
2423 },
2424 leftForLtr (x, itemWidth) {
2425 return x - itemWidth;
2426 }
2427 };
2428 };
2429 const getLeftToRightAdapter = function() {
2430 return {
2431 x (x) {
2432 return x;
2433 },
2434 setWidth (w) {},
2435 textAlign (align) {
2436 return align;
2437 },
2438 xPlus (x, value) {
2439 return x + value;
2440 },
2441 leftForLtr (x, _itemWidth) {
2442 return x;
2443 }
2444 };
2445 };
2446 function getRtlAdapter(rtl, rectX, width) {
2447 return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter();
2448 }
2449 function overrideTextDirection(ctx, direction) {
2450 let style, original;
2451 if (direction === 'ltr' || direction === 'rtl') {
2452 style = ctx.canvas.style;
2453 original = [
2454 style.getPropertyValue('direction'),
2455 style.getPropertyPriority('direction')
2456 ];
2457 style.setProperty('direction', direction, 'important');
2458 ctx.prevTextDirection = original;
2459 }
2460 }
2461 function restoreTextDirection(ctx, original) {
2462 if (original !== undefined) {
2463 delete ctx.prevTextDirection;
2464 ctx.canvas.style.setProperty('direction', original[0], original[1]);
2465 }
2466 }
2467
2468 function propertyFn(property) {
2469 if (property === 'angle') {
2470 return {
2471 between: _angleBetween,
2472 compare: _angleDiff,
2473 normalize: _normalizeAngle
2474 };
2475 }
2476 return {
2477 between: _isBetween,
2478 compare: (a, b)=>a - b,
2479 normalize: (x)=>x
2480 };
2481 }
2482 function normalizeSegment({ start , end , count , loop , style }) {
2483 return {
2484 start: start % count,
2485 end: end % count,
2486 loop: loop && (end - start + 1) % count === 0,
2487 style
2488 };
2489 }
2490 function getSegment(segment, points, bounds) {
2491 const { property , start: startBound , end: endBound } = bounds;
2492 const { between , normalize } = propertyFn(property);
2493 const count = points.length;
2494 let { start , end , loop } = segment;
2495 let i, ilen;
2496 if (loop) {
2497 start += count;
2498 end += count;
2499 for(i = 0, ilen = count; i < ilen; ++i){
2500 if (!between(normalize(points[start % count][property]), startBound, endBound)) {
2501 break;
2502 }
2503 start--;
2504 end--;
2505 }
2506 start %= count;
2507 end %= count;
2508 }
2509 if (end < start) {
2510 end += count;
2511 }
2512 return {
2513 start,
2514 end,
2515 loop,
2516 style: segment.style
2517 };
2518 }
2519 function _boundSegment(segment, points, bounds) {
2520 if (!bounds) {
2521 return [
2522 segment
2523 ];
2524 }
2525 const { property , start: startBound , end: endBound } = bounds;
2526 const count = points.length;
2527 const { compare , between , normalize } = propertyFn(property);
2528 const { start , end , loop , style } = getSegment(segment, points, bounds);
2529 const result = [];
2530 let inside = false;
2531 let subStart = null;
2532 let value, point, prevValue;
2533 const startIsBefore = ()=>between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0;
2534 const endIsBefore = ()=>compare(endBound, value) === 0 || between(endBound, prevValue, value);
2535 const shouldStart = ()=>inside || startIsBefore();
2536 const shouldStop = ()=>!inside || endIsBefore();
2537 for(let i = start, prev = start; i <= end; ++i){
2538 point = points[i % count];
2539 if (point.skip) {
2540 continue;
2541 }
2542 value = normalize(point[property]);
2543 if (value === prevValue) {
2544 continue;
2545 }
2546 inside = between(value, startBound, endBound);
2547 if (subStart === null && shouldStart()) {
2548 subStart = compare(value, startBound) === 0 ? i : prev;
2549 }
2550 if (subStart !== null && shouldStop()) {
2551 result.push(normalizeSegment({
2552 start: subStart,
2553 end: i,
2554 loop,
2555 count,
2556 style
2557 }));
2558 subStart = null;
2559 }
2560 prev = i;
2561 prevValue = value;
2562 }
2563 if (subStart !== null) {
2564 result.push(normalizeSegment({
2565 start: subStart,
2566 end,
2567 loop,
2568 count,
2569 style
2570 }));
2571 }
2572 return result;
2573 }
2574 function _boundSegments(line, bounds) {
2575 const result = [];
2576 const segments = line.segments;
2577 for(let i = 0; i < segments.length; i++){
2578 const sub = _boundSegment(segments[i], line.points, bounds);
2579 if (sub.length) {
2580 result.push(...sub);
2581 }
2582 }
2583 return result;
2584 }
2585 function findStartAndEnd(points, count, loop, spanGaps) {
2586 let start = 0;
2587 let end = count - 1;
2588 if (loop && !spanGaps) {
2589 while(start < count && !points[start].skip){
2590 start++;
2591 }
2592 }
2593 while(start < count && points[start].skip){
2594 start++;
2595 }
2596 start %= count;
2597 if (loop) {
2598 end += start;
2599 }
2600 while(end > start && points[end % count].skip){
2601 end--;
2602 }
2603 end %= count;
2604 return {
2605 start,
2606 end
2607 };
2608 }
2609 function solidSegments(points, start, max, loop) {
2610 const count = points.length;
2611 const result = [];
2612 let last = start;
2613 let prev = points[start];
2614 let end;
2615 for(end = start + 1; end <= max; ++end){
2616 const cur = points[end % count];
2617 if (cur.skip || cur.stop) {
2618 if (!prev.skip) {
2619 loop = false;
2620 result.push({
2621 start: start % count,
2622 end: (end - 1) % count,
2623 loop
2624 });
2625 start = last = cur.stop ? end : null;
2626 }
2627 } else {
2628 last = end;
2629 if (prev.skip) {
2630 start = end;
2631 }
2632 }
2633 prev = cur;
2634 }
2635 if (last !== null) {
2636 result.push({
2637 start: start % count,
2638 end: last % count,
2639 loop
2640 });
2641 }
2642 return result;
2643 }
2644 function _computeSegments(line, segmentOptions) {
2645 const points = line.points;
2646 const spanGaps = line.options.spanGaps;
2647 const count = points.length;
2648 if (!count) {
2649 return [];
2650 }
2651 const loop = !!line._loop;
2652 const { start , end } = findStartAndEnd(points, count, loop, spanGaps);
2653 if (spanGaps === true) {
2654 return splitByStyles(line, [
2655 {
2656 start,
2657 end,
2658 loop
2659 }
2660 ], points, segmentOptions);
2661 }
2662 const max = end < start ? end + count : end;
2663 const completeLoop = !!line._fullLoop && start === 0 && end === count - 1;
2664 return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions);
2665 }
2666 function splitByStyles(line, segments, points, segmentOptions) {
2667 if (!segmentOptions || !segmentOptions.setContext || !points) {
2668 return segments;
2669 }
2670 return doSplitByStyles(line, segments, points, segmentOptions);
2671 }
2672 function doSplitByStyles(line, segments, points, segmentOptions) {
2673 const chartContext = line._chart.getContext();
2674 const baseStyle = readStyle(line.options);
2675 const { _datasetIndex: datasetIndex , options: { spanGaps } } = line;
2676 const count = points.length;
2677 const result = [];
2678 let prevStyle = baseStyle;
2679 let start = segments[0].start;
2680 let i = start;
2681 function addStyle(s, e, l, st) {
2682 const dir = spanGaps ? -1 : 1;
2683 if (s === e) {
2684 return;
2685 }
2686 s += count;
2687 while(points[s % count].skip){
2688 s -= dir;
2689 }
2690 while(points[e % count].skip){
2691 e += dir;
2692 }
2693 if (s % count !== e % count) {
2694 result.push({
2695 start: s % count,
2696 end: e % count,
2697 loop: l,
2698 style: st
2699 });
2700 prevStyle = st;
2701 start = e % count;
2702 }
2703 }
2704 for (const segment of segments){
2705 start = spanGaps ? start : segment.start;
2706 let prev = points[start % count];
2707 let style;
2708 for(i = start + 1; i <= segment.end; i++){
2709 const pt = points[i % count];
2710 style = readStyle(segmentOptions.setContext(createContext(chartContext, {
2711 type: 'segment',
2712 p0: prev,
2713 p1: pt,
2714 p0DataIndex: (i - 1) % count,
2715 p1DataIndex: i % count,
2716 datasetIndex
2717 })));
2718 if (styleChanged(style, prevStyle)) {
2719 addStyle(start, i - 1, segment.loop, prevStyle);
2720 }
2721 prev = pt;
2722 prevStyle = style;
2723 }
2724 if (start < i - 1) {
2725 addStyle(start, i - 1, segment.loop, prevStyle);
2726 }
2727 }
2728 return result;
2729 }
2730 function readStyle(options) {
2731 return {
2732 backgroundColor: options.backgroundColor,
2733 borderCapStyle: options.borderCapStyle,
2734 borderDash: options.borderDash,
2735 borderDashOffset: options.borderDashOffset,
2736 borderJoinStyle: options.borderJoinStyle,
2737 borderWidth: options.borderWidth,
2738 borderColor: options.borderColor
2739 };
2740 }
2741 function styleChanged(style, prevStyle) {
2742 if (!prevStyle) {
2743 return false;
2744 }
2745 const cache = [];
2746 const replacer = function(key, value) {
2747 if (!isPatternOrGradient(value)) {
2748 return value;
2749 }
2750 if (!cache.includes(value)) {
2751 cache.push(value);
2752 }
2753 return cache.indexOf(value);
2754 };
2755 return JSON.stringify(style, replacer) !== JSON.stringify(prevStyle, replacer);
2756 }
2757
2758 function getSizeForArea(scale, chartArea, field) {
2759 return scale.options.clip ? scale[field] : chartArea[field];
2760 }
2761 function getDatasetArea(meta, chartArea) {
2762 const { xScale , yScale } = meta;
2763 if (xScale && yScale) {
2764 return {
2765 left: getSizeForArea(xScale, chartArea, 'left'),
2766 right: getSizeForArea(xScale, chartArea, 'right'),
2767 top: getSizeForArea(yScale, chartArea, 'top'),
2768 bottom: getSizeForArea(yScale, chartArea, 'bottom')
2769 };
2770 }
2771 return chartArea;
2772 }
2773 function getDatasetClipArea(chart, meta) {
2774 const clip = meta._clip;
2775 if (clip.disabled) {
2776 return false;
2777 }
2778 const area = getDatasetArea(meta, chart.chartArea);
2779 return {
2780 left: clip.left === false ? 0 : area.left - (clip.left === true ? 0 : clip.left),
2781 right: clip.right === false ? chart.width : area.right + (clip.right === true ? 0 : clip.right),
2782 top: clip.top === false ? 0 : area.top - (clip.top === true ? 0 : clip.top),
2783 bottom: clip.bottom === false ? chart.height : area.bottom + (clip.bottom === true ? 0 : clip.bottom)
2784 };
2785 }
2786
2787 export { unclipArea as $, _rlookupByKey as A, _lookupByKey as B, _isPointInArea as C, getAngleFromPoint as D, toPadding as E, each as F, getMaximumSize as G, HALF_PI as H, _getParentNode as I, readUsedSize as J, supportsEventListenerOptions as K, throttled as L, _isDomSupported as M, _factorize as N, finiteOrDefault as O, PI as P, callback as Q, _addGrace as R, _limitValue as S, TAU as T, toDegrees as U, _measureText as V, _int16Range as W, _alignPixel as X, clipArea as Y, renderText as Z, _arrayUnique as _, resolve as a, getStyle as a$, toFont as a0, _toLeftRightCenter as a1, _alignStartEnd as a2, overrides as a3, merge as a4, _capitalize as a5, descriptors as a6, isFunction as a7, _attachContext as a8, _createResolver as a9, getRtlAdapter as aA, overrideTextDirection as aB, _textX as aC, restoreTextDirection as aD, drawPointLegend as aE, distanceBetweenPoints as aF, noop as aG, _setMinAndMaxByKey as aH, niceNum as aI, almostWhole as aJ, almostEquals as aK, _decimalPlaces as aL, Ticks as aM, log10 as aN, _longestText as aO, _filterBetween as aP, _lookup as aQ, isPatternOrGradient as aR, getHoverColor as aS, clone as aT, _merger as aU, _mergerIf as aV, _deprecated as aW, _splitKey as aX, toFontString as aY, splineCurve as aZ, splineCurveMonotone as a_, _descriptors as aa, mergeIf as ab, uid as ac, debounce as ad, retinaScale as ae, clearCanvas as af, setsEqual as ag, getDatasetClipArea as ah, _elementsEqual as ai, _isClickEvent as aj, _isBetween as ak, _normalizeAngle as al, _readValueToProps as am, _updateBezierControlPoints as an, _computeSegments as ao, _boundSegments as ap, _steppedInterpolation as aq, _bezierInterpolation as ar, _pointInLine as as, _steppedLineTo as at, _bezierCurveTo as au, drawPoint as av, addRoundedRectPath as aw, toTRBL as ax, toTRBLCorners as ay, _boundSegment as az, isArray as b, fontString as b0, toLineHeight as b1, PITAU as b2, INFINITY as b3, RAD_PER_DEG as b4, QUARTER_PI as b5, TWO_THIRDS_PI as b6, _angleDiff as b7, color as c, defaults as d, effects as e, resolveObjectKey as f, isNumberFinite as g, defined as h, isObject as i, createContext as j, isNullOrUndef as k, listenArrayEvents as l, toPercentage as m, toDimension as n, formatNumber as o, _angleBetween as p, _getStartAndCountOfVisiblePoints as q, requestAnimFrame as r, sign as s, toRadians as t, unlistenArrayEvents as u, valueOrDefault as v, _scaleRangesChanged as w, isNumber as x, _parseObjectDataRadialScale as y, getRelativePosition as z };
2788 //# sourceMappingURL=helpers.dataset.js.map