Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

helpers.segment.js 93KB

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