diff --git a/.devcontainer/setup.sh b/.devcontainer/setup.sh index e07d9f46..423cd767 100755 --- a/.devcontainer/setup.sh +++ b/.devcontainer/setup.sh @@ -14,14 +14,14 @@ for dbsfile in "${dbsfiles[@]}"; do touch $dbsfile printf "{ \t\"dev\": { -\t\t\"url\": \"mongodb://localhost:27017/app\" +\t\t\"url\": \"mongodb://127.0.0.1:27017/app\" \t}, \t\"default\": { -\t\t\"url\": \"mongodb://localhost:27017/app\" +\t\t\"url\": \"mongodb://127.0.0.1:27017/app\" \t} }" >> $dbsfile fi done # Install node modules -yarn setup \ No newline at end of file +yarn setup diff --git a/README.md b/README.md index dd893b33..60016544 100644 --- a/README.md +++ b/README.md @@ -50,5 +50,5 @@ ESLint plugin, to assist development, which enforces a title being provided any ## Localization [![Weblate](https://hosted.weblate.org/widgets/scoutradioz/-/287x66-black.png)](https://hosted.weblate.org/engage/scoutradioz) -We're translating Scoutraioz so FIRST teams and their members, friends, and family from all over the globe can use it in their preferred languages. Translation contributions can be submitted using [Weblate](https://hosted.weblate.org/engage/scoutradioz). +We're translating Scoutradioz so FIRST teams and their members, friends, and family from all over the globe can use it in their preferred languages. Translation contributions can be submitted using [Weblate](https://hosted.weblate.org/engage/scoutradioz). diff --git a/primary/locales/en.json b/primary/locales/en.json index 5b5acaa4..fbf362fd 100644 --- a/primary/locales/en.json +++ b/primary/locales/en.json @@ -2,6 +2,16 @@ "index": { "fulltitle": "Scoutradioz: FRC Scouting as a Service", "welcome": "Welcome to Scoutradioz", + "browse": { + "link": "Or click here to browse data by event", + "title": "View data by event and org", + "tspsExplained": "'TSPS' is **relative** Total Scouting Performance Score (useful for friendly inter-org Scouting competitions!) - and 'Mdn.' is short for Median", + "pastEvents": "To see older data you may need to use the menu option under Info and Reports, 'Browse data from past events'", + "orgKeyAndNickname": "Org key - Nickname", + "matchScoutingEntries": "# Match scouting entries", + "avgErrorRate": "Mdn. error rate (and minimum)", + "tspsScore": "TSPS" + }, "choice": "Are you:", "viewer": { "choice": "Looking to view data", @@ -176,7 +186,7 @@ "scouting": { "match": "Match scouting", "pit": "Pit scouting", - "supermatch": "Super scout match {n}", + "supermatch": "Super scout this match", "superpit": "Super scout", "supermatchnotes": "Super scout match notes:", "supernotes": "Super scout notes for team {team}:", @@ -231,6 +241,8 @@ "pitScoutingPartner": "Partner's pit scouting assignments", "upcomingMatches": "Upcoming matches to be scouted", "matchNumber": "Match {number}", + "sfNumber": "Semifinal {number}", + "fNumber": "Final {number}", "matchResultMissedWarning": "WARNING: A match result may have been missed!", "matchResultMissedAdmin": "Click here, check FIRST match data and update any missing matches.", "matchResultMissedNotAdmin": "Ask a team admin to check FIRST match data and update any missing matches.", @@ -257,6 +269,7 @@ "chooseTeam": "[Choose a team]", "viewOr": "or", "allTeams": "All teams", + "otherTeams": "Other teams", "selectedTeam": "Selected team", "nextMatch": "Next match:", "nextMatchTeam": "Next match for team {team}:", @@ -270,6 +283,7 @@ "title": "Alliance selection", "intro": "Tap a team, then tap the empty slot [2] or [3] to move them up.\nAs teams are selected for alliances, they will gray out in the table below.", "preferred": "Before alliance selection, you and your team lead(s) can mark your preferred teams on this page.", + "tapForPopup": "Tap a team number to view that team's intel, including scouter notes.", "undo": "Undo", "allianceNumber": "Alliance {number}", "showData": "Show team data", @@ -284,7 +298,9 @@ "team": "Team", "rank": "FRC Rank", "numAlliances": "Number of alliances:", - "numRounds": "Number of rounds:" + "numRounds": "Number of rounds:", + "tooltipPicklist": "Each FRC team in an organization has their own picklist. Pick which team's picklist to view.", + "choosePicklist": "View picklist for..." }, "metrics": { "raw": "Raw data", @@ -339,6 +355,7 @@ "allTeams": "all teams", "allianceStats": "Alliance team statistics", "allTeamMetrics": "All team metrics", + "browsePastEvents": "Browse data from past events", "completedMatches": "Completed matches", "upcomingMatches": "Upcoming matches", "upcomingMatchesTeam": "Upcoming matches for {team}", @@ -433,9 +450,12 @@ "editMatchResults": "Edit match results", "editMatchSchedule": "Edit match schedule", "editTeams": "Edit team list", + "editRankings": "Adjust rankings", + "editRankingsInstructions": "Click on the minus/plus to change rankings; refresh page to resort", "eventData": "Event data: [[{event}]]", "getCurrentTeams": "Update list of teams", "invalidEventKey": "Invalid event key: '{eventKey}'. Click on an event in the list to set it automatically.", + "manual": "Manual data entry", "matches": "Matches (FIRST data)", "noEvent": "No event has been set", "recalcDerived": "Recalculate derived metrics", @@ -478,9 +498,21 @@ "permanentDeleteWarning": "By proceeding, you will be *permanently deleting* the data from *{number}* {type} scouting assignments from _{eventName}_. Are you sure you want to continue?", "scoutingGroups": "Scouting groups", "skipBreaks": "Check this box to generate assignments ignoring breaks in the schedule", + "scoutPlayoffs": "Check this box to generate assignments for playoff matches as well", "submitNewGroup": "Submit selected members as a new scouting group", "swapMatchAssignments": "Swap in/out match scouts", "swapPitAssignments": "Swap teams between pit scout groups" + }, + "config": { + "title": "Configure {org}", + "tooltipSubteamKey": "Write a unique identifier for each subteam. After you create a subteam, the label can change but the key should not change.", + "tooltipClassKey": "Write a unique identifier for each class. After you create a class, the label can change but the key should not change.", + "tooltipTeams": "Place the number of all FRC teams associated with this organization, separated by a comma. There can be multiple if your organization is a scouting collective, or if your team is pooling scouters with another FRC team.", + "invalidTeams": "Could not find a team with the number \"{number}\". Please enter a comma-separated list of FRC team numbers.", + "updatedSuccessfully": "Updated successfully.", + "updatedButFixSubteams": "Org config has updated, but one or more users will need to be updated due to subteam / class keys changing.\n- *Go through the list of users and make sure everyone has a subteam and class.\n- Click 'Update' for each user that has been updated.*", + "id": "ID", + "teams": "Team(s)" } }, "date": "Date", @@ -495,5 +527,6 @@ "add": "Add", "class": "Class", "subteam": "Subteam", - "update": "Update" + "update": "Update", + "year": "Year" } diff --git a/primary/locales/fr.json b/primary/locales/fr.json index 2297d30c..e0bfc24a 100644 --- a/primary/locales/fr.json +++ b/primary/locales/fr.json @@ -28,7 +28,10 @@ "first": "En savoir plus sur *FIRST* et FRC" }, "view": "Afficher", - "login": "Connexion" + "login": "Connexion", + "browse": { + "link": "Ou cliquez ici pour chercher des données par évènement" + } }, "hello": { "world": "Bonjour le monde!", diff --git a/primary/locales/zh-hans.json b/primary/locales/zh-hans.json index fe8d7aa9..6e6f77d2 100644 --- a/primary/locales/zh-hans.json +++ b/primary/locales/zh-hans.json @@ -27,7 +27,7 @@ "partner": "申请成为抢先体验合作伙伴", "first": "有关 *FIRST* 和 FRC 的更多信息" }, - "view": "看法", + "view": "浏览", "login": "登录" }, "hello": { @@ -40,7 +40,7 @@ "report": { "intro": "为了帮助我们修复此错误,请:", "screenshot": "截取此错误消息的屏幕截图,", - "url": "单击页面顶部的“共享”,复制此页面的完整 URL,", + "url": "单击页面顶部的“共享”,复制此页面的完整链接(URL),", "send": "将屏幕截图发布到我们的 Discord 服务器或我们的 {github}GitHub 页面{/github},包括相关信息,例如您点击了导致此错误的链接。" }, "stack": "堆栈跟踪:" @@ -58,7 +58,7 @@ "frc": "我们很自豪能成为 FIRST 机器人竞赛的参与者。" }, "nav": { - "home": "家", + "home": "主页", "reports": { "main": "信息和报告:[[{event}]]", "teams": "团队", @@ -66,7 +66,7 @@ "teamStats": "球队数据", "yearStats": "{year}的完整统计数据", "export": { - "main": "导出为 CSV", + "main": "导出数据", "match": "匹配球探数据:[[{event}]]", "pit": "场地侦察数据:[[{event}]]", "matchAll": "匹配球探数据:[[所有 {year}]]", @@ -78,17 +78,17 @@ "main": "管理:[[{org}]]", "members": { "main": "成员", - "list": "会员名单", - "passwords": "审核/重置会员密码" + "list": "成员名单", + "passwords": "审核/重置队员密码" }, "scouters": { - "main": "童子军", + "main": "侦查员", "event": "童子军:[[{event}]]", "audit": "侦察审核", - "present": "设置礼物" + "present": "设定参与此活动的人员" } }, - "admin": "行政", + "admin": "管理员", "user": { "main": "用户:[[{user}]]", "fallback": "用户", @@ -96,11 +96,12 @@ "logout": "登出", "switchorg": "改变组织" }, - "help": "需要帮忙?检查我们的维基!" + "help": "需要帮忙?检查我们的维基!", + "thanks": "特别鸣谢" } }, "home": { - "title": "家", + "title": "主页", "menu": "点击左上角的{menu}打开菜单", "tournamentInfo": "赛事信息", "teamInfo": "团队信息", @@ -110,7 +111,9 @@ "scoutingDashboard": "侦察仪表板", "management": "管理", "admin": "行政", - "specifyTeam": "您必须指定一个团队。" + "specifyTeam": "您必须指定一个团队。", + "formDemos": "表格预览", + "matchFormDemo": "赛事表格" }, "share": { "changeOrg": "您正在查看 {org}。\n要更改您希望查看的组织,请单击菜单中的 *Org: {org}* 并选择 *Change Organization*。" @@ -119,10 +122,10 @@ "loginOrg": "登录 {org}", "orgpassword": "机构密码:", "next": "下一个", - "name": "名称:", + "name": "姓名:", "personalpassword": "个人密码:", "createnew": "请创建一个新密码。", - "mustcreate": "您在您的组织中拥有提升的权限,因此您必须设置密码以确保其他人无法以您的身份登录。", + "mustcreate": "您在您的组织中拥有更高的的权限,因此您必须设置密码以确保其他人无法以您的身份登录。", "currentpassword": "当前密码:", "newpassword": "新密码:", "newpassword2": "确认:", @@ -131,8 +134,8 @@ "changepassword": "更改密码", "blankpassword": "如果您还没有自己的密码,请留空。", "selectorg": "请选择要登录的组织。", - "logoutbeforelogin": "请先注销,然后才能登录其他用户。", - "orgpasswordrequired": "请输入您所在组织的密码。要返回,请打开左上角的导航。", + "logoutbeforelogin": "在以其他用户的身份登录前请先登出当前账号", + "orgpasswordrequired": "请输入您所在组织的密码。若想返回,请打开左上角的导航键。", "orgpasswordincorrect": "组织 {org} 的密码不正确。", "resubmitlogin": "抱歉,请重新提交您的组织登录信息。", "selectuser": "请选择一个用户。", @@ -166,17 +169,17 @@ "small": "上传小#{n}", "preprocess": "预处理照片以节省移动数据?" }, - "matchHeading": "比赛#{match},球队#{team}", + "matchHeading": "比赛#{match},团队#{team}", "dynamicScrolling": "启用动态滚动", "submit": "提交", - "orgManagerActions": "组织经理行动:", + "orgManagerActions": "组织管理人行动:", "clearData": "清除数据", "clearDataConfirm": "如果您*确定*想要*永久删除*本场比赛的球探数据,请在下方输入您的密码。", "invalidMatchKey": "无效的匹配键集。", "invalidTeam": "团队 {team} 不存在。", "invalidTeamKey": "团队密钥未定义或无效。", "noDataSubmit": "没有数据发送到 {url}。", - "submitSuccess": "提交数据成功。", + "submitSuccess": "成功提交数据。", "deleteSuccess": "删除数据成功。如果您希望在屏幕上重新提交数据,您将不会被重定向离开该页面。" }, "notifications": { @@ -192,14 +195,14 @@ "dbSaveFailed": "已收到订阅,但我们无法将其保存到我们的数据库中。", "testPageTitle": "通知测试页面", "invalidKey": "没有匹配 & 匹配团队密钥", - "invalidMatch": "未找到匹配项", + "invalidMatch": "未找到比赛", "content": { "title": "{match} 即将开始", "body": "您被分配到 {alliance} 联盟的团队 {team}。", "ifFocused": "别忘了,{match} 即将开始!" }, "actions": { - "scout": "球探比赛" + "scout": "比赛侦察" } }, "dashboard": { @@ -414,5 +417,12 @@ "tryAgainLater": "请稍后再试。", "yes": "是的", "no": "不", - "matches": "火柴" + "matches": "火柴", + "name": "姓名", + "year": "年份", + "thankyou": { + "2023offseason": "2023非赛季", + "2023inseason": "2023赛季" + }, + "update": "更新" } diff --git a/primary/package.json b/primary/package.json index c5dc49fb..b5164beb 100644 --- a/primary/package.json +++ b/primary/package.json @@ -22,19 +22,15 @@ "---readme---": "Use the win-X scripts if you're using Windows. Always upload to test or QA first, then extensively test before promoting to prod.", "archive": "node ../scripts/uploadversion.js --archive --folder $npm_package_config_folder", "win-archive": "node ../scripts/uploadversion.js --archive --folder %npm_package_config_folder%", - "win-sync-test": "aws s3 sync %npm_package_config_publicFolderName% s3://%npm_package_config_publicS3BucketName%/test --acl public-read", - "win-sync-qa": "aws s3 sync %npm_package_config_publicFolderName% s3://%npm_package_config_publicS3BucketName%/qa --acl public-read", - "win-sync-prod": "aws s3 sync %npm_package_config_publicFolderName% s3://%npm_package_config_publicS3BucketName%/prod --acl public-read", - "win-sync-all": "yarn run win-sync-test && yarn run win-sync-qa && yarn run win-sync-prod", "win-upload-test": "node ../scripts/uploadversion.js --alias test --folder %npm_package_config_folder% --function-name %npm_package_config_functionFullName%", "win-upload-qa": "node ../scripts/uploadversion.js --alias qa --folder %npm_package_config_folder% --function-name %npm_package_config_functionFullName%", "win-promote-test-qa": "node ../scripts/promoteversion.js --promote-from test --promote-to qa --function-name %npm_package_config_functionFullName%", "win-promote-qa-prod": "node ../scripts/promoteversion.js --promote-from qa --promote-to prod --function-name %npm_package_config_functionFullName%", "win-rollback-prod": "node ../scripts/rollbackversion.js --function-name %npm_package_config_functionFullName%", - "sync-test": "aws s3 sync $npm_package_config_publicFolderName s3://$npm_package_config_publicS3BucketName/test --acl public-read", - "sync-qa": "aws s3 sync $npm_package_config_publicFolderName s3://$npm_package_config_publicS3BucketName/qa --acl public-read", - "sync-prod": "aws s3 sync $npm_package_config_publicFolderName s3://$npm_package_config_publicS3BucketName/prod --acl public-read", - "sync-all": "yarn run sync-test && yarn run sync-qa && yarn run sync-prod", + "sync-test": "bun ../scripts/s3sync.ts --tier test --folder public", + "sync-qa": "bun ../scripts/s3sync.ts --tier qa --folder public", + "sync-prod": "bun ../scripts/s3sync.ts --tier prod --folder public", + "sync-all": "bun run sync-test && yarn run sync-qa && yarn run sync-prod", "upload-test": "node ../scripts/uploadversion.js --alias test --folder $npm_package_config_folder --function-name $npm_package_config_functionFullName", "upload-qa": "node ../scripts/uploadversion.js --alias qa --folder $npm_package_config_folder --function-name $npm_package_config_functionFullName", "promote-test-qa": "node ../scripts/promoteversion.js --promote-from test --promote-to qa --function-name $npm_package_config_functionFullName", diff --git a/primary/public-src/less/main.less b/primary/public-src/less/main.less index d054d305..730dc748 100644 --- a/primary/public-src/less/main.less +++ b/primary/public-src/less/main.less @@ -108,10 +108,16 @@ color: white!important; background-color: @alliance-red!important; } +.alliance-red-faded { + background-color: fadeout(@alliance-red, 80%); +} .alliance-blue{ color: white!important; background-color: @alliance-blue!important; } +.alliance-blue-faded { + background-color: fadeout(@alliance-blue, 80%); +} .alliance-border-red{ border: 1px solid desaturate(lighten(@alliance-red, 20%), 50%); @@ -365,4 +371,46 @@ hr{ overflow-x: auto; //- CD 2022-11-11: made headerbar fixed to viewport, added margin-top to force content below the bar margin-top: @headerbar-height; +} + +#dialogElement { + width: calc(100% - 100px); + height: calc(100% - 100px); + padding: 0; + border: none; + + &::backdrop { + background-color: rgba(0,0,0,0.5); + } + + & #dialogContent { + position: relative; + width: 100%; + height: 100%; + } + + & #closePreviewBtn { + position: absolute; + top: 0; + right: 0; + width: 40px; + height: 40px; + display: grid; + place-items: center; + cursor: pointer; + } + + & #previewFrame { + width: 100%; + top: 40px; + position: relative; + height: calc(100% - 40px); + } +} + +@media(max-width: 600px) { + #dialogElement { + width: calc(100% - 48px); + height: calc(100% - 48px); + } } \ No newline at end of file diff --git a/primary/public-src/less/nav.less b/primary/public-src/less/nav.less index 8d00a92e..5a6ee86b 100644 --- a/primary/public-src/less/nav.less +++ b/primary/public-src/less/nav.less @@ -62,6 +62,20 @@ &.tier-dev{background-color: @header-tier-dev;} } +@headerTransition: top 0.15s ease-in-out; + +// Table header that's sticky needs to react to the header position at the top of the page +.stickyTableHeader { + transition: @headerTransition; + top: @headerbar-height; + position: sticky; + z-index: 100; +} +// NavMenu.ts adds/removes 'headerBarHidden' class to document.body +.headerBarHidden .stickyTableHeader { + top: 0px; +} + .header{ .header-color; & .tierlabel { @@ -79,7 +93,7 @@ width: 100%; z-index: 100; top: 0; - transition: top .15s ease-in-out; + transition: @headerTransition; // JL 2022-11-24: Adjusting navbar classes to use flexbox for positioning instead of absolute/inline-block/float tricks display: flex; diff --git a/primary/public-src/less/w3-additions.less b/primary/public-src/less/w3-additions.less index 39bb01c7..9ddc0f9d 100644 --- a/primary/public-src/less/w3-additions.less +++ b/primary/public-src/less/w3-additions.less @@ -94,7 +94,7 @@ a:hover.hover-link{text-decoration: underline;} /* Position the tooltip text */ position: absolute; - z-index: 1; + z-index: 10000; bottom: 125%; left: 50%; margin-left: -120px; diff --git a/primary/public-src/ts-bundled/Dialog.ts b/primary/public-src/ts-bundled/Dialog.ts new file mode 100644 index 00000000..476e426f --- /dev/null +++ b/primary/public-src/ts-bundled/Dialog.ts @@ -0,0 +1,51 @@ +/** + * Modal dialog element with a close button. + */ +class Dialog { + static getDialog() { + let dialogElement = $('dialog#dialogElement') as JQuery; + if (!(dialogElement[0] instanceof HTMLDialogElement)) { + dialogElement = $(document.createElement('dialog')) + .html( + `
+ + +
` + ) + .prop('id', 'dialogElement') + .appendTo(document.body); + dialogElement.find('button#closePreviewBtn').on('click', () => { + dialogElement[0].close(); + }); + } + return dialogElement; + } + + /** + * Open the modal dialog and populate its body with the HTML that you specify. + * @param html The HTML to populate the dialog with. Need to fetch it ahead of time with a `fetch` statement. + * + * @example + * + * fetch('/url'), { method: 'GET' }) + * .then(response => response.text()) + * then(data => Dialog.show(data)); + */ + static show(html: string) { + let dialog = this.getDialog(); + let iframe = dialog.find('iframe#previewFrame') as JQuery; + iframe[0].srcdoc = html; + dialog[0].showModal(); + } + + /** + * Open the modal dialog and populate it with the URL you specified. + * The web request will set the InModalDialog to true automatically, disabling the page heaader. + * @param url URL to open + */ + static showURL(url: string) { + fetch(url, {method: 'GET', headers: {'In-Modal-Dialog': 'true'}}) + .then(response => response.text()) + .then(html => Dialog.show(html)); + } +} diff --git a/primary/public-src/ts-bundled/FormSubmission.ts b/primary/public-src/ts-bundled/FormSubmission.ts index 2e0237f7..67871e71 100644 --- a/primary/public-src/ts-bundled/FormSubmission.ts +++ b/primary/public-src/ts-bundled/FormSubmission.ts @@ -29,7 +29,7 @@ class FormSubmission{ constructor(form: HTMLFormElement|JQuery, url: string, key: string, options?: {autoRetry: boolean}){ if (form && url && key) { - this.data = this._getFormData(form); + this.data = FormSubmission.getFormData(form); this.url = url; this.key = key; //Date.now().toString(); @@ -104,7 +104,10 @@ class FormSubmission{ localStorage.setItem(this.key, JSON.stringify(this.data)); } - _getFormData(form: HTMLFormElement|JQuery){ + /** + * Get a key-value object from any form element (useful outside of the FormSubmission class) + */ + static getFormData(form: HTMLFormElement|JQuery) { let unIndexedData = $(form).serializeArray(); let indexedData: Dictionary = {}; diff --git a/primary/public-src/ts-bundled/NavMenu.ts b/primary/public-src/ts-bundled/NavMenu.ts index efd58503..a6e862b4 100644 --- a/primary/public-src/ts-bundled/NavMenu.ts +++ b/primary/public-src/ts-bundled/NavMenu.ts @@ -19,9 +19,15 @@ $(() => { if (navMenu.opened || Math.abs(lastScrollTop - scrollTop) <= headerbarHeight) return; // scrolled down, hide - if (scrollTop > lastScrollTop) headerbar.addClass('hidden'); + if (scrollTop > lastScrollTop) { + headerbar.addClass('hidden'); + $(document.body).addClass('headerBarHidden'); + } // scrolled up, show - else headerbar.removeClass('hidden'); + else { + headerbar.removeClass('hidden'); + $(document.body).removeClass('headerBarHidden'); + } // lastScrollTop will only update in blocks of headerbarHeight since it's after the return lastScrollTop = scrollTop; diff --git a/primary/public-src/ts-bundled/scoutradioz.ts b/primary/public-src/ts-bundled/scoutradioz.ts index 2553152d..ab4272fa 100644 --- a/primary/public-src/ts-bundled/scoutradioz.ts +++ b/primary/public-src/ts-bundled/scoutradioz.ts @@ -41,7 +41,7 @@ declare function onResize(cb: () => void): void; window.onResize = function(cb: () => void) { resizeCallbacks.push(cb); - cb(); // Run the callback once + requestAnimationFrame(cb); // Run the callback once }; let ticking = false; diff --git a/primary/public-src/ts/bundle.d.ts b/primary/public-src/ts/bundle.d.ts index 764c9aa8..24fc226c 100644 --- a/primary/public-src/ts/bundle.d.ts +++ b/primary/public-src/ts/bundle.d.ts @@ -1,6 +1,29 @@ /// /// /// +/** + * Modal dialog element with a close button. + */ +declare class Dialog { + static getDialog(): JQuery; + /** + * Open the modal dialog and populate its body with the HTML that you specify. + * @param html The HTML to populate the dialog with. Need to fetch it ahead of time with a `fetch` statement. + * + * @example + * + * fetch('/url'), { method: 'GET' }) + * .then(response => response.text()) + * then(data => Dialog.show(data)); + */ + static show(html: string): void; + /** + * Open the modal dialog and populate it with the URL you specified. + * The web request will set the InModalDialog to true automatically, disabling the page heaader. + * @param url URL to open + */ + static showURL(url: string): void; +} declare class FormSubmission { /** * JL note 2022-04-03: Since all uses of FormSubmission follow the following response system: @@ -36,7 +59,10 @@ declare class FormSubmission { submit(cb: ObjectCallback): void; _getFromLocalStorage(): string | null; _addToLocalStorage(): void; - _getFormData(form: HTMLFormElement | JQuery): Dictionary; + /** + * Get a key-value object from any form element (useful outside of the FormSubmission class) + */ + static getFormData(form: HTMLFormElement | JQuery): Dictionary; } interface ObjectCallback { (error: JQueryXHR | Error | string | null, response?: SRResponse): void; diff --git a/primary/public-src/ts/script-allianceselection.ts b/primary/public-src/ts/script-allianceselection.ts index ccb3b468..369f990c 100644 --- a/primary/public-src/ts/script-allianceselection.ts +++ b/primary/public-src/ts/script-allianceselection.ts @@ -76,6 +76,13 @@ $(function(){ $('#numAlliances').on('change', (e) => doNumChange(e.target, 'numAlliances')); $('#numRounds').on('change', (e) => doNumChange(e.target, 'numRounds')); + + // When a team number is clicked, open a dialog with their super scout notes + $('[team-key]').on('click', function() { + let team_key = $(this).attr('team-key'); + Dialog.showURL(`/reports/teamintel?team_key=${team_key}`); + }); + }); function doNumChange(el: Element, param: string) { diff --git a/primary/public-src/ts/script-editform.ts b/primary/public-src/ts/script-editform.ts index 01749577..c6cf3e15 100644 --- a/primary/public-src/ts/script-editform.ts +++ b/primary/public-src/ts/script-editform.ts @@ -188,9 +188,6 @@ async function test() { let jsonString = await validate(); if (jsonString == null) return; - - const iframe = document.getElementById('previewFrame') as HTMLIFrameElement; - const dialog = document.getElementById('previewDialog') as HTMLDialogElement; fetch('/scouting/testform', { method: 'POST', @@ -205,8 +202,7 @@ async function test() { }) .then(response => response.text()) .then(data => { - iframe.srcdoc = data; - dialog.showModal(); + Dialog.show(data); }); } @@ -223,14 +219,8 @@ async function submit() { document.forms.submitForm.submit(); } -function closePreviewDialog() { - const dialog = document.getElementById('previewDialog') as HTMLDialogElement; - dialog.close(); -} - $(() => { $('#testBtn').on('click', test); $('#submitBtn').on('click', submit); $('#validateBtn').on('click', validate); - $('#closePreviewBtn').on('click', closePreviewDialog); }); diff --git a/primary/public-src/ts/script-matchscouting.ts b/primary/public-src/ts/script-matchscouting.ts index e915b05a..5de84eac 100644 --- a/primary/public-src/ts/script-matchscouting.ts +++ b/primary/public-src/ts/script-matchscouting.ts @@ -1,52 +1,62 @@ // These variables are created in the pug view declare let stickyBarEnabled: boolean; -declare let headerList: Array; +declare let groupedLayout: Array<{ + label: string; + items: import('scoutradioz-types').Layout[]; +}>; + +let sections = [] as Array<{ + elem: JQuery; + label: string; + rect: DOMRect; + top: number; + center: number; +}>; $(function () { - $('#toggleStickyToggle').addClass('animate'); - + $('#toggleSticky').on('change', () => { let enabled = $('#toggleSticky').prop('checked'); stickyBarEnabled = enabled; if (enabled) { // Show the sticky bar - $('#stickyBar').show().css('bottom', -60).animate({ - 'bottom': 0 - }, 200); + $('#stickyBar').show().css('bottom', -60).animate( + { + bottom: 0, + }, + 200 + ); // Save the fact that it's enabled localStorage.removeItem('disableStickyBar'); + requestAnimationFrame(handleScroll); } else { // Hide the sticky bar - $('#stickyBar').animate({ - 'bottom': -60 - }, 200); + $('#stickyBar').animate( + { + bottom: -60, + }, + 200 + ); // Clear the "disabled-form" class from all elements - $('.disabled-form').removeClass('disabled-form').removeAttr('disabled') - .find('input, button').removeAttr('disabled'); // and its children which are inputs + $('.disabled-form') + .removeClass('disabled-form') + .removeAttr('disabled') + .find('input, button') + .removeAttr('disabled'); // and its children which are inputs // Save the fact that it's disabled localStorage.setItem('disableStickyBar', '1'); + currentSectionIdx = -1; } }); - - //- Get a list of all the header elements, to use for scrolling - let headerElements: Array = []; - for (let label of headerList) { - let thisHeader = $(`#${label}`); - if (thisHeader[0]) headerElements.push(thisHeader[0]); - } - + const stickyBarTitle = $('#stickyBarTitle'); - const stickyBarLeft = $('#stickyBarLeft'); + const stickyBarLeft = $('#stickyBarLeft'); const stickyBarRight = $('#stickyBarRight'); - - const matchform = $('#matchform'); - - let currentHeaderID = ''; - - handleScroll(); - + + let currentSectionIdx = -1; + let ticking = false; $(window).on('scroll', () => { if (!ticking) { @@ -60,145 +70,96 @@ $(function () { ticking = true; } }); - - + + function lerp(t: number, a: number, b: number) { + return (1 - t) * a + t * b; + } + function handleScroll() { - if (!stickyBarEnabled) return; - - const centerX = window.innerWidth / 2; - const centerY = window.innerHeight * 2/3; - - let centerDiv; - // sometimes gap between elements causes the elementfrompoint to be a parent element - for (let i = 0; i < 10; i++) { - centerDiv = document.elementFromPoint(centerX, centerY - i * 4); - if (centerDiv && matchform.has(centerDiv).length) { - break; - } - } - if (!centerDiv) { - console.error('Could not find a center div!'); - return; + if (!stickyBarEnabled) return console.log('not enabled'); + if (sections.length === 0) return console.error('Sections array is empty!'); + + // Create a "target" that is usually in the center of the screen but semi-smoothly transitions + // from the top of the screen at scroll 0 to the middle, and then from the middle to the bottom of + // the screen, to prevent any sections from being missed while scrolling + let scrollY = window.scrollY; + let halfScreenHeight = window.innerHeight / 2; + let centerOfScreen = window.scrollY + halfScreenHeight; + let bufferZone = window.innerHeight / 3; + let bufferZoneBelowBottom = document.body.offsetHeight - window.innerHeight - bufferZone; + + let targetY = centerOfScreen; + if (scrollY < bufferZone) { + let t = scrollY / bufferZone; + targetY = lerp(Math.sqrt(t), 0, centerOfScreen); } - - // Find the "root" form element so we can iterate across siblings - let attemptsRemaining = 20; // to avoid infinite loop, just in case - while (centerDiv.parentElement && !matchform.is(centerDiv.parentElement) && attemptsRemaining > 0) { - centerDiv = centerDiv.parentElement; - attemptsRemaining--; + if (scrollY > bufferZoneBelowBottom) { + let t = (scrollY - bufferZoneBelowBottom) / bufferZone; + targetY = lerp(Math.pow(t, 2), centerOfScreen, document.body.offsetHeight); } - - // Loop backwards until we find a header element - let thisElement = centerDiv; - attemptsRemaining = 50; // if someone has a group of form elements that's 50 long, they've got problems. - let headerInMiddle: HTMLElement|null = null; - while (thisElement instanceof HTMLElement && !headerInMiddle && attemptsRemaining > 0) { - // test if this element is a header - if (headerElements.includes(thisElement)) { - headerInMiddle = thisElement; // we found our winner - break; + + // Find the section whose center is closest to the calculated target + let closestSection = 0; + let closestDistance = 9999999; + for (let i = 0; i < sections.length; i++) { + let distance = Math.abs(targetY - sections[i].center); + if (distance < closestDistance) { + closestSection = i; + closestDistance = distance; } - thisElement = thisElement.previousElementSibling as HTMLElement; // proceed - attemptsRemaining--; - } - - if (!headerInMiddle) { - console.log(attemptsRemaining); - console.error('Could not find a header in the middle!'); - return; } - let header = headerInMiddle; - - // Special case: Scrolled all the way down in the page, just set the very last header to active - let diff = Math.abs(scrollY + innerHeight - document.body.offsetHeight); - if (diff < 10) { - console.log('Within 10 px of bottom of screen; setting last header to active'); - header = headerElements[headerElements.length - 1]; - } - - if (currentHeaderID !== header.id) { - setStickyBar(header.id, header.innerText); - } - - // Old code backup: Simply find the first visible header element - // for (let header of headerElements) { - // let isVisible = checkVisible(header); - // if (isVisible) { - // //- Only update the sticky bar when it needs to change - // if (currentHeaderID !== header.id) { - // setStickyBar(header.id, header.innerText); - // } - // break; - // } - // } + setSection(closestSection); } - - /** - * Set the sticky bar text. - * @param id string - * @param text string - */ - function setStickyBar(id: string, text: string) { + + function setSection(idx: number) { + assert(sections[idx], new RangeError()); + if (currentSectionIdx === idx) return; // avoid unnecessary recalculations let st = performance.now(); - stickyBarTitle.text(text); - currentHeaderID = id; - - //- Now, update the visibility of the elements under the OTHER headers - for (let i = 0; i < headerElements.length; i++) { - let header = headerElements[i]; - let nextHeader = headerElements[i + 1]; - let thisSibling = header.nextElementSibling; - - if (header.id === id) { - header.classList.remove('disabled-form'); - while(thisSibling && thisSibling !== nextHeader) { - thisSibling.classList.remove('disabled-form'); - // Attempt to un-disable an input element within the sibling; also un-disable the sibling itself - let thisSibInputs = thisSibling.querySelectorAll('input, button'); - // if (thisSiblingInput) thisSiblingInput.disabled = false; - if (thisSibInputs) thisSibInputs.forEach(itm => itm.disabled = false); - else thisSibling.disabled = false; - thisSibling = thisSibling.nextElementSibling; - } + currentSectionIdx = idx; + + // Update the visibility of the elements + for (let i = 0; i < sections.length; i++) { + if (idx === i) { + sections[i].elem.removeClass('disabled-form'); + sections[i].elem.find('input, button').removeAttr('disabled'); } else { - header.classList.add('disabled-form'); - while(thisSibling && thisSibling !== nextHeader) { - thisSibling.classList.add('disabled-form'); - // Attempt to disable an input element within the sibling; also disable the sibling itself - let thisSibInputs = thisSibling.querySelectorAll('input, button'); - if (thisSibInputs) thisSibInputs.forEach(itm => itm.disabled = true); - else thisSibling.disabled = true; - thisSibling = thisSibling.nextElementSibling; - } + sections[i].elem.addClass('disabled-form'); + sections[i].elem.find('input, button').attr('disabled', ''); } } + stickyBarTitle.text(sections[idx].label); console.log(performance.now() - st); } - + stickyBarLeft.on('click', () => { - let currentHeader = document.getElementById(currentHeaderID); - if (!currentHeader) throw new Error(`Header ${currentHeaderID} not found`); - - let index = headerElements.indexOf(currentHeader); - let prevHeader = headerElements[index - 1]; - if (prevHeader) { - window.scrollToId('dynamicscroll_' + prevHeader.id); - } + if (currentSectionIdx < 0) throw new RangeError('Current section not set!'); + let sectionToScrollTo = currentSectionIdx - 1; + if (sectionToScrollTo < 0) sectionToScrollTo = 0; // in this case, just scroll to the top of the first section + let section = sections[sectionToScrollTo]; + window.scrollTo({ + // Scroll such that the center of the section is in the middle of the screen. + // JL note: This seems to work with the match form I tested, but it might still not be perfect + // depending on the size of the sections in the form. But it's at least a TON better than + // the previous implementation. + top: section.center - window.innerHeight/2, + behavior: 'smooth' + }); }); - + stickyBarRight.on('click', () => { - let currentHeader = document.getElementById(currentHeaderID); - if (!currentHeader) throw new Error(`Header ${currentHeaderID} not found`); - - let index = headerElements.indexOf(currentHeader); - let nextHeader = headerElements[index + 1]; - if (nextHeader) { - window.scrollToId('dynamicscroll_' + nextHeader.id); - } + if (currentSectionIdx < 0) throw new RangeError('Current section not set!'); + let sectionToScrollTo = currentSectionIdx + 1; + if (sectionToScrollTo >= sections.length) sectionToScrollTo = sections.length - 1; // in this case, just scroll to the top of the first section + let section = sections[sectionToScrollTo]; + window.scrollTo({ + // JL note: see above. + top: section.center - window.innerHeight/2, + behavior: 'smooth' + }); }); - + //- Just some visual flourish for the icons stickyBarLeft.on('mousedown', fancyMouseDown); stickyBarLeft.on('touchstart', fancyMouseDown); @@ -208,7 +169,7 @@ $(function () { stickyBarLeft.on('touchend', fancyMouseUp); stickyBarRight.on('mouseup', fancyMouseUp); stickyBarRight.on('touchend', fancyMouseUp); - + function fancyMouseDown(this: HTMLElement) { $(this).css({ top: 2, @@ -221,57 +182,82 @@ $(function () { left: '', }); } - - //- Credit: https://stackoverflow.com/questions/5353934/check-if-element-is-visible-on-screen - function checkVisible(elem: HTMLElement) { - let rect = elem.getBoundingClientRect(); - let viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight); - return !(rect.bottom < 0 || rect.top - viewHeight >= 0); - } - - window.onResize(() => { + + function handleResize() { + // Sections calculation needs to be done even if sticky bar is disabled + let bodyRect = document.body.getBoundingClientRect(); // need to subtract bodyRect.top to get absolute position + sections = []; + for (let i = 0; i < groupedLayout.length; i++) { + let section = $(`#group_${i}`); + let rect = section[0].getBoundingClientRect(); + let top = rect.top - bodyRect.top; + let center = top + rect.height / 2; + let label = groupedLayout[i].label; + // the group 0 section may contain no children, if so, ignore it + if (section.children().length > 0) { + sections.push({ + elem: section, + label, + rect, + top, + center, + }); + } + } + // but we can skip the following code if sticky bar is disabled if (!stickyBarEnabled) return; - + handleScroll(); + // - The text is centered at a fixed size, but we want to make sure the text is visible even on small screens. let triLeft = $('#stickyBarLeft')[0]; let text = $('#stickyBarTitle')[0]; const OFFSET = -8; // the buttons have a lot of padding; allowing a bit of overlap - + text.style.fontSize = '1em'; let triRect = triLeft.getBoundingClientRect(); //- This just loops from 1 to 10 and iteratively reduces the font size until it fits without overlapping the triangle icons. - let iterations = 0, textSize = 1; - while (iterations < 10 && text.getBoundingClientRect().left < triRect.right + OFFSET) { + let iterations = 0, + textSize = 1; + while ( + iterations < 10 && + text.getBoundingClientRect().left < triRect.right + OFFSET + ) { textSize -= 0.05; text.style.fontSize = textSize + 'em'; iterations++; } - }); + } + + window.onResize(handleResize); + // when team image loads, recalculate page size too + $('img').on('load', handleResize); }); -$(function(){ - - $('#submit').on('click', function(){ - +$(function () { + $('#submit').on('click', function () { // JL: Disabled inputs are only for visual assistance in dynamic scrolling, but they might be ignored in the form submission if they remain disabled - $('input[disabled]').removeAttr('disabled'); - + $('input[disabled]').removeAttr('disabled'); + let matchForm = $('form[name=matchform]'); - - let matchSubmission = new FormSubmission(matchForm, '/scouting/match/submit', 'matchScouting'); - + + let matchSubmission = new FormSubmission( + matchForm, + '/scouting/match/submit', + 'matchScouting' + ); + matchSubmission.submit((err, response) => { if (err || !response || !response.message) { NotificationCard.error('An error occurred. Please retry.'); } - else{ + else { let message = response.message; - NotificationCard.show(message, {darken: true, type: 'good', ttl: 0}); - - // 2022-03-24 JL: Send assigned scouters back to dashboard, send unassigned scouters back to dashboard/matches - let newHref = (response.assigned) ? '/dashboard' : '/dashboard/matches'; - + NotificationCard.show(message, { darken: true, type: 'good', ttl: 0 }); + + // 2022-03-24 JL: Send assigned scouters back to dashboard, send unassigned scouters back to dashboard/matches + let newHref = response.assigned ? '/dashboard' : '/dashboard/matches'; + setTimeout(() => { window.onbeforeunload = null; window.location.href = newHref; @@ -279,21 +265,17 @@ $(function(){ } }); }); - + // 2024-01-26 JL: Made the editform preview appear in a dialog window; in this case, location.href === 'about:srcdoc' // and we don't want onbeforeunload to fire in the sub window when changes don't matter if (this.location.href !== 'about:srcdoc') { - window.onbeforeunload = function() { + window.onbeforeunload = function () { return 'Leaving this page will lose match scouting data.'; }; } }); // Again because JQuery typing is dumb -interface Element { - disabled: boolean; -} - interface SRResponse { assigned: boolean; -} \ No newline at end of file +} diff --git a/primary/public/images/april-fools-thumbnail.png b/primary/public/images/april-fools-thumbnail.png new file mode 100644 index 00000000..990bb48c Binary files /dev/null and b/primary/public/images/april-fools-thumbnail.png differ diff --git a/primary/public/lib/chart.js b/primary/public/lib/chart.js deleted file mode 100644 index 58990616..00000000 --- a/primary/public/lib/chart.js +++ /dev/null @@ -1,13269 +0,0 @@ -/*! - * Chart.js v3.7.1 - * https://www.chartjs.org - * (c) 2022 Chart.js Contributors - * Released under the MIT License - */ -(function (global, factory) { -typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : -typeof define === 'function' && define.amd ? define(factory) : -(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Chart = factory()); -})(this, (function () { 'use strict'; - -function fontString(pixelSize, fontStyle, fontFamily) { - return fontStyle + ' ' + pixelSize + 'px ' + fontFamily; -} -const requestAnimFrame = (function() { - if (typeof window === 'undefined') { - return function(callback) { - return callback(); - }; - } - return window.requestAnimationFrame; -}()); -function throttled(fn, thisArg, updateFn) { - const updateArgs = updateFn || ((args) => Array.prototype.slice.call(args)); - let ticking = false; - let args = []; - return function(...rest) { - args = updateArgs(rest); - if (!ticking) { - ticking = true; - requestAnimFrame.call(window, () => { - ticking = false; - fn.apply(thisArg, args); - }); - } - }; -} -function debounce(fn, delay) { - let timeout; - return function(...args) { - if (delay) { - clearTimeout(timeout); - timeout = setTimeout(fn, delay, args); - } else { - fn.apply(this, args); - } - return delay; - }; -} -const _toLeftRightCenter = (align) => align === 'start' ? 'left' : align === 'end' ? 'right' : 'center'; -const _alignStartEnd = (align, start, end) => align === 'start' ? start : align === 'end' ? end : (start + end) / 2; -const _textX = (align, left, right, rtl) => { - const check = rtl ? 'left' : 'right'; - return align === check ? right : align === 'center' ? (left + right) / 2 : left; -}; - -class Animator { - constructor() { - this._request = null; - this._charts = new Map(); - this._running = false; - this._lastDate = undefined; - } - _notify(chart, anims, date, type) { - const callbacks = anims.listeners[type]; - const numSteps = anims.duration; - callbacks.forEach(fn => fn({ - chart, - initial: anims.initial, - numSteps, - currentStep: Math.min(date - anims.start, numSteps) - })); - } - _refresh() { - if (this._request) { - return; - } - this._running = true; - this._request = requestAnimFrame.call(window, () => { - this._update(); - this._request = null; - if (this._running) { - this._refresh(); - } - }); - } - _update(date = Date.now()) { - let remaining = 0; - this._charts.forEach((anims, chart) => { - if (!anims.running || !anims.items.length) { - return; - } - const items = anims.items; - let i = items.length - 1; - let draw = false; - let item; - for (; i >= 0; --i) { - item = items[i]; - if (item._active) { - if (item._total > anims.duration) { - anims.duration = item._total; - } - item.tick(date); - draw = true; - } else { - items[i] = items[items.length - 1]; - items.pop(); - } - } - if (draw) { - chart.draw(); - this._notify(chart, anims, date, 'progress'); - } - if (!items.length) { - anims.running = false; - this._notify(chart, anims, date, 'complete'); - anims.initial = false; - } - remaining += items.length; - }); - this._lastDate = date; - if (remaining === 0) { - this._running = false; - } - } - _getAnims(chart) { - const charts = this._charts; - let anims = charts.get(chart); - if (!anims) { - anims = { - running: false, - initial: true, - items: [], - listeners: { - complete: [], - progress: [] - } - }; - charts.set(chart, anims); - } - return anims; - } - listen(chart, event, cb) { - this._getAnims(chart).listeners[event].push(cb); - } - add(chart, items) { - if (!items || !items.length) { - return; - } - this._getAnims(chart).items.push(...items); - } - has(chart) { - return this._getAnims(chart).items.length > 0; - } - start(chart) { - const anims = this._charts.get(chart); - if (!anims) { - return; - } - anims.running = true; - anims.start = Date.now(); - anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0); - this._refresh(); - } - running(chart) { - if (!this._running) { - return false; - } - const anims = this._charts.get(chart); - if (!anims || !anims.running || !anims.items.length) { - return false; - } - return true; - } - stop(chart) { - const anims = this._charts.get(chart); - if (!anims || !anims.items.length) { - return; - } - const items = anims.items; - let i = items.length - 1; - for (; i >= 0; --i) { - items[i].cancel(); - } - anims.items = []; - this._notify(chart, anims, Date.now(), 'complete'); - } - remove(chart) { - return this._charts.delete(chart); - } -} -var animator = new Animator(); - -/*! - * @kurkle/color v0.1.9 - * https://github.com/kurkle/color#readme - * (c) 2020 Jukka Kurkela - * Released under the MIT License - */ -const map$1 = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 10, B: 11, C: 12, D: 13, E: 14, F: 15, a: 10, b: 11, c: 12, d: 13, e: 14, f: 15}; -const hex = '0123456789ABCDEF'; -const h1 = (b) => hex[b & 0xF]; -const h2 = (b) => hex[(b & 0xF0) >> 4] + hex[b & 0xF]; -const eq = (b) => (((b & 0xF0) >> 4) === (b & 0xF)); -function isShort(v) { - return eq(v.r) && eq(v.g) && eq(v.b) && eq(v.a); -} -function hexParse(str) { - var len = str.length; - var ret; - if (str[0] === '#') { - if (len === 4 || len === 5) { - ret = { - r: 255 & map$1[str[1]] * 17, - g: 255 & map$1[str[2]] * 17, - b: 255 & map$1[str[3]] * 17, - a: len === 5 ? map$1[str[4]] * 17 : 255 - }; - } else if (len === 7 || len === 9) { - ret = { - r: map$1[str[1]] << 4 | map$1[str[2]], - g: map$1[str[3]] << 4 | map$1[str[4]], - b: map$1[str[5]] << 4 | map$1[str[6]], - a: len === 9 ? (map$1[str[7]] << 4 | map$1[str[8]]) : 255 - }; - } - } - return ret; -} -function hexString(v) { - var f = isShort(v) ? h1 : h2; - return v - ? '#' + f(v.r) + f(v.g) + f(v.b) + (v.a < 255 ? f(v.a) : '') - : v; -} -function round(v) { - return v + 0.5 | 0; -} -const lim = (v, l, h) => Math.max(Math.min(v, h), l); -function p2b(v) { - return lim(round(v * 2.55), 0, 255); -} -function n2b(v) { - return lim(round(v * 255), 0, 255); -} -function b2n(v) { - return lim(round(v / 2.55) / 100, 0, 1); -} -function n2p(v) { - return lim(round(v * 100), 0, 100); -} -const RGB_RE = /^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/; -function rgbParse(str) { - const m = RGB_RE.exec(str); - let a = 255; - let r, g, b; - if (!m) { - return; - } - if (m[7] !== r) { - const v = +m[7]; - a = 255 & (m[8] ? p2b(v) : v * 255); - } - r = +m[1]; - g = +m[3]; - b = +m[5]; - r = 255 & (m[2] ? p2b(r) : r); - g = 255 & (m[4] ? p2b(g) : g); - b = 255 & (m[6] ? p2b(b) : b); - return { - r: r, - g: g, - b: b, - a: a - }; -} -function rgbString(v) { - return v && ( - v.a < 255 - ? `rgba(${v.r}, ${v.g}, ${v.b}, ${b2n(v.a)})` - : `rgb(${v.r}, ${v.g}, ${v.b})` - ); -} -const HUE_RE = /^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/; -function hsl2rgbn(h, s, l) { - const a = s * Math.min(l, 1 - l); - const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1); - return [f(0), f(8), f(4)]; -} -function hsv2rgbn(h, s, v) { - const f = (n, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0); - return [f(5), f(3), f(1)]; -} -function hwb2rgbn(h, w, b) { - const rgb = hsl2rgbn(h, 1, 0.5); - let i; - if (w + b > 1) { - i = 1 / (w + b); - w *= i; - b *= i; - } - for (i = 0; i < 3; i++) { - rgb[i] *= 1 - w - b; - rgb[i] += w; - } - return rgb; -} -function rgb2hsl(v) { - const range = 255; - const r = v.r / range; - const g = v.g / range; - const b = v.b / range; - const max = Math.max(r, g, b); - const min = Math.min(r, g, b); - const l = (max + min) / 2; - let h, s, d; - if (max !== min) { - d = max - min; - s = l > 0.5 ? d / (2 - max - min) : d / (max + min); - h = max === r - ? ((g - b) / d) + (g < b ? 6 : 0) - : max === g - ? (b - r) / d + 2 - : (r - g) / d + 4; - h = h * 60 + 0.5; - } - return [h | 0, s || 0, l]; -} -function calln(f, a, b, c) { - return ( - Array.isArray(a) - ? f(a[0], a[1], a[2]) - : f(a, b, c) - ).map(n2b); -} -function hsl2rgb(h, s, l) { - return calln(hsl2rgbn, h, s, l); -} -function hwb2rgb(h, w, b) { - return calln(hwb2rgbn, h, w, b); -} -function hsv2rgb(h, s, v) { - return calln(hsv2rgbn, h, s, v); -} -function hue(h) { - return (h % 360 + 360) % 360; -} -function hueParse(str) { - const m = HUE_RE.exec(str); - let a = 255; - let v; - if (!m) { - return; - } - if (m[5] !== v) { - a = m[6] ? p2b(+m[5]) : n2b(+m[5]); - } - const h = hue(+m[2]); - const p1 = +m[3] / 100; - const p2 = +m[4] / 100; - if (m[1] === 'hwb') { - v = hwb2rgb(h, p1, p2); - } else if (m[1] === 'hsv') { - v = hsv2rgb(h, p1, p2); - } else { - v = hsl2rgb(h, p1, p2); - } - return { - r: v[0], - g: v[1], - b: v[2], - a: a - }; -} -function rotate(v, deg) { - var h = rgb2hsl(v); - h[0] = hue(h[0] + deg); - h = hsl2rgb(h); - v.r = h[0]; - v.g = h[1]; - v.b = h[2]; -} -function hslString(v) { - if (!v) { - return; - } - const a = rgb2hsl(v); - const h = a[0]; - const s = n2p(a[1]); - const l = n2p(a[2]); - return v.a < 255 - ? `hsla(${h}, ${s}%, ${l}%, ${b2n(v.a)})` - : `hsl(${h}, ${s}%, ${l}%)`; -} -const map$1$1 = { - x: 'dark', - Z: 'light', - Y: 're', - X: 'blu', - W: 'gr', - V: 'medium', - U: 'slate', - A: 'ee', - T: 'ol', - S: 'or', - B: 'ra', - C: 'lateg', - D: 'ights', - R: 'in', - Q: 'turquois', - E: 'hi', - P: 'ro', - O: 'al', - N: 'le', - M: 'de', - L: 'yello', - F: 'en', - K: 'ch', - G: 'arks', - H: 'ea', - I: 'ightg', - J: 'wh' -}; -const names = { - OiceXe: 'f0f8ff', - antiquewEte: 'faebd7', - aqua: 'ffff', - aquamarRe: '7fffd4', - azuY: 'f0ffff', - beige: 'f5f5dc', - bisque: 'ffe4c4', - black: '0', - blanKedOmond: 'ffebcd', - Xe: 'ff', - XeviTet: '8a2be2', - bPwn: 'a52a2a', - burlywood: 'deb887', - caMtXe: '5f9ea0', - KartYuse: '7fff00', - KocTate: 'd2691e', - cSO: 'ff7f50', - cSnflowerXe: '6495ed', - cSnsilk: 'fff8dc', - crimson: 'dc143c', - cyan: 'ffff', - xXe: '8b', - xcyan: '8b8b', - xgTMnPd: 'b8860b', - xWay: 'a9a9a9', - xgYF: '6400', - xgYy: 'a9a9a9', - xkhaki: 'bdb76b', - xmagFta: '8b008b', - xTivegYF: '556b2f', - xSange: 'ff8c00', - xScEd: '9932cc', - xYd: '8b0000', - xsOmon: 'e9967a', - xsHgYF: '8fbc8f', - xUXe: '483d8b', - xUWay: '2f4f4f', - xUgYy: '2f4f4f', - xQe: 'ced1', - xviTet: '9400d3', - dAppRk: 'ff1493', - dApskyXe: 'bfff', - dimWay: '696969', - dimgYy: '696969', - dodgerXe: '1e90ff', - fiYbrick: 'b22222', - flSOwEte: 'fffaf0', - foYstWAn: '228b22', - fuKsia: 'ff00ff', - gaRsbSo: 'dcdcdc', - ghostwEte: 'f8f8ff', - gTd: 'ffd700', - gTMnPd: 'daa520', - Way: '808080', - gYF: '8000', - gYFLw: 'adff2f', - gYy: '808080', - honeyMw: 'f0fff0', - hotpRk: 'ff69b4', - RdianYd: 'cd5c5c', - Rdigo: '4b0082', - ivSy: 'fffff0', - khaki: 'f0e68c', - lavFMr: 'e6e6fa', - lavFMrXsh: 'fff0f5', - lawngYF: '7cfc00', - NmoncEffon: 'fffacd', - ZXe: 'add8e6', - ZcSO: 'f08080', - Zcyan: 'e0ffff', - ZgTMnPdLw: 'fafad2', - ZWay: 'd3d3d3', - ZgYF: '90ee90', - ZgYy: 'd3d3d3', - ZpRk: 'ffb6c1', - ZsOmon: 'ffa07a', - ZsHgYF: '20b2aa', - ZskyXe: '87cefa', - ZUWay: '778899', - ZUgYy: '778899', - ZstAlXe: 'b0c4de', - ZLw: 'ffffe0', - lime: 'ff00', - limegYF: '32cd32', - lRF: 'faf0e6', - magFta: 'ff00ff', - maPon: '800000', - VaquamarRe: '66cdaa', - VXe: 'cd', - VScEd: 'ba55d3', - VpurpN: '9370db', - VsHgYF: '3cb371', - VUXe: '7b68ee', - VsprRggYF: 'fa9a', - VQe: '48d1cc', - VviTetYd: 'c71585', - midnightXe: '191970', - mRtcYam: 'f5fffa', - mistyPse: 'ffe4e1', - moccasR: 'ffe4b5', - navajowEte: 'ffdead', - navy: '80', - Tdlace: 'fdf5e6', - Tive: '808000', - TivedBb: '6b8e23', - Sange: 'ffa500', - SangeYd: 'ff4500', - ScEd: 'da70d6', - pOegTMnPd: 'eee8aa', - pOegYF: '98fb98', - pOeQe: 'afeeee', - pOeviTetYd: 'db7093', - papayawEp: 'ffefd5', - pHKpuff: 'ffdab9', - peru: 'cd853f', - pRk: 'ffc0cb', - plum: 'dda0dd', - powMrXe: 'b0e0e6', - purpN: '800080', - YbeccapurpN: '663399', - Yd: 'ff0000', - Psybrown: 'bc8f8f', - PyOXe: '4169e1', - saddNbPwn: '8b4513', - sOmon: 'fa8072', - sandybPwn: 'f4a460', - sHgYF: '2e8b57', - sHshell: 'fff5ee', - siFna: 'a0522d', - silver: 'c0c0c0', - skyXe: '87ceeb', - UXe: '6a5acd', - UWay: '708090', - UgYy: '708090', - snow: 'fffafa', - sprRggYF: 'ff7f', - stAlXe: '4682b4', - tan: 'd2b48c', - teO: '8080', - tEstN: 'd8bfd8', - tomato: 'ff6347', - Qe: '40e0d0', - viTet: 'ee82ee', - JHt: 'f5deb3', - wEte: 'ffffff', - wEtesmoke: 'f5f5f5', - Lw: 'ffff00', - LwgYF: '9acd32' -}; -function unpack() { - const unpacked = {}; - const keys = Object.keys(names); - const tkeys = Object.keys(map$1$1); - let i, j, k, ok, nk; - for (i = 0; i < keys.length; i++) { - ok = nk = keys[i]; - for (j = 0; j < tkeys.length; j++) { - k = tkeys[j]; - nk = nk.replace(k, map$1$1[k]); - } - k = parseInt(names[ok], 16); - unpacked[nk] = [k >> 16 & 0xFF, k >> 8 & 0xFF, k & 0xFF]; - } - return unpacked; -} -let names$1; -function nameParse(str) { - if (!names$1) { - names$1 = unpack(); - names$1.transparent = [0, 0, 0, 0]; - } - const a = names$1[str.toLowerCase()]; - return a && { - r: a[0], - g: a[1], - b: a[2], - a: a.length === 4 ? a[3] : 255 - }; -} -function modHSL(v, i, ratio) { - if (v) { - let tmp = rgb2hsl(v); - tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1)); - tmp = hsl2rgb(tmp); - v.r = tmp[0]; - v.g = tmp[1]; - v.b = tmp[2]; - } -} -function clone$1(v, proto) { - return v ? Object.assign(proto || {}, v) : v; -} -function fromObject(input) { - var v = {r: 0, g: 0, b: 0, a: 255}; - if (Array.isArray(input)) { - if (input.length >= 3) { - v = {r: input[0], g: input[1], b: input[2], a: 255}; - if (input.length > 3) { - v.a = n2b(input[3]); - } - } - } else { - v = clone$1(input, {r: 0, g: 0, b: 0, a: 1}); - v.a = n2b(v.a); - } - return v; -} -function functionParse(str) { - if (str.charAt(0) === 'r') { - return rgbParse(str); - } - return hueParse(str); -} -class Color { - constructor(input) { - if (input instanceof Color) { - return input; - } - const type = typeof input; - let v; - if (type === 'object') { - v = fromObject(input); - } else if (type === 'string') { - v = hexParse(input) || nameParse(input) || functionParse(input); - } - this._rgb = v; - this._valid = !!v; - } - get valid() { - return this._valid; - } - get rgb() { - var v = clone$1(this._rgb); - if (v) { - v.a = b2n(v.a); - } - return v; - } - set rgb(obj) { - this._rgb = fromObject(obj); - } - rgbString() { - return this._valid ? rgbString(this._rgb) : this._rgb; - } - hexString() { - return this._valid ? hexString(this._rgb) : this._rgb; - } - hslString() { - return this._valid ? hslString(this._rgb) : this._rgb; - } - mix(color, weight) { - const me = this; - if (color) { - const c1 = me.rgb; - const c2 = color.rgb; - let w2; - const p = weight === w2 ? 0.5 : weight; - const w = 2 * p - 1; - const a = c1.a - c2.a; - const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0; - w2 = 1 - w1; - c1.r = 0xFF & w1 * c1.r + w2 * c2.r + 0.5; - c1.g = 0xFF & w1 * c1.g + w2 * c2.g + 0.5; - c1.b = 0xFF & w1 * c1.b + w2 * c2.b + 0.5; - c1.a = p * c1.a + (1 - p) * c2.a; - me.rgb = c1; - } - return me; - } - clone() { - return new Color(this.rgb); - } - alpha(a) { - this._rgb.a = n2b(a); - return this; - } - clearer(ratio) { - const rgb = this._rgb; - rgb.a *= 1 - ratio; - return this; - } - greyscale() { - const rgb = this._rgb; - const val = round(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11); - rgb.r = rgb.g = rgb.b = val; - return this; - } - opaquer(ratio) { - const rgb = this._rgb; - rgb.a *= 1 + ratio; - return this; - } - negate() { - const v = this._rgb; - v.r = 255 - v.r; - v.g = 255 - v.g; - v.b = 255 - v.b; - return this; - } - lighten(ratio) { - modHSL(this._rgb, 2, ratio); - return this; - } - darken(ratio) { - modHSL(this._rgb, 2, -ratio); - return this; - } - saturate(ratio) { - modHSL(this._rgb, 1, ratio); - return this; - } - desaturate(ratio) { - modHSL(this._rgb, 1, -ratio); - return this; - } - rotate(deg) { - rotate(this._rgb, deg); - return this; - } -} -function index_esm(input) { - return new Color(input); -} - -const isPatternOrGradient = (value) => value instanceof CanvasGradient || value instanceof CanvasPattern; -function color(value) { - return isPatternOrGradient(value) ? value : index_esm(value); -} -function getHoverColor(value) { - return isPatternOrGradient(value) - ? value - : index_esm(value).saturate(0.5).darken(0.1).hexString(); -} - -function noop() {} -const uid = (function() { - let id = 0; - return function() { - return id++; - }; -}()); -function isNullOrUndef(value) { - return value === null || typeof value === 'undefined'; -} -function isArray(value) { - if (Array.isArray && Array.isArray(value)) { - return true; - } - const type = Object.prototype.toString.call(value); - if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') { - return true; - } - return false; -} -function isObject(value) { - return value !== null && Object.prototype.toString.call(value) === '[object Object]'; -} -const isNumberFinite = (value) => (typeof value === 'number' || value instanceof Number) && isFinite(+value); -function finiteOrDefault(value, defaultValue) { - return isNumberFinite(value) ? value : defaultValue; -} -function valueOrDefault(value, defaultValue) { - return typeof value === 'undefined' ? defaultValue : value; -} -const toPercentage = (value, dimension) => - typeof value === 'string' && value.endsWith('%') ? - parseFloat(value) / 100 - : value / dimension; -const toDimension = (value, dimension) => - typeof value === 'string' && value.endsWith('%') ? - parseFloat(value) / 100 * dimension - : +value; -function callback(fn, args, thisArg) { - if (fn && typeof fn.call === 'function') { - return fn.apply(thisArg, args); - } -} -function each(loopable, fn, thisArg, reverse) { - let i, len, keys; - if (isArray(loopable)) { - len = loopable.length; - if (reverse) { - for (i = len - 1; i >= 0; i--) { - fn.call(thisArg, loopable[i], i); - } - } else { - for (i = 0; i < len; i++) { - fn.call(thisArg, loopable[i], i); - } - } - } else if (isObject(loopable)) { - keys = Object.keys(loopable); - len = keys.length; - for (i = 0; i < len; i++) { - fn.call(thisArg, loopable[keys[i]], keys[i]); - } - } -} -function _elementsEqual(a0, a1) { - let i, ilen, v0, v1; - if (!a0 || !a1 || a0.length !== a1.length) { - return false; - } - for (i = 0, ilen = a0.length; i < ilen; ++i) { - v0 = a0[i]; - v1 = a1[i]; - if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) { - return false; - } - } - return true; -} -function clone(source) { - if (isArray(source)) { - return source.map(clone); - } - if (isObject(source)) { - const target = Object.create(null); - const keys = Object.keys(source); - const klen = keys.length; - let k = 0; - for (; k < klen; ++k) { - target[keys[k]] = clone(source[keys[k]]); - } - return target; - } - return source; -} -function isValidKey(key) { - return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1; -} -function _merger(key, target, source, options) { - if (!isValidKey(key)) { - return; - } - const tval = target[key]; - const sval = source[key]; - if (isObject(tval) && isObject(sval)) { - merge(tval, sval, options); - } else { - target[key] = clone(sval); - } -} -function merge(target, source, options) { - const sources = isArray(source) ? source : [source]; - const ilen = sources.length; - if (!isObject(target)) { - return target; - } - options = options || {}; - const merger = options.merger || _merger; - for (let i = 0; i < ilen; ++i) { - source = sources[i]; - if (!isObject(source)) { - continue; - } - const keys = Object.keys(source); - for (let k = 0, klen = keys.length; k < klen; ++k) { - merger(keys[k], target, source, options); - } - } - return target; -} -function mergeIf(target, source) { - return merge(target, source, {merger: _mergerIf}); -} -function _mergerIf(key, target, source) { - if (!isValidKey(key)) { - return; - } - const tval = target[key]; - const sval = source[key]; - if (isObject(tval) && isObject(sval)) { - mergeIf(tval, sval); - } else if (!Object.prototype.hasOwnProperty.call(target, key)) { - target[key] = clone(sval); - } -} -function _deprecated(scope, value, previous, current) { - if (value !== undefined) { - console.warn(scope + ': "' + previous + - '" is deprecated. Please use "' + current + '" instead'); - } -} -const emptyString = ''; -const dot = '.'; -function indexOfDotOrLength(key, start) { - const idx = key.indexOf(dot, start); - return idx === -1 ? key.length : idx; -} -function resolveObjectKey(obj, key) { - if (key === emptyString) { - return obj; - } - let pos = 0; - let idx = indexOfDotOrLength(key, pos); - while (obj && idx > pos) { - obj = obj[key.substr(pos, idx - pos)]; - pos = idx + 1; - idx = indexOfDotOrLength(key, pos); - } - return obj; -} -function _capitalize(str) { - return str.charAt(0).toUpperCase() + str.slice(1); -} -const defined = (value) => typeof value !== 'undefined'; -const isFunction = (value) => typeof value === 'function'; -const setsEqual = (a, b) => { - if (a.size !== b.size) { - return false; - } - for (const item of a) { - if (!b.has(item)) { - return false; - } - } - return true; -}; -function _isClickEvent(e) { - return e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu'; -} - -const overrides = Object.create(null); -const descriptors = Object.create(null); -function getScope$1(node, key) { - if (!key) { - return node; - } - const keys = key.split('.'); - for (let i = 0, n = keys.length; i < n; ++i) { - const k = keys[i]; - node = node[k] || (node[k] = Object.create(null)); - } - return node; -} -function set(root, scope, values) { - if (typeof scope === 'string') { - return merge(getScope$1(root, scope), values); - } - return merge(getScope$1(root, ''), scope); -} -class Defaults { - constructor(_descriptors) { - this.animation = undefined; - this.backgroundColor = 'rgba(0,0,0,0.1)'; - this.borderColor = 'rgba(0,0,0,0.1)'; - this.color = '#666'; - this.datasets = {}; - this.devicePixelRatio = (context) => context.chart.platform.getDevicePixelRatio(); - this.elements = {}; - this.events = [ - 'mousemove', - 'mouseout', - 'click', - 'touchstart', - 'touchmove' - ]; - this.font = { - family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", - size: 12, - style: 'normal', - lineHeight: 1.2, - weight: null - }; - this.hover = {}; - this.hoverBackgroundColor = (ctx, options) => getHoverColor(options.backgroundColor); - this.hoverBorderColor = (ctx, options) => getHoverColor(options.borderColor); - this.hoverColor = (ctx, options) => getHoverColor(options.color); - this.indexAxis = 'x'; - this.interaction = { - mode: 'nearest', - intersect: true - }; - this.maintainAspectRatio = true; - this.onHover = null; - this.onClick = null; - this.parsing = true; - this.plugins = {}; - this.responsive = true; - this.scale = undefined; - this.scales = {}; - this.showLine = true; - this.drawActiveElementsOnTop = true; - this.describe(_descriptors); - } - set(scope, values) { - return set(this, scope, values); - } - get(scope) { - return getScope$1(this, scope); - } - describe(scope, values) { - return set(descriptors, scope, values); - } - override(scope, values) { - return set(overrides, scope, values); - } - route(scope, name, targetScope, targetName) { - const scopeObject = getScope$1(this, scope); - const targetScopeObject = getScope$1(this, targetScope); - const privateName = '_' + name; - Object.defineProperties(scopeObject, { - [privateName]: { - value: scopeObject[name], - writable: true - }, - [name]: { - enumerable: true, - get() { - const local = this[privateName]; - const target = targetScopeObject[targetName]; - if (isObject(local)) { - return Object.assign({}, target, local); - } - return valueOrDefault(local, target); - }, - set(value) { - this[privateName] = value; - } - } - }); - } -} -var defaults = new Defaults({ - _scriptable: (name) => !name.startsWith('on'), - _indexable: (name) => name !== 'events', - hover: { - _fallback: 'interaction' - }, - interaction: { - _scriptable: false, - _indexable: false, - } -}); - -const PI = Math.PI; -const TAU = 2 * PI; -const PITAU = TAU + PI; -const INFINITY = Number.POSITIVE_INFINITY; -const RAD_PER_DEG = PI / 180; -const HALF_PI = PI / 2; -const QUARTER_PI = PI / 4; -const TWO_THIRDS_PI = PI * 2 / 3; -const log10 = Math.log10; -const sign = Math.sign; -function niceNum(range) { - const roundedRange = Math.round(range); - range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range; - const niceRange = Math.pow(10, Math.floor(log10(range))); - const fraction = range / niceRange; - const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10; - return niceFraction * niceRange; -} -function _factorize(value) { - const result = []; - const sqrt = Math.sqrt(value); - let i; - for (i = 1; i < sqrt; i++) { - if (value % i === 0) { - result.push(i); - result.push(value / i); - } - } - if (sqrt === (sqrt | 0)) { - result.push(sqrt); - } - result.sort((a, b) => a - b).pop(); - return result; -} -function isNumber(n) { - return !isNaN(parseFloat(n)) && isFinite(n); -} -function almostEquals(x, y, epsilon) { - return Math.abs(x - y) < epsilon; -} -function almostWhole(x, epsilon) { - const rounded = Math.round(x); - return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x); -} -function _setMinAndMaxByKey(array, target, property) { - let i, ilen, value; - for (i = 0, ilen = array.length; i < ilen; i++) { - value = array[i][property]; - if (!isNaN(value)) { - target.min = Math.min(target.min, value); - target.max = Math.max(target.max, value); - } - } -} -function toRadians(degrees) { - return degrees * (PI / 180); -} -function toDegrees(radians) { - return radians * (180 / PI); -} -function _decimalPlaces(x) { - if (!isNumberFinite(x)) { - return; - } - let e = 1; - let p = 0; - while (Math.round(x * e) / e !== x) { - e *= 10; - p++; - } - return p; -} -function getAngleFromPoint(centrePoint, anglePoint) { - const distanceFromXCenter = anglePoint.x - centrePoint.x; - const distanceFromYCenter = anglePoint.y - centrePoint.y; - const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter); - let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter); - if (angle < (-0.5 * PI)) { - angle += TAU; - } - return { - angle, - distance: radialDistanceFromCenter - }; -} -function distanceBetweenPoints(pt1, pt2) { - return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2)); -} -function _angleDiff(a, b) { - return (a - b + PITAU) % TAU - PI; -} -function _normalizeAngle(a) { - return (a % TAU + TAU) % TAU; -} -function _angleBetween(angle, start, end, sameAngleIsFullCircle) { - const a = _normalizeAngle(angle); - const s = _normalizeAngle(start); - const e = _normalizeAngle(end); - const angleToStart = _normalizeAngle(s - a); - const angleToEnd = _normalizeAngle(e - a); - const startToAngle = _normalizeAngle(a - s); - const endToAngle = _normalizeAngle(a - e); - return a === s || a === e || (sameAngleIsFullCircle && s === e) - || (angleToStart > angleToEnd && startToAngle < endToAngle); -} -function _limitValue(value, min, max) { - return Math.max(min, Math.min(max, value)); -} -function _int16Range(value) { - return _limitValue(value, -32768, 32767); -} -function _isBetween(value, start, end, epsilon = 1e-6) { - return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon; -} - -function toFontString(font) { - if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) { - return null; - } - return (font.style ? font.style + ' ' : '') - + (font.weight ? font.weight + ' ' : '') - + font.size + 'px ' - + font.family; -} -function _measureText(ctx, data, gc, longest, string) { - let textWidth = data[string]; - if (!textWidth) { - textWidth = data[string] = ctx.measureText(string).width; - gc.push(string); - } - if (textWidth > longest) { - longest = textWidth; - } - return longest; -} -function _longestText(ctx, font, arrayOfThings, cache) { - cache = cache || {}; - let data = cache.data = cache.data || {}; - let gc = cache.garbageCollect = cache.garbageCollect || []; - if (cache.font !== font) { - data = cache.data = {}; - gc = cache.garbageCollect = []; - cache.font = font; - } - ctx.save(); - ctx.font = font; - let longest = 0; - const ilen = arrayOfThings.length; - let i, j, jlen, thing, nestedThing; - for (i = 0; i < ilen; i++) { - thing = arrayOfThings[i]; - if (thing !== undefined && thing !== null && isArray(thing) !== true) { - longest = _measureText(ctx, data, gc, longest, thing); - } else if (isArray(thing)) { - for (j = 0, jlen = thing.length; j < jlen; j++) { - nestedThing = thing[j]; - if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) { - longest = _measureText(ctx, data, gc, longest, nestedThing); - } - } - } - } - ctx.restore(); - const gcLen = gc.length / 2; - if (gcLen > arrayOfThings.length) { - for (i = 0; i < gcLen; i++) { - delete data[gc[i]]; - } - gc.splice(0, gcLen); - } - return longest; -} -function _alignPixel(chart, pixel, width) { - const devicePixelRatio = chart.currentDevicePixelRatio; - const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0; - return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth; -} -function clearCanvas(canvas, ctx) { - ctx = ctx || canvas.getContext('2d'); - ctx.save(); - ctx.resetTransform(); - ctx.clearRect(0, 0, canvas.width, canvas.height); - ctx.restore(); -} -function drawPoint(ctx, options, x, y) { - let type, xOffset, yOffset, size, cornerRadius; - const style = options.pointStyle; - const rotation = options.rotation; - const radius = options.radius; - let rad = (rotation || 0) * RAD_PER_DEG; - if (style && typeof style === 'object') { - type = style.toString(); - if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') { - ctx.save(); - ctx.translate(x, y); - ctx.rotate(rad); - ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height); - ctx.restore(); - return; - } - } - if (isNaN(radius) || radius <= 0) { - return; - } - ctx.beginPath(); - switch (style) { - default: - ctx.arc(x, y, radius, 0, TAU); - ctx.closePath(); - break; - case 'triangle': - ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); - rad += TWO_THIRDS_PI; - ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); - rad += TWO_THIRDS_PI; - ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); - ctx.closePath(); - break; - case 'rectRounded': - cornerRadius = radius * 0.516; - size = radius - cornerRadius; - xOffset = Math.cos(rad + QUARTER_PI) * size; - yOffset = Math.sin(rad + QUARTER_PI) * size; - ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI); - ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad); - ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI); - ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI); - ctx.closePath(); - break; - case 'rect': - if (!rotation) { - size = Math.SQRT1_2 * radius; - ctx.rect(x - size, y - size, 2 * size, 2 * size); - break; - } - rad += QUARTER_PI; - case 'rectRot': - xOffset = Math.cos(rad) * radius; - yOffset = Math.sin(rad) * radius; - ctx.moveTo(x - xOffset, y - yOffset); - ctx.lineTo(x + yOffset, y - xOffset); - ctx.lineTo(x + xOffset, y + yOffset); - ctx.lineTo(x - yOffset, y + xOffset); - ctx.closePath(); - break; - case 'crossRot': - rad += QUARTER_PI; - case 'cross': - xOffset = Math.cos(rad) * radius; - yOffset = Math.sin(rad) * radius; - ctx.moveTo(x - xOffset, y - yOffset); - ctx.lineTo(x + xOffset, y + yOffset); - ctx.moveTo(x + yOffset, y - xOffset); - ctx.lineTo(x - yOffset, y + xOffset); - break; - case 'star': - xOffset = Math.cos(rad) * radius; - yOffset = Math.sin(rad) * radius; - ctx.moveTo(x - xOffset, y - yOffset); - ctx.lineTo(x + xOffset, y + yOffset); - ctx.moveTo(x + yOffset, y - xOffset); - ctx.lineTo(x - yOffset, y + xOffset); - rad += QUARTER_PI; - xOffset = Math.cos(rad) * radius; - yOffset = Math.sin(rad) * radius; - ctx.moveTo(x - xOffset, y - yOffset); - ctx.lineTo(x + xOffset, y + yOffset); - ctx.moveTo(x + yOffset, y - xOffset); - ctx.lineTo(x - yOffset, y + xOffset); - break; - case 'line': - xOffset = Math.cos(rad) * radius; - yOffset = Math.sin(rad) * radius; - ctx.moveTo(x - xOffset, y - yOffset); - ctx.lineTo(x + xOffset, y + yOffset); - break; - case 'dash': - ctx.moveTo(x, y); - ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius); - break; - } - ctx.fill(); - if (options.borderWidth > 0) { - ctx.stroke(); - } -} -function _isPointInArea(point, area, margin) { - margin = margin || 0.5; - return !area || (point && point.x > area.left - margin && point.x < area.right + margin && - point.y > area.top - margin && point.y < area.bottom + margin); -} -function clipArea(ctx, area) { - ctx.save(); - ctx.beginPath(); - ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); - ctx.clip(); -} -function unclipArea(ctx) { - ctx.restore(); -} -function _steppedLineTo(ctx, previous, target, flip, mode) { - if (!previous) { - return ctx.lineTo(target.x, target.y); - } - if (mode === 'middle') { - const midpoint = (previous.x + target.x) / 2.0; - ctx.lineTo(midpoint, previous.y); - ctx.lineTo(midpoint, target.y); - } else if (mode === 'after' !== !!flip) { - ctx.lineTo(previous.x, target.y); - } else { - ctx.lineTo(target.x, previous.y); - } - ctx.lineTo(target.x, target.y); -} -function _bezierCurveTo(ctx, previous, target, flip) { - if (!previous) { - return ctx.lineTo(target.x, target.y); - } - 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); -} -function renderText(ctx, text, x, y, font, opts = {}) { - const lines = isArray(text) ? text : [text]; - const stroke = opts.strokeWidth > 0 && opts.strokeColor !== ''; - let i, line; - ctx.save(); - ctx.font = font.string; - setRenderOpts(ctx, opts); - for (i = 0; i < lines.length; ++i) { - line = lines[i]; - if (stroke) { - if (opts.strokeColor) { - ctx.strokeStyle = opts.strokeColor; - } - if (!isNullOrUndef(opts.strokeWidth)) { - ctx.lineWidth = opts.strokeWidth; - } - ctx.strokeText(line, x, y, opts.maxWidth); - } - ctx.fillText(line, x, y, opts.maxWidth); - decorateText(ctx, x, y, line, opts); - y += font.lineHeight; - } - ctx.restore(); -} -function setRenderOpts(ctx, opts) { - if (opts.translation) { - ctx.translate(opts.translation[0], opts.translation[1]); - } - if (!isNullOrUndef(opts.rotation)) { - ctx.rotate(opts.rotation); - } - if (opts.color) { - ctx.fillStyle = opts.color; - } - if (opts.textAlign) { - ctx.textAlign = opts.textAlign; - } - if (opts.textBaseline) { - ctx.textBaseline = opts.textBaseline; - } -} -function decorateText(ctx, x, y, line, opts) { - if (opts.strikethrough || opts.underline) { - const metrics = ctx.measureText(line); - const left = x - metrics.actualBoundingBoxLeft; - const right = x + metrics.actualBoundingBoxRight; - const top = y - metrics.actualBoundingBoxAscent; - const bottom = y + metrics.actualBoundingBoxDescent; - const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom; - ctx.strokeStyle = ctx.fillStyle; - ctx.beginPath(); - ctx.lineWidth = opts.decorationWidth || 2; - ctx.moveTo(left, yDecoration); - ctx.lineTo(right, yDecoration); - ctx.stroke(); - } -} -function addRoundedRectPath(ctx, rect) { - const {x, y, w, h, radius} = rect; - ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, -HALF_PI, PI, true); - ctx.lineTo(x, y + h - radius.bottomLeft); - ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true); - ctx.lineTo(x + w - radius.bottomRight, y + h); - ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true); - ctx.lineTo(x + w, y + radius.topRight); - ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true); - ctx.lineTo(x + radius.topLeft, y); -} - -function _lookup(table, value, cmp) { - cmp = cmp || ((index) => table[index] < value); - let hi = table.length - 1; - let lo = 0; - let mid; - while (hi - lo > 1) { - mid = (lo + hi) >> 1; - if (cmp(mid)) { - lo = mid; - } else { - hi = mid; - } - } - return {lo, hi}; -} -const _lookupByKey = (table, key, value) => - _lookup(table, value, index => table[index][key] < value); -const _rlookupByKey = (table, key, value) => - _lookup(table, value, index => table[index][key] >= value); -function _filterBetween(values, min, max) { - let start = 0; - let end = values.length; - while (start < end && values[start] < min) { - start++; - } - while (end > start && values[end - 1] > max) { - end--; - } - return start > 0 || end < values.length - ? values.slice(start, end) - : values; -} -const arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift']; -function listenArrayEvents(array, listener) { - if (array._chartjs) { - array._chartjs.listeners.push(listener); - return; - } - Object.defineProperty(array, '_chartjs', { - configurable: true, - enumerable: false, - value: { - listeners: [listener] - } - }); - arrayEvents.forEach((key) => { - const method = '_onData' + _capitalize(key); - const base = array[key]; - Object.defineProperty(array, key, { - configurable: true, - enumerable: false, - value(...args) { - const res = base.apply(this, args); - array._chartjs.listeners.forEach((object) => { - if (typeof object[method] === 'function') { - object[method](...args); - } - }); - return res; - } - }); - }); -} -function unlistenArrayEvents(array, listener) { - const stub = array._chartjs; - if (!stub) { - return; - } - const listeners = stub.listeners; - const index = listeners.indexOf(listener); - if (index !== -1) { - listeners.splice(index, 1); - } - if (listeners.length > 0) { - return; - } - arrayEvents.forEach((key) => { - delete array[key]; - }); - delete array._chartjs; -} -function _arrayUnique(items) { - const set = new Set(); - let i, ilen; - for (i = 0, ilen = items.length; i < ilen; ++i) { - set.add(items[i]); - } - if (set.size === ilen) { - return items; - } - return Array.from(set); -} - -function _isDomSupported() { - return typeof window !== 'undefined' && typeof document !== 'undefined'; -} -function _getParentNode(domNode) { - let parent = domNode.parentNode; - if (parent && parent.toString() === '[object ShadowRoot]') { - parent = parent.host; - } - return parent; -} -function parseMaxStyle(styleValue, node, parentProperty) { - let valueInPixels; - if (typeof styleValue === 'string') { - valueInPixels = parseInt(styleValue, 10); - if (styleValue.indexOf('%') !== -1) { - valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty]; - } - } else { - valueInPixels = styleValue; - } - return valueInPixels; -} -const getComputedStyle = (element) => window.getComputedStyle(element, null); -function getStyle(el, property) { - return getComputedStyle(el).getPropertyValue(property); -} -const positions = ['top', 'right', 'bottom', 'left']; -function getPositionedStyle(styles, style, suffix) { - const result = {}; - suffix = suffix ? '-' + suffix : ''; - for (let i = 0; i < 4; i++) { - const pos = positions[i]; - result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0; - } - result.width = result.left + result.right; - result.height = result.top + result.bottom; - return result; -} -const useOffsetPos = (x, y, target) => (x > 0 || y > 0) && (!target || !target.shadowRoot); -function getCanvasPosition(evt, canvas) { - const e = evt.native || evt; - const touches = e.touches; - const source = touches && touches.length ? touches[0] : e; - const {offsetX, offsetY} = source; - let box = false; - let x, y; - if (useOffsetPos(offsetX, offsetY, e.target)) { - x = offsetX; - y = offsetY; - } else { - const rect = canvas.getBoundingClientRect(); - x = source.clientX - rect.left; - y = source.clientY - rect.top; - box = true; - } - return {x, y, box}; -} -function getRelativePosition$1(evt, chart) { - const {canvas, currentDevicePixelRatio} = chart; - const style = getComputedStyle(canvas); - const borderBox = style.boxSizing === 'border-box'; - const paddings = getPositionedStyle(style, 'padding'); - const borders = getPositionedStyle(style, 'border', 'width'); - const {x, y, box} = getCanvasPosition(evt, canvas); - const xOffset = paddings.left + (box && borders.left); - const yOffset = paddings.top + (box && borders.top); - let {width, height} = chart; - if (borderBox) { - width -= paddings.width + borders.width; - height -= paddings.height + borders.height; - } - return { - x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio), - y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio) - }; -} -function getContainerSize(canvas, width, height) { - let maxWidth, maxHeight; - if (width === undefined || height === undefined) { - const container = _getParentNode(canvas); - if (!container) { - width = canvas.clientWidth; - height = canvas.clientHeight; - } else { - const rect = container.getBoundingClientRect(); - const containerStyle = getComputedStyle(container); - const containerBorder = getPositionedStyle(containerStyle, 'border', 'width'); - const containerPadding = getPositionedStyle(containerStyle, 'padding'); - width = rect.width - containerPadding.width - containerBorder.width; - height = rect.height - containerPadding.height - containerBorder.height; - maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth'); - maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight'); - } - } - return { - width, - height, - maxWidth: maxWidth || INFINITY, - maxHeight: maxHeight || INFINITY - }; -} -const round1 = v => Math.round(v * 10) / 10; -function getMaximumSize(canvas, bbWidth, bbHeight, aspectRatio) { - const style = getComputedStyle(canvas); - const margins = getPositionedStyle(style, 'margin'); - const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY; - const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY; - const containerSize = getContainerSize(canvas, bbWidth, bbHeight); - let {width, height} = containerSize; - if (style.boxSizing === 'content-box') { - const borders = getPositionedStyle(style, 'border', 'width'); - const paddings = getPositionedStyle(style, 'padding'); - width -= paddings.width + borders.width; - height -= paddings.height + borders.height; - } - width = Math.max(0, width - margins.width); - height = Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height - margins.height); - width = round1(Math.min(width, maxWidth, containerSize.maxWidth)); - height = round1(Math.min(height, maxHeight, containerSize.maxHeight)); - if (width && !height) { - height = round1(width / 2); - } - return { - width, - height - }; -} -function retinaScale(chart, forceRatio, forceStyle) { - const pixelRatio = forceRatio || 1; - const deviceHeight = Math.floor(chart.height * pixelRatio); - const deviceWidth = Math.floor(chart.width * pixelRatio); - chart.height = deviceHeight / pixelRatio; - chart.width = deviceWidth / pixelRatio; - const canvas = chart.canvas; - if (canvas.style && (forceStyle || (!canvas.style.height && !canvas.style.width))) { - canvas.style.height = `${chart.height}px`; - canvas.style.width = `${chart.width}px`; - } - if (chart.currentDevicePixelRatio !== pixelRatio - || canvas.height !== deviceHeight - || canvas.width !== deviceWidth) { - chart.currentDevicePixelRatio = pixelRatio; - canvas.height = deviceHeight; - canvas.width = deviceWidth; - chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); - return true; - } - return false; -} -const supportsEventListenerOptions = (function() { - let passiveSupported = false; - try { - const options = { - get passive() { - passiveSupported = true; - return false; - } - }; - window.addEventListener('test', null, options); - window.removeEventListener('test', null, options); - } catch (e) { - } - return passiveSupported; -}()); -function readUsedSize(element, property) { - const value = getStyle(element, property); - const matches = value && value.match(/^(\d+)(\.\d+)?px$/); - return matches ? +matches[1] : undefined; -} - -function getRelativePosition(e, chart) { - if ('native' in e) { - return { - x: e.x, - y: e.y - }; - } - return getRelativePosition$1(e, chart); -} -function evaluateAllVisibleItems(chart, handler) { - const metasets = chart.getSortedVisibleDatasetMetas(); - let index, data, element; - for (let i = 0, ilen = metasets.length; i < ilen; ++i) { - ({index, data} = metasets[i]); - for (let j = 0, jlen = data.length; j < jlen; ++j) { - element = data[j]; - if (!element.skip) { - handler(element, index, j); - } - } - } -} -function binarySearch(metaset, axis, value, intersect) { - const {controller, data, _sorted} = metaset; - const iScale = controller._cachedMeta.iScale; - if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) { - const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey; - if (!intersect) { - return lookupMethod(data, axis, value); - } else if (controller._sharedOptions) { - const el = data[0]; - const range = typeof el.getRange === 'function' && el.getRange(axis); - if (range) { - const start = lookupMethod(data, axis, value - range); - const end = lookupMethod(data, axis, value + range); - return {lo: start.lo, hi: end.hi}; - } - } - } - return {lo: 0, hi: data.length - 1}; -} -function optimizedEvaluateItems(chart, axis, position, handler, intersect) { - const metasets = chart.getSortedVisibleDatasetMetas(); - const value = position[axis]; - for (let i = 0, ilen = metasets.length; i < ilen; ++i) { - const {index, data} = metasets[i]; - const {lo, hi} = binarySearch(metasets[i], axis, value, intersect); - for (let j = lo; j <= hi; ++j) { - const element = data[j]; - if (!element.skip) { - handler(element, index, j); - } - } - } -} -function getDistanceMetricForAxis(axis) { - const useX = axis.indexOf('x') !== -1; - const useY = axis.indexOf('y') !== -1; - return function(pt1, pt2) { - const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0; - const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0; - return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); - }; -} -function getIntersectItems(chart, position, axis, useFinalPosition) { - const items = []; - if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) { - return items; - } - const evaluationFunc = function(element, datasetIndex, index) { - if (element.inRange(position.x, position.y, useFinalPosition)) { - items.push({element, datasetIndex, index}); - } - }; - optimizedEvaluateItems(chart, axis, position, evaluationFunc, true); - return items; -} -function getNearestRadialItems(chart, position, axis, useFinalPosition) { - let items = []; - function evaluationFunc(element, datasetIndex, index) { - const {startAngle, endAngle} = element.getProps(['startAngle', 'endAngle'], useFinalPosition); - const {angle} = getAngleFromPoint(element, {x: position.x, y: position.y}); - if (_angleBetween(angle, startAngle, endAngle)) { - items.push({element, datasetIndex, index}); - } - } - optimizedEvaluateItems(chart, axis, position, evaluationFunc); - return items; -} -function getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition) { - let items = []; - const distanceMetric = getDistanceMetricForAxis(axis); - let minDistance = Number.POSITIVE_INFINITY; - function evaluationFunc(element, datasetIndex, index) { - const inRange = element.inRange(position.x, position.y, useFinalPosition); - if (intersect && !inRange) { - return; - } - const center = element.getCenterPoint(useFinalPosition); - const pointInArea = _isPointInArea(center, chart.chartArea, chart._minPadding); - if (!pointInArea && !inRange) { - return; - } - const distance = distanceMetric(position, center); - if (distance < minDistance) { - items = [{element, datasetIndex, index}]; - minDistance = distance; - } else if (distance === minDistance) { - items.push({element, datasetIndex, index}); - } - } - optimizedEvaluateItems(chart, axis, position, evaluationFunc); - return items; -} -function getNearestItems(chart, position, axis, intersect, useFinalPosition) { - if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) { - return []; - } - return axis === 'r' && !intersect - ? getNearestRadialItems(chart, position, axis, useFinalPosition) - : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition); -} -function getAxisItems(chart, e, options, useFinalPosition) { - const position = getRelativePosition(e, chart); - const items = []; - const axis = options.axis; - const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange'; - let intersectsItem = false; - evaluateAllVisibleItems(chart, (element, datasetIndex, index) => { - if (element[rangeMethod](position[axis], useFinalPosition)) { - items.push({element, datasetIndex, index}); - } - if (element.inRange(position.x, position.y, useFinalPosition)) { - intersectsItem = true; - } - }); - if (options.intersect && !intersectsItem) { - return []; - } - return items; -} -var Interaction = { - modes: { - index(chart, e, options, useFinalPosition) { - const position = getRelativePosition(e, chart); - const axis = options.axis || 'x'; - const items = options.intersect - ? getIntersectItems(chart, position, axis, useFinalPosition) - : getNearestItems(chart, position, axis, false, useFinalPosition); - const elements = []; - if (!items.length) { - return []; - } - chart.getSortedVisibleDatasetMetas().forEach((meta) => { - const index = items[0].index; - const element = meta.data[index]; - if (element && !element.skip) { - elements.push({element, datasetIndex: meta.index, index}); - } - }); - return elements; - }, - dataset(chart, e, options, useFinalPosition) { - const position = getRelativePosition(e, chart); - const axis = options.axis || 'xy'; - let items = options.intersect - ? getIntersectItems(chart, position, axis, useFinalPosition) : - getNearestItems(chart, position, axis, false, useFinalPosition); - if (items.length > 0) { - const datasetIndex = items[0].datasetIndex; - const data = chart.getDatasetMeta(datasetIndex).data; - items = []; - for (let i = 0; i < data.length; ++i) { - items.push({element: data[i], datasetIndex, index: i}); - } - } - return items; - }, - point(chart, e, options, useFinalPosition) { - const position = getRelativePosition(e, chart); - const axis = options.axis || 'xy'; - return getIntersectItems(chart, position, axis, useFinalPosition); - }, - nearest(chart, e, options, useFinalPosition) { - const position = getRelativePosition(e, chart); - const axis = options.axis || 'xy'; - return getNearestItems(chart, position, axis, options.intersect, useFinalPosition); - }, - x(chart, e, options, useFinalPosition) { - return getAxisItems(chart, e, {axis: 'x', intersect: options.intersect}, useFinalPosition); - }, - y(chart, e, options, useFinalPosition) { - return getAxisItems(chart, e, {axis: 'y', intersect: options.intersect}, useFinalPosition); - } - } -}; - -const LINE_HEIGHT = new RegExp(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/); -const FONT_STYLE = new RegExp(/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/); -function toLineHeight(value, size) { - const matches = ('' + value).match(LINE_HEIGHT); - if (!matches || matches[1] === 'normal') { - return size * 1.2; - } - value = +matches[2]; - switch (matches[3]) { - case 'px': - return value; - case '%': - value /= 100; - break; - } - return size * value; -} -const numberOrZero = v => +v || 0; -function _readValueToProps(value, props) { - const ret = {}; - const objProps = isObject(props); - const keys = objProps ? Object.keys(props) : props; - const read = isObject(value) - ? objProps - ? prop => valueOrDefault(value[prop], value[props[prop]]) - : prop => value[prop] - : () => value; - for (const prop of keys) { - ret[prop] = numberOrZero(read(prop)); - } - return ret; -} -function toTRBL(value) { - return _readValueToProps(value, {top: 'y', right: 'x', bottom: 'y', left: 'x'}); -} -function toTRBLCorners(value) { - return _readValueToProps(value, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']); -} -function toPadding(value) { - const obj = toTRBL(value); - obj.width = obj.left + obj.right; - obj.height = obj.top + obj.bottom; - return obj; -} -function toFont(options, fallback) { - options = options || {}; - fallback = fallback || defaults.font; - let size = valueOrDefault(options.size, fallback.size); - if (typeof size === 'string') { - size = parseInt(size, 10); - } - let style = valueOrDefault(options.style, fallback.style); - if (style && !('' + style).match(FONT_STYLE)) { - console.warn('Invalid font style specified: "' + style + '"'); - style = ''; - } - const font = { - family: valueOrDefault(options.family, fallback.family), - lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size), - size, - style, - weight: valueOrDefault(options.weight, fallback.weight), - string: '' - }; - font.string = toFontString(font); - return font; -} -function resolve(inputs, context, index, info) { - let cacheable = true; - let i, ilen, value; - for (i = 0, ilen = inputs.length; i < ilen; ++i) { - value = inputs[i]; - if (value === undefined) { - continue; - } - if (context !== undefined && typeof value === 'function') { - value = value(context); - cacheable = false; - } - if (index !== undefined && isArray(value)) { - value = value[index % value.length]; - cacheable = false; - } - if (value !== undefined) { - if (info && !cacheable) { - info.cacheable = false; - } - return value; - } - } -} -function _addGrace(minmax, grace, beginAtZero) { - const {min, max} = minmax; - const change = toDimension(grace, (max - min) / 2); - const keepZero = (value, add) => beginAtZero && value === 0 ? 0 : value + add; - return { - min: keepZero(min, -Math.abs(change)), - max: keepZero(max, change) - }; -} -function createContext(parentContext, context) { - return Object.assign(Object.create(parentContext), context); -} - -const STATIC_POSITIONS = ['left', 'top', 'right', 'bottom']; -function filterByPosition(array, position) { - return array.filter(v => v.pos === position); -} -function filterDynamicPositionByAxis(array, axis) { - return array.filter(v => STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis); -} -function sortByWeight(array, reverse) { - return array.sort((a, b) => { - const v0 = reverse ? b : a; - const v1 = reverse ? a : b; - return v0.weight === v1.weight ? - v0.index - v1.index : - v0.weight - v1.weight; - }); -} -function wrapBoxes(boxes) { - const layoutBoxes = []; - let i, ilen, box, pos, stack, stackWeight; - for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) { - box = boxes[i]; - ({position: pos, options: {stack, stackWeight = 1}} = box); - layoutBoxes.push({ - index: i, - box, - pos, - horizontal: box.isHorizontal(), - weight: box.weight, - stack: stack && (pos + stack), - stackWeight - }); - } - return layoutBoxes; -} -function buildStacks(layouts) { - const stacks = {}; - for (const wrap of layouts) { - const {stack, pos, stackWeight} = wrap; - if (!stack || !STATIC_POSITIONS.includes(pos)) { - continue; - } - const _stack = stacks[stack] || (stacks[stack] = {count: 0, placed: 0, weight: 0, size: 0}); - _stack.count++; - _stack.weight += stackWeight; - } - return stacks; -} -function setLayoutDims(layouts, params) { - const stacks = buildStacks(layouts); - const {vBoxMaxWidth, hBoxMaxHeight} = params; - let i, ilen, layout; - for (i = 0, ilen = layouts.length; i < ilen; ++i) { - layout = layouts[i]; - const {fullSize} = layout.box; - const stack = stacks[layout.stack]; - const factor = stack && layout.stackWeight / stack.weight; - if (layout.horizontal) { - layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth; - layout.height = hBoxMaxHeight; - } else { - layout.width = vBoxMaxWidth; - layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight; - } - } - return stacks; -} -function buildLayoutBoxes(boxes) { - const layoutBoxes = wrapBoxes(boxes); - const fullSize = sortByWeight(layoutBoxes.filter(wrap => wrap.box.fullSize), true); - const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true); - const right = sortByWeight(filterByPosition(layoutBoxes, 'right')); - const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true); - const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom')); - const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x'); - const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y'); - return { - fullSize, - leftAndTop: left.concat(top), - rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal), - chartArea: filterByPosition(layoutBoxes, 'chartArea'), - vertical: left.concat(right).concat(centerVertical), - horizontal: top.concat(bottom).concat(centerHorizontal) - }; -} -function getCombinedMax(maxPadding, chartArea, a, b) { - return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]); -} -function updateMaxPadding(maxPadding, boxPadding) { - maxPadding.top = Math.max(maxPadding.top, boxPadding.top); - maxPadding.left = Math.max(maxPadding.left, boxPadding.left); - maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom); - maxPadding.right = Math.max(maxPadding.right, boxPadding.right); -} -function updateDims(chartArea, params, layout, stacks) { - const {pos, box} = layout; - const maxPadding = chartArea.maxPadding; - if (!isObject(pos)) { - if (layout.size) { - chartArea[pos] -= layout.size; - } - const stack = stacks[layout.stack] || {size: 0, count: 1}; - stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width); - layout.size = stack.size / stack.count; - chartArea[pos] += layout.size; - } - if (box.getPadding) { - updateMaxPadding(maxPadding, box.getPadding()); - } - const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right')); - const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom')); - const widthChanged = newWidth !== chartArea.w; - const heightChanged = newHeight !== chartArea.h; - chartArea.w = newWidth; - chartArea.h = newHeight; - return layout.horizontal - ? {same: widthChanged, other: heightChanged} - : {same: heightChanged, other: widthChanged}; -} -function handleMaxPadding(chartArea) { - const maxPadding = chartArea.maxPadding; - function updatePos(pos) { - const change = Math.max(maxPadding[pos] - chartArea[pos], 0); - chartArea[pos] += change; - return change; - } - chartArea.y += updatePos('top'); - chartArea.x += updatePos('left'); - updatePos('right'); - updatePos('bottom'); -} -function getMargins(horizontal, chartArea) { - const maxPadding = chartArea.maxPadding; - function marginForPositions(positions) { - const margin = {left: 0, top: 0, right: 0, bottom: 0}; - positions.forEach((pos) => { - margin[pos] = Math.max(chartArea[pos], maxPadding[pos]); - }); - return margin; - } - return horizontal - ? marginForPositions(['left', 'right']) - : marginForPositions(['top', 'bottom']); -} -function fitBoxes(boxes, chartArea, params, stacks) { - const refitBoxes = []; - let i, ilen, layout, box, refit, changed; - for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) { - layout = boxes[i]; - box = layout.box; - box.update( - layout.width || chartArea.w, - layout.height || chartArea.h, - getMargins(layout.horizontal, chartArea) - ); - const {same, other} = updateDims(chartArea, params, layout, stacks); - refit |= same && refitBoxes.length; - changed = changed || other; - if (!box.fullSize) { - refitBoxes.push(layout); - } - } - return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed; -} -function setBoxDims(box, left, top, width, height) { - box.top = top; - box.left = left; - box.right = left + width; - box.bottom = top + height; - box.width = width; - box.height = height; -} -function placeBoxes(boxes, chartArea, params, stacks) { - const userPadding = params.padding; - let {x, y} = chartArea; - for (const layout of boxes) { - const box = layout.box; - const stack = stacks[layout.stack] || {count: 1, placed: 0, weight: 1}; - const weight = (layout.stackWeight / stack.weight) || 1; - if (layout.horizontal) { - const width = chartArea.w * weight; - const height = stack.size || box.height; - if (defined(stack.start)) { - y = stack.start; - } - if (box.fullSize) { - setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height); - } else { - setBoxDims(box, chartArea.left + stack.placed, y, width, height); - } - stack.start = y; - stack.placed += width; - y = box.bottom; - } else { - const height = chartArea.h * weight; - const width = stack.size || box.width; - if (defined(stack.start)) { - x = stack.start; - } - if (box.fullSize) { - setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top); - } else { - setBoxDims(box, x, chartArea.top + stack.placed, width, height); - } - stack.start = x; - stack.placed += height; - x = box.right; - } - } - chartArea.x = x; - chartArea.y = y; -} -defaults.set('layout', { - autoPadding: true, - padding: { - top: 0, - right: 0, - bottom: 0, - left: 0 - } -}); -var layouts = { - addBox(chart, item) { - if (!chart.boxes) { - chart.boxes = []; - } - item.fullSize = item.fullSize || false; - item.position = item.position || 'top'; - item.weight = item.weight || 0; - item._layers = item._layers || function() { - return [{ - z: 0, - draw(chartArea) { - item.draw(chartArea); - } - }]; - }; - chart.boxes.push(item); - }, - removeBox(chart, layoutItem) { - const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1; - if (index !== -1) { - chart.boxes.splice(index, 1); - } - }, - configure(chart, item, options) { - item.fullSize = options.fullSize; - item.position = options.position; - item.weight = options.weight; - }, - update(chart, width, height, minPadding) { - if (!chart) { - return; - } - const padding = toPadding(chart.options.layout.padding); - const availableWidth = Math.max(width - padding.width, 0); - const availableHeight = Math.max(height - padding.height, 0); - const boxes = buildLayoutBoxes(chart.boxes); - const verticalBoxes = boxes.vertical; - const horizontalBoxes = boxes.horizontal; - each(chart.boxes, box => { - if (typeof box.beforeLayout === 'function') { - box.beforeLayout(); - } - }); - const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) => - wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1; - const params = Object.freeze({ - outerWidth: width, - outerHeight: height, - padding, - availableWidth, - availableHeight, - vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount, - hBoxMaxHeight: availableHeight / 2 - }); - const maxPadding = Object.assign({}, padding); - updateMaxPadding(maxPadding, toPadding(minPadding)); - const chartArea = Object.assign({ - maxPadding, - w: availableWidth, - h: availableHeight, - x: padding.left, - y: padding.top - }, padding); - const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params); - fitBoxes(boxes.fullSize, chartArea, params, stacks); - fitBoxes(verticalBoxes, chartArea, params, stacks); - if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) { - fitBoxes(verticalBoxes, chartArea, params, stacks); - } - handleMaxPadding(chartArea); - placeBoxes(boxes.leftAndTop, chartArea, params, stacks); - chartArea.x += chartArea.w; - chartArea.y += chartArea.h; - placeBoxes(boxes.rightAndBottom, chartArea, params, stacks); - chart.chartArea = { - left: chartArea.left, - top: chartArea.top, - right: chartArea.left + chartArea.w, - bottom: chartArea.top + chartArea.h, - height: chartArea.h, - width: chartArea.w, - }; - each(boxes.chartArea, (layout) => { - const box = layout.box; - Object.assign(box, chart.chartArea); - box.update(chartArea.w, chartArea.h, {left: 0, top: 0, right: 0, bottom: 0}); - }); - } -}; - -function _createResolver(scopes, prefixes = [''], rootScopes = scopes, fallback, getTarget = () => scopes[0]) { - if (!defined(fallback)) { - fallback = _resolve('_fallback', scopes); - } - const cache = { - [Symbol.toStringTag]: 'Object', - _cacheable: true, - _scopes: scopes, - _rootScopes: rootScopes, - _fallback: fallback, - _getTarget: getTarget, - override: (scope) => _createResolver([scope, ...scopes], prefixes, rootScopes, fallback), - }; - return new Proxy(cache, { - deleteProperty(target, prop) { - delete target[prop]; - delete target._keys; - delete scopes[0][prop]; - return true; - }, - get(target, prop) { - return _cached(target, prop, - () => _resolveWithPrefixes(prop, prefixes, scopes, target)); - }, - getOwnPropertyDescriptor(target, prop) { - return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop); - }, - getPrototypeOf() { - return Reflect.getPrototypeOf(scopes[0]); - }, - has(target, prop) { - return getKeysFromAllScopes(target).includes(prop); - }, - ownKeys(target) { - return getKeysFromAllScopes(target); - }, - set(target, prop, value) { - const storage = target._storage || (target._storage = getTarget()); - target[prop] = storage[prop] = value; - delete target._keys; - return true; - } - }); -} -function _attachContext(proxy, context, subProxy, descriptorDefaults) { - const cache = { - _cacheable: false, - _proxy: proxy, - _context: context, - _subProxy: subProxy, - _stack: new Set(), - _descriptors: _descriptors(proxy, descriptorDefaults), - setContext: (ctx) => _attachContext(proxy, ctx, subProxy, descriptorDefaults), - override: (scope) => _attachContext(proxy.override(scope), context, subProxy, descriptorDefaults) - }; - return new Proxy(cache, { - deleteProperty(target, prop) { - delete target[prop]; - delete proxy[prop]; - return true; - }, - get(target, prop, receiver) { - return _cached(target, prop, - () => _resolveWithContext(target, prop, receiver)); - }, - getOwnPropertyDescriptor(target, prop) { - return target._descriptors.allKeys - ? Reflect.has(proxy, prop) ? {enumerable: true, configurable: true} : undefined - : Reflect.getOwnPropertyDescriptor(proxy, prop); - }, - getPrototypeOf() { - return Reflect.getPrototypeOf(proxy); - }, - has(target, prop) { - return Reflect.has(proxy, prop); - }, - ownKeys() { - return Reflect.ownKeys(proxy); - }, - set(target, prop, value) { - proxy[prop] = value; - delete target[prop]; - return true; - } - }); -} -function _descriptors(proxy, defaults = {scriptable: true, indexable: true}) { - const {_scriptable = defaults.scriptable, _indexable = defaults.indexable, _allKeys = defaults.allKeys} = proxy; - return { - allKeys: _allKeys, - scriptable: _scriptable, - indexable: _indexable, - isScriptable: isFunction(_scriptable) ? _scriptable : () => _scriptable, - isIndexable: isFunction(_indexable) ? _indexable : () => _indexable - }; -} -const readKey = (prefix, name) => prefix ? prefix + _capitalize(name) : name; -const needsSubResolver = (prop, value) => isObject(value) && prop !== 'adapters' && - (Object.getPrototypeOf(value) === null || value.constructor === Object); -function _cached(target, prop, resolve) { - if (Object.prototype.hasOwnProperty.call(target, prop)) { - return target[prop]; - } - const value = resolve(); - target[prop] = value; - return value; -} -function _resolveWithContext(target, prop, receiver) { - const {_proxy, _context, _subProxy, _descriptors: descriptors} = target; - let value = _proxy[prop]; - if (isFunction(value) && descriptors.isScriptable(prop)) { - value = _resolveScriptable(prop, value, target, receiver); - } - if (isArray(value) && value.length) { - value = _resolveArray(prop, value, target, descriptors.isIndexable); - } - if (needsSubResolver(prop, value)) { - value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors); - } - return value; -} -function _resolveScriptable(prop, value, target, receiver) { - const {_proxy, _context, _subProxy, _stack} = target; - if (_stack.has(prop)) { - throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop); - } - _stack.add(prop); - value = value(_context, _subProxy || receiver); - _stack.delete(prop); - if (needsSubResolver(prop, value)) { - value = createSubResolver(_proxy._scopes, _proxy, prop, value); - } - return value; -} -function _resolveArray(prop, value, target, isIndexable) { - const {_proxy, _context, _subProxy, _descriptors: descriptors} = target; - if (defined(_context.index) && isIndexable(prop)) { - value = value[_context.index % value.length]; - } else if (isObject(value[0])) { - const arr = value; - const scopes = _proxy._scopes.filter(s => s !== arr); - value = []; - for (const item of arr) { - const resolver = createSubResolver(scopes, _proxy, prop, item); - value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors)); - } - } - return value; -} -function resolveFallback(fallback, prop, value) { - return isFunction(fallback) ? fallback(prop, value) : fallback; -} -const getScope = (key, parent) => key === true ? parent - : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined; -function addScopes(set, parentScopes, key, parentFallback, value) { - for (const parent of parentScopes) { - const scope = getScope(key, parent); - if (scope) { - set.add(scope); - const fallback = resolveFallback(scope._fallback, key, value); - if (defined(fallback) && fallback !== key && fallback !== parentFallback) { - return fallback; - } - } else if (scope === false && defined(parentFallback) && key !== parentFallback) { - return null; - } - } - return false; -} -function createSubResolver(parentScopes, resolver, prop, value) { - const rootScopes = resolver._rootScopes; - const fallback = resolveFallback(resolver._fallback, prop, value); - const allScopes = [...parentScopes, ...rootScopes]; - const set = new Set(); - set.add(value); - let key = addScopesFromKey(set, allScopes, prop, fallback || prop, value); - if (key === null) { - return false; - } - if (defined(fallback) && fallback !== prop) { - key = addScopesFromKey(set, allScopes, fallback, key, value); - if (key === null) { - return false; - } - } - return _createResolver(Array.from(set), [''], rootScopes, fallback, - () => subGetTarget(resolver, prop, value)); -} -function addScopesFromKey(set, allScopes, key, fallback, item) { - while (key) { - key = addScopes(set, allScopes, key, fallback, item); - } - return key; -} -function subGetTarget(resolver, prop, value) { - const parent = resolver._getTarget(); - if (!(prop in parent)) { - parent[prop] = {}; - } - const target = parent[prop]; - if (isArray(target) && isObject(value)) { - return value; - } - return target; -} -function _resolveWithPrefixes(prop, prefixes, scopes, proxy) { - let value; - for (const prefix of prefixes) { - value = _resolve(readKey(prefix, prop), scopes); - if (defined(value)) { - return needsSubResolver(prop, value) - ? createSubResolver(scopes, proxy, prop, value) - : value; - } - } -} -function _resolve(key, scopes) { - for (const scope of scopes) { - if (!scope) { - continue; - } - const value = scope[key]; - if (defined(value)) { - return value; - } - } -} -function getKeysFromAllScopes(target) { - let keys = target._keys; - if (!keys) { - keys = target._keys = resolveKeysFromAllScopes(target._scopes); - } - return keys; -} -function resolveKeysFromAllScopes(scopes) { - const set = new Set(); - for (const scope of scopes) { - for (const key of Object.keys(scope).filter(k => !k.startsWith('_'))) { - set.add(key); - } - } - return Array.from(set); -} - -const EPSILON = Number.EPSILON || 1e-14; -const getPoint = (points, i) => i < points.length && !points[i].skip && points[i]; -const getValueAxis = (indexAxis) => indexAxis === 'x' ? 'y' : 'x'; -function splineCurve(firstPoint, middlePoint, afterPoint, t) { - const previous = firstPoint.skip ? middlePoint : firstPoint; - const current = middlePoint; - const next = afterPoint.skip ? middlePoint : afterPoint; - const d01 = distanceBetweenPoints(current, previous); - const d12 = distanceBetweenPoints(next, current); - let s01 = d01 / (d01 + d12); - let s12 = d12 / (d01 + d12); - s01 = isNaN(s01) ? 0 : s01; - s12 = isNaN(s12) ? 0 : s12; - const fa = t * s01; - const fb = t * s12; - return { - previous: { - x: current.x - fa * (next.x - previous.x), - y: current.y - fa * (next.y - previous.y) - }, - next: { - x: current.x + fb * (next.x - previous.x), - y: current.y + fb * (next.y - previous.y) - } - }; -} -function monotoneAdjust(points, deltaK, mK) { - const pointsLen = points.length; - let alphaK, betaK, tauK, squaredMagnitude, pointCurrent; - let pointAfter = getPoint(points, 0); - for (let i = 0; i < pointsLen - 1; ++i) { - pointCurrent = pointAfter; - pointAfter = getPoint(points, i + 1); - if (!pointCurrent || !pointAfter) { - continue; - } - if (almostEquals(deltaK[i], 0, EPSILON)) { - mK[i] = mK[i + 1] = 0; - continue; - } - alphaK = mK[i] / deltaK[i]; - betaK = mK[i + 1] / deltaK[i]; - squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2); - if (squaredMagnitude <= 9) { - continue; - } - tauK = 3 / Math.sqrt(squaredMagnitude); - mK[i] = alphaK * tauK * deltaK[i]; - mK[i + 1] = betaK * tauK * deltaK[i]; - } -} -function monotoneCompute(points, mK, indexAxis = 'x') { - const valueAxis = getValueAxis(indexAxis); - const pointsLen = points.length; - let delta, pointBefore, pointCurrent; - let pointAfter = getPoint(points, 0); - for (let i = 0; i < pointsLen; ++i) { - pointBefore = pointCurrent; - pointCurrent = pointAfter; - pointAfter = getPoint(points, i + 1); - if (!pointCurrent) { - continue; - } - const iPixel = pointCurrent[indexAxis]; - const vPixel = pointCurrent[valueAxis]; - if (pointBefore) { - delta = (iPixel - pointBefore[indexAxis]) / 3; - pointCurrent[`cp1${indexAxis}`] = iPixel - delta; - pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i]; - } - if (pointAfter) { - delta = (pointAfter[indexAxis] - iPixel) / 3; - pointCurrent[`cp2${indexAxis}`] = iPixel + delta; - pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i]; - } - } -} -function splineCurveMonotone(points, indexAxis = 'x') { - const valueAxis = getValueAxis(indexAxis); - const pointsLen = points.length; - const deltaK = Array(pointsLen).fill(0); - const mK = Array(pointsLen); - let i, pointBefore, pointCurrent; - let pointAfter = getPoint(points, 0); - for (i = 0; i < pointsLen; ++i) { - pointBefore = pointCurrent; - pointCurrent = pointAfter; - pointAfter = getPoint(points, i + 1); - if (!pointCurrent) { - continue; - } - if (pointAfter) { - const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis]; - deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0; - } - mK[i] = !pointBefore ? deltaK[i] - : !pointAfter ? deltaK[i - 1] - : (sign(deltaK[i - 1]) !== sign(deltaK[i])) ? 0 - : (deltaK[i - 1] + deltaK[i]) / 2; - } - monotoneAdjust(points, deltaK, mK); - monotoneCompute(points, mK, indexAxis); -} -function capControlPoint(pt, min, max) { - return Math.max(Math.min(pt, max), min); -} -function capBezierPoints(points, area) { - let i, ilen, point, inArea, inAreaPrev; - let inAreaNext = _isPointInArea(points[0], area); - for (i = 0, ilen = points.length; i < ilen; ++i) { - inAreaPrev = inArea; - inArea = inAreaNext; - inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area); - if (!inArea) { - continue; - } - point = points[i]; - if (inAreaPrev) { - point.cp1x = capControlPoint(point.cp1x, area.left, area.right); - point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom); - } - if (inAreaNext) { - point.cp2x = capControlPoint(point.cp2x, area.left, area.right); - point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom); - } - } -} -function _updateBezierControlPoints(points, options, area, loop, indexAxis) { - let i, ilen, point, controlPoints; - if (options.spanGaps) { - points = points.filter((pt) => !pt.skip); - } - if (options.cubicInterpolationMode === 'monotone') { - splineCurveMonotone(points, indexAxis); - } else { - let prev = loop ? points[points.length - 1] : points[0]; - for (i = 0, ilen = points.length; i < ilen; ++i) { - point = points[i]; - controlPoints = splineCurve( - prev, - point, - points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen], - options.tension - ); - point.cp1x = controlPoints.previous.x; - point.cp1y = controlPoints.previous.y; - point.cp2x = controlPoints.next.x; - point.cp2y = controlPoints.next.y; - prev = point; - } - } - if (options.capBezierPoints) { - capBezierPoints(points, area); - } -} - -const atEdge = (t) => t === 0 || t === 1; -const elasticIn = (t, s, p) => -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p)); -const elasticOut = (t, s, p) => Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1; -const effects = { - linear: t => t, - easeInQuad: t => t * t, - easeOutQuad: t => -t * (t - 2), - easeInOutQuad: t => ((t /= 0.5) < 1) - ? 0.5 * t * t - : -0.5 * ((--t) * (t - 2) - 1), - easeInCubic: t => t * t * t, - easeOutCubic: t => (t -= 1) * t * t + 1, - easeInOutCubic: t => ((t /= 0.5) < 1) - ? 0.5 * t * t * t - : 0.5 * ((t -= 2) * t * t + 2), - easeInQuart: t => t * t * t * t, - easeOutQuart: t => -((t -= 1) * t * t * t - 1), - easeInOutQuart: t => ((t /= 0.5) < 1) - ? 0.5 * t * t * t * t - : -0.5 * ((t -= 2) * t * t * t - 2), - easeInQuint: t => t * t * t * t * t, - easeOutQuint: t => (t -= 1) * t * t * t * t + 1, - easeInOutQuint: t => ((t /= 0.5) < 1) - ? 0.5 * t * t * t * t * t - : 0.5 * ((t -= 2) * t * t * t * t + 2), - easeInSine: t => -Math.cos(t * HALF_PI) + 1, - easeOutSine: t => Math.sin(t * HALF_PI), - easeInOutSine: t => -0.5 * (Math.cos(PI * t) - 1), - easeInExpo: t => (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)), - easeOutExpo: t => (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1, - 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), - easeInCirc: t => (t >= 1) ? t : -(Math.sqrt(1 - t * t) - 1), - easeOutCirc: t => Math.sqrt(1 - (t -= 1) * t), - easeInOutCirc: t => ((t /= 0.5) < 1) - ? -0.5 * (Math.sqrt(1 - t * t) - 1) - : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1), - easeInElastic: t => atEdge(t) ? t : elasticIn(t, 0.075, 0.3), - easeOutElastic: t => atEdge(t) ? t : elasticOut(t, 0.075, 0.3), - easeInOutElastic(t) { - const s = 0.1125; - const p = 0.45; - return atEdge(t) ? t : - t < 0.5 - ? 0.5 * elasticIn(t * 2, s, p) - : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p); - }, - easeInBack(t) { - const s = 1.70158; - return t * t * ((s + 1) * t - s); - }, - easeOutBack(t) { - const s = 1.70158; - return (t -= 1) * t * ((s + 1) * t + s) + 1; - }, - easeInOutBack(t) { - let s = 1.70158; - if ((t /= 0.5) < 1) { - return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s)); - } - return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2); - }, - easeInBounce: t => 1 - effects.easeOutBounce(1 - t), - easeOutBounce(t) { - const m = 7.5625; - const d = 2.75; - if (t < (1 / d)) { - return m * t * t; - } - if (t < (2 / d)) { - return m * (t -= (1.5 / d)) * t + 0.75; - } - if (t < (2.5 / d)) { - return m * (t -= (2.25 / d)) * t + 0.9375; - } - return m * (t -= (2.625 / d)) * t + 0.984375; - }, - easeInOutBounce: t => (t < 0.5) - ? effects.easeInBounce(t * 2) * 0.5 - : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5, -}; - -function _pointInLine(p1, p2, t, mode) { - return { - x: p1.x + t * (p2.x - p1.x), - y: p1.y + t * (p2.y - p1.y) - }; -} -function _steppedInterpolation(p1, p2, t, mode) { - return { - x: p1.x + t * (p2.x - p1.x), - y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y - : mode === 'after' ? t < 1 ? p1.y : p2.y - : t > 0 ? p2.y : p1.y - }; -} -function _bezierInterpolation(p1, p2, t, mode) { - const cp1 = {x: p1.cp2x, y: p1.cp2y}; - const cp2 = {x: p2.cp1x, y: p2.cp1y}; - const a = _pointInLine(p1, cp1, t); - const b = _pointInLine(cp1, cp2, t); - const c = _pointInLine(cp2, p2, t); - const d = _pointInLine(a, b, t); - const e = _pointInLine(b, c, t); - return _pointInLine(d, e, t); -} - -const intlCache = new Map(); -function getNumberFormat(locale, options) { - options = options || {}; - const cacheKey = locale + JSON.stringify(options); - let formatter = intlCache.get(cacheKey); - if (!formatter) { - formatter = new Intl.NumberFormat(locale, options); - intlCache.set(cacheKey, formatter); - } - return formatter; -} -function formatNumber(num, locale, options) { - return getNumberFormat(locale, options).format(num); -} - -const getRightToLeftAdapter = function(rectX, width) { - return { - x(x) { - return rectX + rectX + width - x; - }, - setWidth(w) { - width = w; - }, - textAlign(align) { - if (align === 'center') { - return align; - } - return align === 'right' ? 'left' : 'right'; - }, - xPlus(x, value) { - return x - value; - }, - leftForLtr(x, itemWidth) { - return x - itemWidth; - }, - }; -}; -const getLeftToRightAdapter = function() { - return { - x(x) { - return x; - }, - setWidth(w) { - }, - textAlign(align) { - return align; - }, - xPlus(x, value) { - return x + value; - }, - leftForLtr(x, _itemWidth) { - return x; - }, - }; -}; -function getRtlAdapter(rtl, rectX, width) { - return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter(); -} -function overrideTextDirection(ctx, direction) { - let style, original; - if (direction === 'ltr' || direction === 'rtl') { - style = ctx.canvas.style; - original = [ - style.getPropertyValue('direction'), - style.getPropertyPriority('direction'), - ]; - style.setProperty('direction', direction, 'important'); - ctx.prevTextDirection = original; - } -} -function restoreTextDirection(ctx, original) { - if (original !== undefined) { - delete ctx.prevTextDirection; - ctx.canvas.style.setProperty('direction', original[0], original[1]); - } -} - -function propertyFn(property) { - if (property === 'angle') { - return { - between: _angleBetween, - compare: _angleDiff, - normalize: _normalizeAngle, - }; - } - return { - between: _isBetween, - compare: (a, b) => a - b, - normalize: x => x - }; -} -function normalizeSegment({start, end, count, loop, style}) { - return { - start: start % count, - end: end % count, - loop: loop && (end - start + 1) % count === 0, - style - }; -} -function getSegment(segment, points, bounds) { - const {property, start: startBound, end: endBound} = bounds; - const {between, normalize} = propertyFn(property); - const count = points.length; - let {start, end, loop} = segment; - let i, ilen; - if (loop) { - start += count; - end += count; - for (i = 0, ilen = count; i < ilen; ++i) { - if (!between(normalize(points[start % count][property]), startBound, endBound)) { - break; - } - start--; - end--; - } - start %= count; - end %= count; - } - if (end < start) { - end += count; - } - return {start, end, loop, style: segment.style}; -} -function _boundSegment(segment, points, bounds) { - if (!bounds) { - return [segment]; - } - const {property, start: startBound, end: endBound} = bounds; - const count = points.length; - const {compare, between, normalize} = propertyFn(property); - const {start, end, loop, style} = getSegment(segment, points, bounds); - const result = []; - let inside = false; - let subStart = null; - let value, point, prevValue; - const startIsBefore = () => between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0; - const endIsBefore = () => compare(endBound, value) === 0 || between(endBound, prevValue, value); - const shouldStart = () => inside || startIsBefore(); - const shouldStop = () => !inside || endIsBefore(); - for (let i = start, prev = start; i <= end; ++i) { - point = points[i % count]; - if (point.skip) { - continue; - } - value = normalize(point[property]); - if (value === prevValue) { - continue; - } - inside = between(value, startBound, endBound); - if (subStart === null && shouldStart()) { - subStart = compare(value, startBound) === 0 ? i : prev; - } - if (subStart !== null && shouldStop()) { - result.push(normalizeSegment({start: subStart, end: i, loop, count, style})); - subStart = null; - } - prev = i; - prevValue = value; - } - if (subStart !== null) { - result.push(normalizeSegment({start: subStart, end, loop, count, style})); - } - return result; -} -function _boundSegments(line, bounds) { - const result = []; - const segments = line.segments; - for (let i = 0; i < segments.length; i++) { - const sub = _boundSegment(segments[i], line.points, bounds); - if (sub.length) { - result.push(...sub); - } - } - return result; -} -function findStartAndEnd(points, count, loop, spanGaps) { - let start = 0; - let end = count - 1; - if (loop && !spanGaps) { - while (start < count && !points[start].skip) { - start++; - } - } - while (start < count && points[start].skip) { - start++; - } - start %= count; - if (loop) { - end += start; - } - while (end > start && points[end % count].skip) { - end--; - } - end %= count; - return {start, end}; -} -function solidSegments(points, start, max, loop) { - const count = points.length; - const result = []; - let last = start; - let prev = points[start]; - let end; - for (end = start + 1; end <= max; ++end) { - const cur = points[end % count]; - if (cur.skip || cur.stop) { - if (!prev.skip) { - loop = false; - result.push({start: start % count, end: (end - 1) % count, loop}); - start = last = cur.stop ? end : null; - } - } else { - last = end; - if (prev.skip) { - start = end; - } - } - prev = cur; - } - if (last !== null) { - result.push({start: start % count, end: last % count, loop}); - } - return result; -} -function _computeSegments(line, segmentOptions) { - const points = line.points; - const spanGaps = line.options.spanGaps; - const count = points.length; - if (!count) { - return []; - } - const loop = !!line._loop; - const {start, end} = findStartAndEnd(points, count, loop, spanGaps); - if (spanGaps === true) { - return splitByStyles(line, [{start, end, loop}], points, segmentOptions); - } - const max = end < start ? end + count : end; - const completeLoop = !!line._fullLoop && start === 0 && end === count - 1; - return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions); -} -function splitByStyles(line, segments, points, segmentOptions) { - if (!segmentOptions || !segmentOptions.setContext || !points) { - return segments; - } - return doSplitByStyles(line, segments, points, segmentOptions); -} -function doSplitByStyles(line, segments, points, segmentOptions) { - const chartContext = line._chart.getContext(); - const baseStyle = readStyle(line.options); - const {_datasetIndex: datasetIndex, options: {spanGaps}} = line; - const count = points.length; - const result = []; - let prevStyle = baseStyle; - let start = segments[0].start; - let i = start; - function addStyle(s, e, l, st) { - const dir = spanGaps ? -1 : 1; - if (s === e) { - return; - } - s += count; - while (points[s % count].skip) { - s -= dir; - } - while (points[e % count].skip) { - e += dir; - } - if (s % count !== e % count) { - result.push({start: s % count, end: e % count, loop: l, style: st}); - prevStyle = st; - start = e % count; - } - } - for (const segment of segments) { - start = spanGaps ? start : segment.start; - let prev = points[start % count]; - let style; - for (i = start + 1; i <= segment.end; i++) { - const pt = points[i % count]; - style = readStyle(segmentOptions.setContext(createContext(chartContext, { - type: 'segment', - p0: prev, - p1: pt, - p0DataIndex: (i - 1) % count, - p1DataIndex: i % count, - datasetIndex - }))); - if (styleChanged(style, prevStyle)) { - addStyle(start, i - 1, segment.loop, prevStyle); - } - prev = pt; - prevStyle = style; - } - if (start < i - 1) { - addStyle(start, i - 1, segment.loop, prevStyle); - } - } - return result; -} -function readStyle(options) { - return { - backgroundColor: options.backgroundColor, - borderCapStyle: options.borderCapStyle, - borderDash: options.borderDash, - borderDashOffset: options.borderDashOffset, - borderJoinStyle: options.borderJoinStyle, - borderWidth: options.borderWidth, - borderColor: options.borderColor - }; -} -function styleChanged(style, prevStyle) { - return prevStyle && JSON.stringify(style) !== JSON.stringify(prevStyle); -} - -var helpers = /*#__PURE__*/Object.freeze({ -__proto__: null, -easingEffects: effects, -color: color, -getHoverColor: getHoverColor, -noop: noop, -uid: uid, -isNullOrUndef: isNullOrUndef, -isArray: isArray, -isObject: isObject, -isFinite: isNumberFinite, -finiteOrDefault: finiteOrDefault, -valueOrDefault: valueOrDefault, -toPercentage: toPercentage, -toDimension: toDimension, -callback: callback, -each: each, -_elementsEqual: _elementsEqual, -clone: clone, -_merger: _merger, -merge: merge, -mergeIf: mergeIf, -_mergerIf: _mergerIf, -_deprecated: _deprecated, -resolveObjectKey: resolveObjectKey, -_capitalize: _capitalize, -defined: defined, -isFunction: isFunction, -setsEqual: setsEqual, -_isClickEvent: _isClickEvent, -toFontString: toFontString, -_measureText: _measureText, -_longestText: _longestText, -_alignPixel: _alignPixel, -clearCanvas: clearCanvas, -drawPoint: drawPoint, -_isPointInArea: _isPointInArea, -clipArea: clipArea, -unclipArea: unclipArea, -_steppedLineTo: _steppedLineTo, -_bezierCurveTo: _bezierCurveTo, -renderText: renderText, -addRoundedRectPath: addRoundedRectPath, -_lookup: _lookup, -_lookupByKey: _lookupByKey, -_rlookupByKey: _rlookupByKey, -_filterBetween: _filterBetween, -listenArrayEvents: listenArrayEvents, -unlistenArrayEvents: unlistenArrayEvents, -_arrayUnique: _arrayUnique, -_createResolver: _createResolver, -_attachContext: _attachContext, -_descriptors: _descriptors, -splineCurve: splineCurve, -splineCurveMonotone: splineCurveMonotone, -_updateBezierControlPoints: _updateBezierControlPoints, -_isDomSupported: _isDomSupported, -_getParentNode: _getParentNode, -getStyle: getStyle, -getRelativePosition: getRelativePosition$1, -getMaximumSize: getMaximumSize, -retinaScale: retinaScale, -supportsEventListenerOptions: supportsEventListenerOptions, -readUsedSize: readUsedSize, -fontString: fontString, -requestAnimFrame: requestAnimFrame, -throttled: throttled, -debounce: debounce, -_toLeftRightCenter: _toLeftRightCenter, -_alignStartEnd: _alignStartEnd, -_textX: _textX, -_pointInLine: _pointInLine, -_steppedInterpolation: _steppedInterpolation, -_bezierInterpolation: _bezierInterpolation, -formatNumber: formatNumber, -toLineHeight: toLineHeight, -_readValueToProps: _readValueToProps, -toTRBL: toTRBL, -toTRBLCorners: toTRBLCorners, -toPadding: toPadding, -toFont: toFont, -resolve: resolve, -_addGrace: _addGrace, -createContext: createContext, -PI: PI, -TAU: TAU, -PITAU: PITAU, -INFINITY: INFINITY, -RAD_PER_DEG: RAD_PER_DEG, -HALF_PI: HALF_PI, -QUARTER_PI: QUARTER_PI, -TWO_THIRDS_PI: TWO_THIRDS_PI, -log10: log10, -sign: sign, -niceNum: niceNum, -_factorize: _factorize, -isNumber: isNumber, -almostEquals: almostEquals, -almostWhole: almostWhole, -_setMinAndMaxByKey: _setMinAndMaxByKey, -toRadians: toRadians, -toDegrees: toDegrees, -_decimalPlaces: _decimalPlaces, -getAngleFromPoint: getAngleFromPoint, -distanceBetweenPoints: distanceBetweenPoints, -_angleDiff: _angleDiff, -_normalizeAngle: _normalizeAngle, -_angleBetween: _angleBetween, -_limitValue: _limitValue, -_int16Range: _int16Range, -_isBetween: _isBetween, -getRtlAdapter: getRtlAdapter, -overrideTextDirection: overrideTextDirection, -restoreTextDirection: restoreTextDirection, -_boundSegment: _boundSegment, -_boundSegments: _boundSegments, -_computeSegments: _computeSegments -}); - -class BasePlatform { - acquireContext(canvas, aspectRatio) {} - releaseContext(context) { - return false; - } - addEventListener(chart, type, listener) {} - removeEventListener(chart, type, listener) {} - getDevicePixelRatio() { - return 1; - } - getMaximumSize(element, width, height, aspectRatio) { - width = Math.max(0, width || element.width); - height = height || element.height; - return { - width, - height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height) - }; - } - isAttached(canvas) { - return true; - } - updateConfig(config) { - } -} - -class BasicPlatform extends BasePlatform { - acquireContext(item) { - return item && item.getContext && item.getContext('2d') || null; - } - updateConfig(config) { - config.options.animation = false; - } -} - -const EXPANDO_KEY = '$chartjs'; -const EVENT_TYPES = { - touchstart: 'mousedown', - touchmove: 'mousemove', - touchend: 'mouseup', - pointerenter: 'mouseenter', - pointerdown: 'mousedown', - pointermove: 'mousemove', - pointerup: 'mouseup', - pointerleave: 'mouseout', - pointerout: 'mouseout' -}; -const isNullOrEmpty = value => value === null || value === ''; -function initCanvas(canvas, aspectRatio) { - const style = canvas.style; - const renderHeight = canvas.getAttribute('height'); - const renderWidth = canvas.getAttribute('width'); - canvas[EXPANDO_KEY] = { - initial: { - height: renderHeight, - width: renderWidth, - style: { - display: style.display, - height: style.height, - width: style.width - } - } - }; - style.display = style.display || 'block'; - style.boxSizing = style.boxSizing || 'border-box'; - if (isNullOrEmpty(renderWidth)) { - const displayWidth = readUsedSize(canvas, 'width'); - if (displayWidth !== undefined) { - canvas.width = displayWidth; - } - } - if (isNullOrEmpty(renderHeight)) { - if (canvas.style.height === '') { - canvas.height = canvas.width / (aspectRatio || 2); - } else { - const displayHeight = readUsedSize(canvas, 'height'); - if (displayHeight !== undefined) { - canvas.height = displayHeight; - } - } - } - return canvas; -} -const eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false; -function addListener(node, type, listener) { - node.addEventListener(type, listener, eventListenerOptions); -} -function removeListener(chart, type, listener) { - chart.canvas.removeEventListener(type, listener, eventListenerOptions); -} -function fromNativeEvent(event, chart) { - const type = EVENT_TYPES[event.type] || event.type; - const {x, y} = getRelativePosition$1(event, chart); - return { - type, - chart, - native: event, - x: x !== undefined ? x : null, - y: y !== undefined ? y : null, - }; -} -function nodeListContains(nodeList, canvas) { - for (const node of nodeList) { - if (node === canvas || node.contains(canvas)) { - return true; - } - } -} -function createAttachObserver(chart, type, listener) { - const canvas = chart.canvas; - const observer = new MutationObserver(entries => { - let trigger = false; - for (const entry of entries) { - trigger = trigger || nodeListContains(entry.addedNodes, canvas); - trigger = trigger && !nodeListContains(entry.removedNodes, canvas); - } - if (trigger) { - listener(); - } - }); - observer.observe(document, {childList: true, subtree: true}); - return observer; -} -function createDetachObserver(chart, type, listener) { - const canvas = chart.canvas; - const observer = new MutationObserver(entries => { - let trigger = false; - for (const entry of entries) { - trigger = trigger || nodeListContains(entry.removedNodes, canvas); - trigger = trigger && !nodeListContains(entry.addedNodes, canvas); - } - if (trigger) { - listener(); - } - }); - observer.observe(document, {childList: true, subtree: true}); - return observer; -} -const drpListeningCharts = new Map(); -let oldDevicePixelRatio = 0; -function onWindowResize() { - const dpr = window.devicePixelRatio; - if (dpr === oldDevicePixelRatio) { - return; - } - oldDevicePixelRatio = dpr; - drpListeningCharts.forEach((resize, chart) => { - if (chart.currentDevicePixelRatio !== dpr) { - resize(); - } - }); -} -function listenDevicePixelRatioChanges(chart, resize) { - if (!drpListeningCharts.size) { - window.addEventListener('resize', onWindowResize); - } - drpListeningCharts.set(chart, resize); -} -function unlistenDevicePixelRatioChanges(chart) { - drpListeningCharts.delete(chart); - if (!drpListeningCharts.size) { - window.removeEventListener('resize', onWindowResize); - } -} -function createResizeObserver(chart, type, listener) { - const canvas = chart.canvas; - const container = canvas && _getParentNode(canvas); - if (!container) { - return; - } - const resize = throttled((width, height) => { - const w = container.clientWidth; - listener(width, height); - if (w < container.clientWidth) { - listener(); - } - }, window); - const observer = new ResizeObserver(entries => { - const entry = entries[0]; - const width = entry.contentRect.width; - const height = entry.contentRect.height; - if (width === 0 && height === 0) { - return; - } - resize(width, height); - }); - observer.observe(container); - listenDevicePixelRatioChanges(chart, resize); - return observer; -} -function releaseObserver(chart, type, observer) { - if (observer) { - observer.disconnect(); - } - if (type === 'resize') { - unlistenDevicePixelRatioChanges(chart); - } -} -function createProxyAndListen(chart, type, listener) { - const canvas = chart.canvas; - const proxy = throttled((event) => { - if (chart.ctx !== null) { - listener(fromNativeEvent(event, chart)); - } - }, chart, (args) => { - const event = args[0]; - return [event, event.offsetX, event.offsetY]; - }); - addListener(canvas, type, proxy); - return proxy; -} -class DomPlatform extends BasePlatform { - acquireContext(canvas, aspectRatio) { - const context = canvas && canvas.getContext && canvas.getContext('2d'); - if (context && context.canvas === canvas) { - initCanvas(canvas, aspectRatio); - return context; - } - return null; - } - releaseContext(context) { - const canvas = context.canvas; - if (!canvas[EXPANDO_KEY]) { - return false; - } - const initial = canvas[EXPANDO_KEY].initial; - ['height', 'width'].forEach((prop) => { - const value = initial[prop]; - if (isNullOrUndef(value)) { - canvas.removeAttribute(prop); - } else { - canvas.setAttribute(prop, value); - } - }); - const style = initial.style || {}; - Object.keys(style).forEach((key) => { - canvas.style[key] = style[key]; - }); - canvas.width = canvas.width; - delete canvas[EXPANDO_KEY]; - return true; - } - addEventListener(chart, type, listener) { - this.removeEventListener(chart, type); - const proxies = chart.$proxies || (chart.$proxies = {}); - const handlers = { - attach: createAttachObserver, - detach: createDetachObserver, - resize: createResizeObserver - }; - const handler = handlers[type] || createProxyAndListen; - proxies[type] = handler(chart, type, listener); - } - removeEventListener(chart, type) { - const proxies = chart.$proxies || (chart.$proxies = {}); - const proxy = proxies[type]; - if (!proxy) { - return; - } - const handlers = { - attach: releaseObserver, - detach: releaseObserver, - resize: releaseObserver - }; - const handler = handlers[type] || removeListener; - handler(chart, type, proxy); - proxies[type] = undefined; - } - getDevicePixelRatio() { - return window.devicePixelRatio; - } - getMaximumSize(canvas, width, height, aspectRatio) { - return getMaximumSize(canvas, width, height, aspectRatio); - } - isAttached(canvas) { - const container = _getParentNode(canvas); - return !!(container && container.isConnected); - } -} - -function _detectPlatform(canvas) { - if (!_isDomSupported() || (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) { - return BasicPlatform; - } - return DomPlatform; -} - -var platforms = /*#__PURE__*/Object.freeze({ -__proto__: null, -_detectPlatform: _detectPlatform, -BasePlatform: BasePlatform, -BasicPlatform: BasicPlatform, -DomPlatform: DomPlatform -}); - -const transparent = 'transparent'; -const interpolators = { - boolean(from, to, factor) { - return factor > 0.5 ? to : from; - }, - color(from, to, factor) { - const c0 = color(from || transparent); - const c1 = c0.valid && color(to || transparent); - return c1 && c1.valid - ? c1.mix(c0, factor).hexString() - : to; - }, - number(from, to, factor) { - return from + (to - from) * factor; - } -}; -class Animation { - constructor(cfg, target, prop, to) { - const currentValue = target[prop]; - to = resolve([cfg.to, to, currentValue, cfg.from]); - const from = resolve([cfg.from, currentValue, to]); - this._active = true; - this._fn = cfg.fn || interpolators[cfg.type || typeof from]; - this._easing = effects[cfg.easing] || effects.linear; - this._start = Math.floor(Date.now() + (cfg.delay || 0)); - this._duration = this._total = Math.floor(cfg.duration); - this._loop = !!cfg.loop; - this._target = target; - this._prop = prop; - this._from = from; - this._to = to; - this._promises = undefined; - } - active() { - return this._active; - } - update(cfg, to, date) { - if (this._active) { - this._notify(false); - const currentValue = this._target[this._prop]; - const elapsed = date - this._start; - const remain = this._duration - elapsed; - this._start = date; - this._duration = Math.floor(Math.max(remain, cfg.duration)); - this._total += elapsed; - this._loop = !!cfg.loop; - this._to = resolve([cfg.to, to, currentValue, cfg.from]); - this._from = resolve([cfg.from, currentValue, to]); - } - } - cancel() { - if (this._active) { - this.tick(Date.now()); - this._active = false; - this._notify(false); - } - } - tick(date) { - const elapsed = date - this._start; - const duration = this._duration; - const prop = this._prop; - const from = this._from; - const loop = this._loop; - const to = this._to; - let factor; - this._active = from !== to && (loop || (elapsed < duration)); - if (!this._active) { - this._target[prop] = to; - this._notify(true); - return; - } - if (elapsed < 0) { - this._target[prop] = from; - return; - } - factor = (elapsed / duration) % 2; - factor = loop && factor > 1 ? 2 - factor : factor; - factor = this._easing(Math.min(1, Math.max(0, factor))); - this._target[prop] = this._fn(from, to, factor); - } - wait() { - const promises = this._promises || (this._promises = []); - return new Promise((res, rej) => { - promises.push({res, rej}); - }); - } - _notify(resolved) { - const method = resolved ? 'res' : 'rej'; - const promises = this._promises || []; - for (let i = 0; i < promises.length; i++) { - promises[i][method](); - } - } -} - -const numbers = ['x', 'y', 'borderWidth', 'radius', 'tension']; -const colors = ['color', 'borderColor', 'backgroundColor']; -defaults.set('animation', { - delay: undefined, - duration: 1000, - easing: 'easeOutQuart', - fn: undefined, - from: undefined, - loop: undefined, - to: undefined, - type: undefined, -}); -const animationOptions = Object.keys(defaults.animation); -defaults.describe('animation', { - _fallback: false, - _indexable: false, - _scriptable: (name) => name !== 'onProgress' && name !== 'onComplete' && name !== 'fn', -}); -defaults.set('animations', { - colors: { - type: 'color', - properties: colors - }, - numbers: { - type: 'number', - properties: numbers - }, -}); -defaults.describe('animations', { - _fallback: 'animation', -}); -defaults.set('transitions', { - active: { - animation: { - duration: 400 - } - }, - resize: { - animation: { - duration: 0 - } - }, - show: { - animations: { - colors: { - from: 'transparent' - }, - visible: { - type: 'boolean', - duration: 0 - }, - } - }, - hide: { - animations: { - colors: { - to: 'transparent' - }, - visible: { - type: 'boolean', - easing: 'linear', - fn: v => v | 0 - }, - } - } -}); -class Animations { - constructor(chart, config) { - this._chart = chart; - this._properties = new Map(); - this.configure(config); - } - configure(config) { - if (!isObject(config)) { - return; - } - const animatedProps = this._properties; - Object.getOwnPropertyNames(config).forEach(key => { - const cfg = config[key]; - if (!isObject(cfg)) { - return; - } - const resolved = {}; - for (const option of animationOptions) { - resolved[option] = cfg[option]; - } - (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => { - if (prop === key || !animatedProps.has(prop)) { - animatedProps.set(prop, resolved); - } - }); - }); - } - _animateOptions(target, values) { - const newOptions = values.options; - const options = resolveTargetOptions(target, newOptions); - if (!options) { - return []; - } - const animations = this._createAnimations(options, newOptions); - if (newOptions.$shared) { - awaitAll(target.options.$animations, newOptions).then(() => { - target.options = newOptions; - }, () => { - }); - } - return animations; - } - _createAnimations(target, values) { - const animatedProps = this._properties; - const animations = []; - const running = target.$animations || (target.$animations = {}); - const props = Object.keys(values); - const date = Date.now(); - let i; - for (i = props.length - 1; i >= 0; --i) { - const prop = props[i]; - if (prop.charAt(0) === '$') { - continue; - } - if (prop === 'options') { - animations.push(...this._animateOptions(target, values)); - continue; - } - const value = values[prop]; - let animation = running[prop]; - const cfg = animatedProps.get(prop); - if (animation) { - if (cfg && animation.active()) { - animation.update(cfg, value, date); - continue; - } else { - animation.cancel(); - } - } - if (!cfg || !cfg.duration) { - target[prop] = value; - continue; - } - running[prop] = animation = new Animation(cfg, target, prop, value); - animations.push(animation); - } - return animations; - } - update(target, values) { - if (this._properties.size === 0) { - Object.assign(target, values); - return; - } - const animations = this._createAnimations(target, values); - if (animations.length) { - animator.add(this._chart, animations); - return true; - } - } -} -function awaitAll(animations, properties) { - const running = []; - const keys = Object.keys(properties); - for (let i = 0; i < keys.length; i++) { - const anim = animations[keys[i]]; - if (anim && anim.active()) { - running.push(anim.wait()); - } - } - return Promise.all(running); -} -function resolveTargetOptions(target, newOptions) { - if (!newOptions) { - return; - } - let options = target.options; - if (!options) { - target.options = newOptions; - return; - } - if (options.$shared) { - target.options = options = Object.assign({}, options, {$shared: false, $animations: {}}); - } - return options; -} - -function scaleClip(scale, allowedOverflow) { - const opts = scale && scale.options || {}; - const reverse = opts.reverse; - const min = opts.min === undefined ? allowedOverflow : 0; - const max = opts.max === undefined ? allowedOverflow : 0; - return { - start: reverse ? max : min, - end: reverse ? min : max - }; -} -function defaultClip(xScale, yScale, allowedOverflow) { - if (allowedOverflow === false) { - return false; - } - const x = scaleClip(xScale, allowedOverflow); - const y = scaleClip(yScale, allowedOverflow); - return { - top: y.end, - right: x.end, - bottom: y.start, - left: x.start - }; -} -function toClip(value) { - let t, r, b, l; - if (isObject(value)) { - t = value.top; - r = value.right; - b = value.bottom; - l = value.left; - } else { - t = r = b = l = value; - } - return { - top: t, - right: r, - bottom: b, - left: l, - disabled: value === false - }; -} -function getSortedDatasetIndices(chart, filterVisible) { - const keys = []; - const metasets = chart._getSortedDatasetMetas(filterVisible); - let i, ilen; - for (i = 0, ilen = metasets.length; i < ilen; ++i) { - keys.push(metasets[i].index); - } - return keys; -} -function applyStack(stack, value, dsIndex, options = {}) { - const keys = stack.keys; - const singleMode = options.mode === 'single'; - let i, ilen, datasetIndex, otherValue; - if (value === null) { - return; - } - for (i = 0, ilen = keys.length; i < ilen; ++i) { - datasetIndex = +keys[i]; - if (datasetIndex === dsIndex) { - if (options.all) { - continue; - } - break; - } - otherValue = stack.values[datasetIndex]; - if (isNumberFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) { - value += otherValue; - } - } - return value; -} -function convertObjectDataToArray(data) { - const keys = Object.keys(data); - const adata = new Array(keys.length); - let i, ilen, key; - for (i = 0, ilen = keys.length; i < ilen; ++i) { - key = keys[i]; - adata[i] = { - x: key, - y: data[key] - }; - } - return adata; -} -function isStacked(scale, meta) { - const stacked = scale && scale.options.stacked; - return stacked || (stacked === undefined && meta.stack !== undefined); -} -function getStackKey(indexScale, valueScale, meta) { - return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`; -} -function getUserBounds(scale) { - const {min, max, minDefined, maxDefined} = scale.getUserBounds(); - return { - min: minDefined ? min : Number.NEGATIVE_INFINITY, - max: maxDefined ? max : Number.POSITIVE_INFINITY - }; -} -function getOrCreateStack(stacks, stackKey, indexValue) { - const subStack = stacks[stackKey] || (stacks[stackKey] = {}); - return subStack[indexValue] || (subStack[indexValue] = {}); -} -function getLastIndexInStack(stack, vScale, positive, type) { - for (const meta of vScale.getMatchingVisibleMetas(type).reverse()) { - const value = stack[meta.index]; - if ((positive && value > 0) || (!positive && value < 0)) { - return meta.index; - } - } - return null; -} -function updateStacks(controller, parsed) { - const {chart, _cachedMeta: meta} = controller; - const stacks = chart._stacks || (chart._stacks = {}); - const {iScale, vScale, index: datasetIndex} = meta; - const iAxis = iScale.axis; - const vAxis = vScale.axis; - const key = getStackKey(iScale, vScale, meta); - const ilen = parsed.length; - let stack; - for (let i = 0; i < ilen; ++i) { - const item = parsed[i]; - const {[iAxis]: index, [vAxis]: value} = item; - const itemStacks = item._stacks || (item._stacks = {}); - stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index); - stack[datasetIndex] = value; - stack._top = getLastIndexInStack(stack, vScale, true, meta.type); - stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type); - } -} -function getFirstScaleId(chart, axis) { - const scales = chart.scales; - return Object.keys(scales).filter(key => scales[key].axis === axis).shift(); -} -function createDatasetContext(parent, index) { - return createContext(parent, - { - active: false, - dataset: undefined, - datasetIndex: index, - index, - mode: 'default', - type: 'dataset' - } - ); -} -function createDataContext(parent, index, element) { - return createContext(parent, { - active: false, - dataIndex: index, - parsed: undefined, - raw: undefined, - element, - index, - mode: 'default', - type: 'data' - }); -} -function clearStacks(meta, items) { - const datasetIndex = meta.controller.index; - const axis = meta.vScale && meta.vScale.axis; - if (!axis) { - return; - } - items = items || meta._parsed; - for (const parsed of items) { - const stacks = parsed._stacks; - if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) { - return; - } - delete stacks[axis][datasetIndex]; - } -} -const isDirectUpdateMode = (mode) => mode === 'reset' || mode === 'none'; -const cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached); -const createStack = (canStack, meta, chart) => canStack && !meta.hidden && meta._stacked - && {keys: getSortedDatasetIndices(chart, true), values: null}; -class DatasetController { - constructor(chart, datasetIndex) { - this.chart = chart; - this._ctx = chart.ctx; - this.index = datasetIndex; - this._cachedDataOpts = {}; - this._cachedMeta = this.getMeta(); - this._type = this._cachedMeta.type; - this.options = undefined; - this._parsing = false; - this._data = undefined; - this._objectData = undefined; - this._sharedOptions = undefined; - this._drawStart = undefined; - this._drawCount = undefined; - this.enableOptionSharing = false; - this.$context = undefined; - this._syncList = []; - this.initialize(); - } - initialize() { - const meta = this._cachedMeta; - this.configure(); - this.linkScales(); - meta._stacked = isStacked(meta.vScale, meta); - this.addElements(); - } - updateIndex(datasetIndex) { - if (this.index !== datasetIndex) { - clearStacks(this._cachedMeta); - } - this.index = datasetIndex; - } - linkScales() { - const chart = this.chart; - const meta = this._cachedMeta; - const dataset = this.getDataset(); - const chooseId = (axis, x, y, r) => axis === 'x' ? x : axis === 'r' ? r : y; - const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x')); - const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y')); - const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r')); - const indexAxis = meta.indexAxis; - const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid); - const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid); - meta.xScale = this.getScaleForId(xid); - meta.yScale = this.getScaleForId(yid); - meta.rScale = this.getScaleForId(rid); - meta.iScale = this.getScaleForId(iid); - meta.vScale = this.getScaleForId(vid); - } - getDataset() { - return this.chart.data.datasets[this.index]; - } - getMeta() { - return this.chart.getDatasetMeta(this.index); - } - getScaleForId(scaleID) { - return this.chart.scales[scaleID]; - } - _getOtherScale(scale) { - const meta = this._cachedMeta; - return scale === meta.iScale - ? meta.vScale - : meta.iScale; - } - reset() { - this._update('reset'); - } - _destroy() { - const meta = this._cachedMeta; - if (this._data) { - unlistenArrayEvents(this._data, this); - } - if (meta._stacked) { - clearStacks(meta); - } - } - _dataCheck() { - const dataset = this.getDataset(); - const data = dataset.data || (dataset.data = []); - const _data = this._data; - if (isObject(data)) { - this._data = convertObjectDataToArray(data); - } else if (_data !== data) { - if (_data) { - unlistenArrayEvents(_data, this); - const meta = this._cachedMeta; - clearStacks(meta); - meta._parsed = []; - } - if (data && Object.isExtensible(data)) { - listenArrayEvents(data, this); - } - this._syncList = []; - this._data = data; - } - } - addElements() { - const meta = this._cachedMeta; - this._dataCheck(); - if (this.datasetElementType) { - meta.dataset = new this.datasetElementType(); - } - } - buildOrUpdateElements(resetNewElements) { - const meta = this._cachedMeta; - const dataset = this.getDataset(); - let stackChanged = false; - this._dataCheck(); - const oldStacked = meta._stacked; - meta._stacked = isStacked(meta.vScale, meta); - if (meta.stack !== dataset.stack) { - stackChanged = true; - clearStacks(meta); - meta.stack = dataset.stack; - } - this._resyncElements(resetNewElements); - if (stackChanged || oldStacked !== meta._stacked) { - updateStacks(this, meta._parsed); - } - } - configure() { - const config = this.chart.config; - const scopeKeys = config.datasetScopeKeys(this._type); - const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true); - this.options = config.createResolver(scopes, this.getContext()); - this._parsing = this.options.parsing; - this._cachedDataOpts = {}; - } - parse(start, count) { - const {_cachedMeta: meta, _data: data} = this; - const {iScale, _stacked} = meta; - const iAxis = iScale.axis; - let sorted = start === 0 && count === data.length ? true : meta._sorted; - let prev = start > 0 && meta._parsed[start - 1]; - let i, cur, parsed; - if (this._parsing === false) { - meta._parsed = data; - meta._sorted = true; - parsed = data; - } else { - if (isArray(data[start])) { - parsed = this.parseArrayData(meta, data, start, count); - } else if (isObject(data[start])) { - parsed = this.parseObjectData(meta, data, start, count); - } else { - parsed = this.parsePrimitiveData(meta, data, start, count); - } - const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]); - for (i = 0; i < count; ++i) { - meta._parsed[i + start] = cur = parsed[i]; - if (sorted) { - if (isNotInOrderComparedToPrev()) { - sorted = false; - } - prev = cur; - } - } - meta._sorted = sorted; - } - if (_stacked) { - updateStacks(this, parsed); - } - } - parsePrimitiveData(meta, data, start, count) { - const {iScale, vScale} = meta; - const iAxis = iScale.axis; - const vAxis = vScale.axis; - const labels = iScale.getLabels(); - const singleScale = iScale === vScale; - const parsed = new Array(count); - let i, ilen, index; - for (i = 0, ilen = count; i < ilen; ++i) { - index = i + start; - parsed[i] = { - [iAxis]: singleScale || iScale.parse(labels[index], index), - [vAxis]: vScale.parse(data[index], index) - }; - } - return parsed; - } - parseArrayData(meta, data, start, count) { - const {xScale, yScale} = meta; - const parsed = new Array(count); - let i, ilen, index, item; - for (i = 0, ilen = count; i < ilen; ++i) { - index = i + start; - item = data[index]; - parsed[i] = { - x: xScale.parse(item[0], index), - y: yScale.parse(item[1], index) - }; - } - return parsed; - } - parseObjectData(meta, data, start, count) { - const {xScale, yScale} = meta; - const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing; - const parsed = new Array(count); - let i, ilen, index, item; - for (i = 0, ilen = count; i < ilen; ++i) { - index = i + start; - item = data[index]; - parsed[i] = { - x: xScale.parse(resolveObjectKey(item, xAxisKey), index), - y: yScale.parse(resolveObjectKey(item, yAxisKey), index) - }; - } - return parsed; - } - getParsed(index) { - return this._cachedMeta._parsed[index]; - } - getDataElement(index) { - return this._cachedMeta.data[index]; - } - applyStack(scale, parsed, mode) { - const chart = this.chart; - const meta = this._cachedMeta; - const value = parsed[scale.axis]; - const stack = { - keys: getSortedDatasetIndices(chart, true), - values: parsed._stacks[scale.axis] - }; - return applyStack(stack, value, meta.index, {mode}); - } - updateRangeFromParsed(range, scale, parsed, stack) { - const parsedValue = parsed[scale.axis]; - let value = parsedValue === null ? NaN : parsedValue; - const values = stack && parsed._stacks[scale.axis]; - if (stack && values) { - stack.values = values; - value = applyStack(stack, parsedValue, this._cachedMeta.index); - } - range.min = Math.min(range.min, value); - range.max = Math.max(range.max, value); - } - getMinMax(scale, canStack) { - const meta = this._cachedMeta; - const _parsed = meta._parsed; - const sorted = meta._sorted && scale === meta.iScale; - const ilen = _parsed.length; - const otherScale = this._getOtherScale(scale); - const stack = createStack(canStack, meta, this.chart); - const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY}; - const {min: otherMin, max: otherMax} = getUserBounds(otherScale); - let i, parsed; - function _skip() { - parsed = _parsed[i]; - const otherValue = parsed[otherScale.axis]; - return !isNumberFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue; - } - for (i = 0; i < ilen; ++i) { - if (_skip()) { - continue; - } - this.updateRangeFromParsed(range, scale, parsed, stack); - if (sorted) { - break; - } - } - if (sorted) { - for (i = ilen - 1; i >= 0; --i) { - if (_skip()) { - continue; - } - this.updateRangeFromParsed(range, scale, parsed, stack); - break; - } - } - return range; - } - getAllParsedValues(scale) { - const parsed = this._cachedMeta._parsed; - const values = []; - let i, ilen, value; - for (i = 0, ilen = parsed.length; i < ilen; ++i) { - value = parsed[i][scale.axis]; - if (isNumberFinite(value)) { - values.push(value); - } - } - return values; - } - getMaxOverflow() { - return false; - } - getLabelAndValue(index) { - const meta = this._cachedMeta; - const iScale = meta.iScale; - const vScale = meta.vScale; - const parsed = this.getParsed(index); - return { - label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '', - value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : '' - }; - } - _update(mode) { - const meta = this._cachedMeta; - this.update(mode || 'default'); - meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow()))); - } - update(mode) {} - draw() { - const ctx = this._ctx; - const chart = this.chart; - const meta = this._cachedMeta; - const elements = meta.data || []; - const area = chart.chartArea; - const active = []; - const start = this._drawStart || 0; - const count = this._drawCount || (elements.length - start); - const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop; - let i; - if (meta.dataset) { - meta.dataset.draw(ctx, area, start, count); - } - for (i = start; i < start + count; ++i) { - const element = elements[i]; - if (element.hidden) { - continue; - } - if (element.active && drawActiveElementsOnTop) { - active.push(element); - } else { - element.draw(ctx, area); - } - } - for (i = 0; i < active.length; ++i) { - active[i].draw(ctx, area); - } - } - getStyle(index, active) { - const mode = active ? 'active' : 'default'; - return index === undefined && this._cachedMeta.dataset - ? this.resolveDatasetElementOptions(mode) - : this.resolveDataElementOptions(index || 0, mode); - } - getContext(index, active, mode) { - const dataset = this.getDataset(); - let context; - if (index >= 0 && index < this._cachedMeta.data.length) { - const element = this._cachedMeta.data[index]; - context = element.$context || - (element.$context = createDataContext(this.getContext(), index, element)); - context.parsed = this.getParsed(index); - context.raw = dataset.data[index]; - context.index = context.dataIndex = index; - } else { - context = this.$context || - (this.$context = createDatasetContext(this.chart.getContext(), this.index)); - context.dataset = dataset; - context.index = context.datasetIndex = this.index; - } - context.active = !!active; - context.mode = mode; - return context; - } - resolveDatasetElementOptions(mode) { - return this._resolveElementOptions(this.datasetElementType.id, mode); - } - resolveDataElementOptions(index, mode) { - return this._resolveElementOptions(this.dataElementType.id, mode, index); - } - _resolveElementOptions(elementType, mode = 'default', index) { - const active = mode === 'active'; - const cache = this._cachedDataOpts; - const cacheKey = elementType + '-' + mode; - const cached = cache[cacheKey]; - const sharing = this.enableOptionSharing && defined(index); - if (cached) { - return cloneIfNotShared(cached, sharing); - } - const config = this.chart.config; - const scopeKeys = config.datasetElementScopeKeys(this._type, elementType); - const prefixes = active ? [`${elementType}Hover`, 'hover', elementType, ''] : [elementType, '']; - const scopes = config.getOptionScopes(this.getDataset(), scopeKeys); - const names = Object.keys(defaults.elements[elementType]); - const context = () => this.getContext(index, active); - const values = config.resolveNamedOptions(scopes, names, context, prefixes); - if (values.$shared) { - values.$shared = sharing; - cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing)); - } - return values; - } - _resolveAnimations(index, transition, active) { - const chart = this.chart; - const cache = this._cachedDataOpts; - const cacheKey = `animation-${transition}`; - const cached = cache[cacheKey]; - if (cached) { - return cached; - } - let options; - if (chart.options.animation !== false) { - const config = this.chart.config; - const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition); - const scopes = config.getOptionScopes(this.getDataset(), scopeKeys); - options = config.createResolver(scopes, this.getContext(index, active, transition)); - } - const animations = new Animations(chart, options && options.animations); - if (options && options._cacheable) { - cache[cacheKey] = Object.freeze(animations); - } - return animations; - } - getSharedOptions(options) { - if (!options.$shared) { - return; - } - return this._sharedOptions || (this._sharedOptions = Object.assign({}, options)); - } - includeOptions(mode, sharedOptions) { - return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled; - } - updateElement(element, index, properties, mode) { - if (isDirectUpdateMode(mode)) { - Object.assign(element, properties); - } else { - this._resolveAnimations(index, mode).update(element, properties); - } - } - updateSharedOptions(sharedOptions, mode, newOptions) { - if (sharedOptions && !isDirectUpdateMode(mode)) { - this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions); - } - } - _setStyle(element, index, mode, active) { - element.active = active; - const options = this.getStyle(index, active); - this._resolveAnimations(index, mode, active).update(element, { - options: (!active && this.getSharedOptions(options)) || options - }); - } - removeHoverStyle(element, datasetIndex, index) { - this._setStyle(element, index, 'active', false); - } - setHoverStyle(element, datasetIndex, index) { - this._setStyle(element, index, 'active', true); - } - _removeDatasetHoverStyle() { - const element = this._cachedMeta.dataset; - if (element) { - this._setStyle(element, undefined, 'active', false); - } - } - _setDatasetHoverStyle() { - const element = this._cachedMeta.dataset; - if (element) { - this._setStyle(element, undefined, 'active', true); - } - } - _resyncElements(resetNewElements) { - const data = this._data; - const elements = this._cachedMeta.data; - for (const [method, arg1, arg2] of this._syncList) { - this[method](arg1, arg2); - } - this._syncList = []; - const numMeta = elements.length; - const numData = data.length; - const count = Math.min(numData, numMeta); - if (count) { - this.parse(0, count); - } - if (numData > numMeta) { - this._insertElements(numMeta, numData - numMeta, resetNewElements); - } else if (numData < numMeta) { - this._removeElements(numData, numMeta - numData); - } - } - _insertElements(start, count, resetNewElements = true) { - const meta = this._cachedMeta; - const data = meta.data; - const end = start + count; - let i; - const move = (arr) => { - arr.length += count; - for (i = arr.length - 1; i >= end; i--) { - arr[i] = arr[i - count]; - } - }; - move(data); - for (i = start; i < end; ++i) { - data[i] = new this.dataElementType(); - } - if (this._parsing) { - move(meta._parsed); - } - this.parse(start, count); - if (resetNewElements) { - this.updateElements(data, start, count, 'reset'); - } - } - updateElements(element, start, count, mode) {} - _removeElements(start, count) { - const meta = this._cachedMeta; - if (this._parsing) { - const removed = meta._parsed.splice(start, count); - if (meta._stacked) { - clearStacks(meta, removed); - } - } - meta.data.splice(start, count); - } - _sync(args) { - if (this._parsing) { - this._syncList.push(args); - } else { - const [method, arg1, arg2] = args; - this[method](arg1, arg2); - } - this.chart._dataChanges.push([this.index, ...args]); - } - _onDataPush() { - const count = arguments.length; - this._sync(['_insertElements', this.getDataset().data.length - count, count]); - } - _onDataPop() { - this._sync(['_removeElements', this._cachedMeta.data.length - 1, 1]); - } - _onDataShift() { - this._sync(['_removeElements', 0, 1]); - } - _onDataSplice(start, count) { - if (count) { - this._sync(['_removeElements', start, count]); - } - const newCount = arguments.length - 2; - if (newCount) { - this._sync(['_insertElements', start, newCount]); - } - } - _onDataUnshift() { - this._sync(['_insertElements', 0, arguments.length]); - } -} -DatasetController.defaults = {}; -DatasetController.prototype.datasetElementType = null; -DatasetController.prototype.dataElementType = null; - -class Element { - constructor() { - this.x = undefined; - this.y = undefined; - this.active = false; - this.options = undefined; - this.$animations = undefined; - } - tooltipPosition(useFinalPosition) { - const {x, y} = this.getProps(['x', 'y'], useFinalPosition); - return {x, y}; - } - hasValue() { - return isNumber(this.x) && isNumber(this.y); - } - getProps(props, final) { - const anims = this.$animations; - if (!final || !anims) { - return this; - } - const ret = {}; - props.forEach(prop => { - ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop]; - }); - return ret; - } -} -Element.defaults = {}; -Element.defaultRoutes = undefined; - -const formatters = { - values(value) { - return isArray(value) ? value : '' + value; - }, - numeric(tickValue, index, ticks) { - if (tickValue === 0) { - return '0'; - } - const locale = this.chart.options.locale; - let notation; - let delta = tickValue; - if (ticks.length > 1) { - const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value)); - if (maxTick < 1e-4 || maxTick > 1e+15) { - notation = 'scientific'; - } - delta = calculateDelta(tickValue, ticks); - } - const logDelta = log10(Math.abs(delta)); - const numDecimal = Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0); - const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal}; - Object.assign(options, this.options.ticks.format); - return formatNumber(tickValue, locale, options); - }, - logarithmic(tickValue, index, ticks) { - if (tickValue === 0) { - return '0'; - } - const remain = tickValue / (Math.pow(10, Math.floor(log10(tickValue)))); - if (remain === 1 || remain === 2 || remain === 5) { - return formatters.numeric.call(this, tickValue, index, ticks); - } - return ''; - } -}; -function calculateDelta(tickValue, ticks) { - let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value; - if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) { - delta = tickValue - Math.floor(tickValue); - } - return delta; -} -var Ticks = {formatters}; - -defaults.set('scale', { - display: true, - offset: false, - reverse: false, - beginAtZero: false, - bounds: 'ticks', - grace: 0, - grid: { - display: true, - lineWidth: 1, - drawBorder: true, - drawOnChartArea: true, - drawTicks: true, - tickLength: 8, - tickWidth: (_ctx, options) => options.lineWidth, - tickColor: (_ctx, options) => options.color, - offset: false, - borderDash: [], - borderDashOffset: 0.0, - borderWidth: 1 - }, - title: { - display: false, - text: '', - padding: { - top: 4, - bottom: 4 - } - }, - ticks: { - minRotation: 0, - maxRotation: 50, - mirror: false, - textStrokeWidth: 0, - textStrokeColor: '', - padding: 3, - display: true, - autoSkip: true, - autoSkipPadding: 3, - labelOffset: 0, - callback: Ticks.formatters.values, - minor: {}, - major: {}, - align: 'center', - crossAlign: 'near', - showLabelBackdrop: false, - backdropColor: 'rgba(255, 255, 255, 0.75)', - backdropPadding: 2, - } -}); -defaults.route('scale.ticks', 'color', '', 'color'); -defaults.route('scale.grid', 'color', '', 'borderColor'); -defaults.route('scale.grid', 'borderColor', '', 'borderColor'); -defaults.route('scale.title', 'color', '', 'color'); -defaults.describe('scale', { - _fallback: false, - _scriptable: (name) => !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser', - _indexable: (name) => name !== 'borderDash' && name !== 'tickBorderDash', -}); -defaults.describe('scales', { - _fallback: 'scale', -}); -defaults.describe('scale.ticks', { - _scriptable: (name) => name !== 'backdropPadding' && name !== 'callback', - _indexable: (name) => name !== 'backdropPadding', -}); - -function autoSkip(scale, ticks) { - const tickOpts = scale.options.ticks; - const ticksLimit = tickOpts.maxTicksLimit || determineMaxTicks(scale); - const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : []; - const numMajorIndices = majorIndices.length; - const first = majorIndices[0]; - const last = majorIndices[numMajorIndices - 1]; - const newTicks = []; - if (numMajorIndices > ticksLimit) { - skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit); - return newTicks; - } - const spacing = calculateSpacing(majorIndices, ticks, ticksLimit); - if (numMajorIndices > 0) { - let i, ilen; - const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null; - skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first); - for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) { - skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]); - } - skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing); - return newTicks; - } - skip(ticks, newTicks, spacing); - return newTicks; -} -function determineMaxTicks(scale) { - const offset = scale.options.offset; - const tickLength = scale._tickSize(); - const maxScale = scale._length / tickLength + (offset ? 0 : 1); - const maxChart = scale._maxLength / tickLength; - return Math.floor(Math.min(maxScale, maxChart)); -} -function calculateSpacing(majorIndices, ticks, ticksLimit) { - const evenMajorSpacing = getEvenSpacing(majorIndices); - const spacing = ticks.length / ticksLimit; - if (!evenMajorSpacing) { - return Math.max(spacing, 1); - } - const factors = _factorize(evenMajorSpacing); - for (let i = 0, ilen = factors.length - 1; i < ilen; i++) { - const factor = factors[i]; - if (factor > spacing) { - return factor; - } - } - return Math.max(spacing, 1); -} -function getMajorIndices(ticks) { - const result = []; - let i, ilen; - for (i = 0, ilen = ticks.length; i < ilen; i++) { - if (ticks[i].major) { - result.push(i); - } - } - return result; -} -function skipMajors(ticks, newTicks, majorIndices, spacing) { - let count = 0; - let next = majorIndices[0]; - let i; - spacing = Math.ceil(spacing); - for (i = 0; i < ticks.length; i++) { - if (i === next) { - newTicks.push(ticks[i]); - count++; - next = majorIndices[count * spacing]; - } - } -} -function skip(ticks, newTicks, spacing, majorStart, majorEnd) { - const start = valueOrDefault(majorStart, 0); - const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length); - let count = 0; - let length, i, next; - spacing = Math.ceil(spacing); - if (majorEnd) { - length = majorEnd - majorStart; - spacing = length / Math.floor(length / spacing); - } - next = start; - while (next < 0) { - count++; - next = Math.round(start + count * spacing); - } - for (i = Math.max(start, 0); i < end; i++) { - if (i === next) { - newTicks.push(ticks[i]); - count++; - next = Math.round(start + count * spacing); - } - } -} -function getEvenSpacing(arr) { - const len = arr.length; - let i, diff; - if (len < 2) { - return false; - } - for (diff = arr[0], i = 1; i < len; ++i) { - if (arr[i] - arr[i - 1] !== diff) { - return false; - } - } - return diff; -} - -const reverseAlign = (align) => align === 'left' ? 'right' : align === 'right' ? 'left' : align; -const offsetFromEdge = (scale, edge, offset) => edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset; -function sample(arr, numItems) { - const result = []; - const increment = arr.length / numItems; - const len = arr.length; - let i = 0; - for (; i < len; i += increment) { - result.push(arr[Math.floor(i)]); - } - return result; -} -function getPixelForGridLine(scale, index, offsetGridLines) { - const length = scale.ticks.length; - const validIndex = Math.min(index, length - 1); - const start = scale._startPixel; - const end = scale._endPixel; - const epsilon = 1e-6; - let lineValue = scale.getPixelForTick(validIndex); - let offset; - if (offsetGridLines) { - if (length === 1) { - offset = Math.max(lineValue - start, end - lineValue); - } else if (index === 0) { - offset = (scale.getPixelForTick(1) - lineValue) / 2; - } else { - offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2; - } - lineValue += validIndex < index ? offset : -offset; - if (lineValue < start - epsilon || lineValue > end + epsilon) { - return; - } - } - return lineValue; -} -function garbageCollect(caches, length) { - each(caches, (cache) => { - const gc = cache.gc; - const gcLen = gc.length / 2; - let i; - if (gcLen > length) { - for (i = 0; i < gcLen; ++i) { - delete cache.data[gc[i]]; - } - gc.splice(0, gcLen); - } - }); -} -function getTickMarkLength(options) { - return options.drawTicks ? options.tickLength : 0; -} -function getTitleHeight(options, fallback) { - if (!options.display) { - return 0; - } - const font = toFont(options.font, fallback); - const padding = toPadding(options.padding); - const lines = isArray(options.text) ? options.text.length : 1; - return (lines * font.lineHeight) + padding.height; -} -function createScaleContext(parent, scale) { - return createContext(parent, { - scale, - type: 'scale' - }); -} -function createTickContext(parent, index, tick) { - return createContext(parent, { - tick, - index, - type: 'tick' - }); -} -function titleAlign(align, position, reverse) { - let ret = _toLeftRightCenter(align); - if ((reverse && position !== 'right') || (!reverse && position === 'right')) { - ret = reverseAlign(ret); - } - return ret; -} -function titleArgs(scale, offset, position, align) { - const {top, left, bottom, right, chart} = scale; - const {chartArea, scales} = chart; - let rotation = 0; - let maxWidth, titleX, titleY; - const height = bottom - top; - const width = right - left; - if (scale.isHorizontal()) { - titleX = _alignStartEnd(align, left, right); - if (isObject(position)) { - const positionAxisID = Object.keys(position)[0]; - const value = position[positionAxisID]; - titleY = scales[positionAxisID].getPixelForValue(value) + height - offset; - } else if (position === 'center') { - titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset; - } else { - titleY = offsetFromEdge(scale, position, offset); - } - maxWidth = right - left; - } else { - if (isObject(position)) { - const positionAxisID = Object.keys(position)[0]; - const value = position[positionAxisID]; - titleX = scales[positionAxisID].getPixelForValue(value) - width + offset; - } else if (position === 'center') { - titleX = (chartArea.left + chartArea.right) / 2 - width + offset; - } else { - titleX = offsetFromEdge(scale, position, offset); - } - titleY = _alignStartEnd(align, bottom, top); - rotation = position === 'left' ? -HALF_PI : HALF_PI; - } - return {titleX, titleY, maxWidth, rotation}; -} -class Scale extends Element { - constructor(cfg) { - super(); - this.id = cfg.id; - this.type = cfg.type; - this.options = undefined; - this.ctx = cfg.ctx; - this.chart = cfg.chart; - this.top = undefined; - this.bottom = undefined; - this.left = undefined; - this.right = undefined; - this.width = undefined; - this.height = undefined; - this._margins = { - left: 0, - right: 0, - top: 0, - bottom: 0 - }; - this.maxWidth = undefined; - this.maxHeight = undefined; - this.paddingTop = undefined; - this.paddingBottom = undefined; - this.paddingLeft = undefined; - this.paddingRight = undefined; - this.axis = undefined; - this.labelRotation = undefined; - this.min = undefined; - this.max = undefined; - this._range = undefined; - this.ticks = []; - this._gridLineItems = null; - this._labelItems = null; - this._labelSizes = null; - this._length = 0; - this._maxLength = 0; - this._longestTextCache = {}; - this._startPixel = undefined; - this._endPixel = undefined; - this._reversePixels = false; - this._userMax = undefined; - this._userMin = undefined; - this._suggestedMax = undefined; - this._suggestedMin = undefined; - this._ticksLength = 0; - this._borderValue = 0; - this._cache = {}; - this._dataLimitsCached = false; - this.$context = undefined; - } - init(options) { - this.options = options.setContext(this.getContext()); - this.axis = options.axis; - this._userMin = this.parse(options.min); - this._userMax = this.parse(options.max); - this._suggestedMin = this.parse(options.suggestedMin); - this._suggestedMax = this.parse(options.suggestedMax); - } - parse(raw, index) { - return raw; - } - getUserBounds() { - let {_userMin, _userMax, _suggestedMin, _suggestedMax} = this; - _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY); - _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY); - _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY); - _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY); - return { - min: finiteOrDefault(_userMin, _suggestedMin), - max: finiteOrDefault(_userMax, _suggestedMax), - minDefined: isNumberFinite(_userMin), - maxDefined: isNumberFinite(_userMax) - }; - } - getMinMax(canStack) { - let {min, max, minDefined, maxDefined} = this.getUserBounds(); - let range; - if (minDefined && maxDefined) { - return {min, max}; - } - const metas = this.getMatchingVisibleMetas(); - for (let i = 0, ilen = metas.length; i < ilen; ++i) { - range = metas[i].controller.getMinMax(this, canStack); - if (!minDefined) { - min = Math.min(min, range.min); - } - if (!maxDefined) { - max = Math.max(max, range.max); - } - } - min = maxDefined && min > max ? max : min; - max = minDefined && min > max ? min : max; - return { - min: finiteOrDefault(min, finiteOrDefault(max, min)), - max: finiteOrDefault(max, finiteOrDefault(min, max)) - }; - } - getPadding() { - return { - left: this.paddingLeft || 0, - top: this.paddingTop || 0, - right: this.paddingRight || 0, - bottom: this.paddingBottom || 0 - }; - } - getTicks() { - return this.ticks; - } - getLabels() { - const data = this.chart.data; - return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || []; - } - beforeLayout() { - this._cache = {}; - this._dataLimitsCached = false; - } - beforeUpdate() { - callback(this.options.beforeUpdate, [this]); - } - update(maxWidth, maxHeight, margins) { - const {beginAtZero, grace, ticks: tickOpts} = this.options; - const sampleSize = tickOpts.sampleSize; - this.beforeUpdate(); - this.maxWidth = maxWidth; - this.maxHeight = maxHeight; - this._margins = margins = Object.assign({ - left: 0, - right: 0, - top: 0, - bottom: 0 - }, margins); - this.ticks = null; - this._labelSizes = null; - this._gridLineItems = null; - this._labelItems = null; - this.beforeSetDimensions(); - this.setDimensions(); - this.afterSetDimensions(); - this._maxLength = this.isHorizontal() - ? this.width + margins.left + margins.right - : this.height + margins.top + margins.bottom; - if (!this._dataLimitsCached) { - this.beforeDataLimits(); - this.determineDataLimits(); - this.afterDataLimits(); - this._range = _addGrace(this, grace, beginAtZero); - this._dataLimitsCached = true; - } - this.beforeBuildTicks(); - this.ticks = this.buildTicks() || []; - this.afterBuildTicks(); - const samplingEnabled = sampleSize < this.ticks.length; - this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks); - this.configure(); - this.beforeCalculateLabelRotation(); - this.calculateLabelRotation(); - this.afterCalculateLabelRotation(); - if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) { - this.ticks = autoSkip(this, this.ticks); - this._labelSizes = null; - } - if (samplingEnabled) { - this._convertTicksToLabels(this.ticks); - } - this.beforeFit(); - this.fit(); - this.afterFit(); - this.afterUpdate(); - } - configure() { - let reversePixels = this.options.reverse; - let startPixel, endPixel; - if (this.isHorizontal()) { - startPixel = this.left; - endPixel = this.right; - } else { - startPixel = this.top; - endPixel = this.bottom; - reversePixels = !reversePixels; - } - this._startPixel = startPixel; - this._endPixel = endPixel; - this._reversePixels = reversePixels; - this._length = endPixel - startPixel; - this._alignToPixels = this.options.alignToPixels; - } - afterUpdate() { - callback(this.options.afterUpdate, [this]); - } - beforeSetDimensions() { - callback(this.options.beforeSetDimensions, [this]); - } - setDimensions() { - if (this.isHorizontal()) { - this.width = this.maxWidth; - this.left = 0; - this.right = this.width; - } else { - this.height = this.maxHeight; - this.top = 0; - this.bottom = this.height; - } - this.paddingLeft = 0; - this.paddingTop = 0; - this.paddingRight = 0; - this.paddingBottom = 0; - } - afterSetDimensions() { - callback(this.options.afterSetDimensions, [this]); - } - _callHooks(name) { - this.chart.notifyPlugins(name, this.getContext()); - callback(this.options[name], [this]); - } - beforeDataLimits() { - this._callHooks('beforeDataLimits'); - } - determineDataLimits() {} - afterDataLimits() { - this._callHooks('afterDataLimits'); - } - beforeBuildTicks() { - this._callHooks('beforeBuildTicks'); - } - buildTicks() { - return []; - } - afterBuildTicks() { - this._callHooks('afterBuildTicks'); - } - beforeTickToLabelConversion() { - callback(this.options.beforeTickToLabelConversion, [this]); - } - generateTickLabels(ticks) { - const tickOpts = this.options.ticks; - let i, ilen, tick; - for (i = 0, ilen = ticks.length; i < ilen; i++) { - tick = ticks[i]; - tick.label = callback(tickOpts.callback, [tick.value, i, ticks], this); - } - } - afterTickToLabelConversion() { - callback(this.options.afterTickToLabelConversion, [this]); - } - beforeCalculateLabelRotation() { - callback(this.options.beforeCalculateLabelRotation, [this]); - } - calculateLabelRotation() { - const options = this.options; - const tickOpts = options.ticks; - const numTicks = this.ticks.length; - const minRotation = tickOpts.minRotation || 0; - const maxRotation = tickOpts.maxRotation; - let labelRotation = minRotation; - let tickWidth, maxHeight, maxLabelDiagonal; - if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) { - this.labelRotation = minRotation; - return; - } - const labelSizes = this._getLabelSizes(); - const maxLabelWidth = labelSizes.widest.width; - const maxLabelHeight = labelSizes.highest.height; - const maxWidth = _limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth); - tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1); - if (maxLabelWidth + 6 > tickWidth) { - tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1)); - maxHeight = this.maxHeight - getTickMarkLength(options.grid) - - tickOpts.padding - getTitleHeight(options.title, this.chart.options.font); - maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight); - labelRotation = toDegrees(Math.min( - Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)), - Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1)) - )); - labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation)); - } - this.labelRotation = labelRotation; - } - afterCalculateLabelRotation() { - callback(this.options.afterCalculateLabelRotation, [this]); - } - beforeFit() { - callback(this.options.beforeFit, [this]); - } - fit() { - const minSize = { - width: 0, - height: 0 - }; - const {chart, options: {ticks: tickOpts, title: titleOpts, grid: gridOpts}} = this; - const display = this._isVisible(); - const isHorizontal = this.isHorizontal(); - if (display) { - const titleHeight = getTitleHeight(titleOpts, chart.options.font); - if (isHorizontal) { - minSize.width = this.maxWidth; - minSize.height = getTickMarkLength(gridOpts) + titleHeight; - } else { - minSize.height = this.maxHeight; - minSize.width = getTickMarkLength(gridOpts) + titleHeight; - } - if (tickOpts.display && this.ticks.length) { - const {first, last, widest, highest} = this._getLabelSizes(); - const tickPadding = tickOpts.padding * 2; - const angleRadians = toRadians(this.labelRotation); - const cos = Math.cos(angleRadians); - const sin = Math.sin(angleRadians); - if (isHorizontal) { - const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height; - minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding); - } else { - const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height; - minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding); - } - this._calculatePadding(first, last, sin, cos); - } - } - this._handleMargins(); - if (isHorizontal) { - this.width = this._length = chart.width - this._margins.left - this._margins.right; - this.height = minSize.height; - } else { - this.width = minSize.width; - this.height = this._length = chart.height - this._margins.top - this._margins.bottom; - } - } - _calculatePadding(first, last, sin, cos) { - const {ticks: {align, padding}, position} = this.options; - const isRotated = this.labelRotation !== 0; - const labelsBelowTicks = position !== 'top' && this.axis === 'x'; - if (this.isHorizontal()) { - const offsetLeft = this.getPixelForTick(0) - this.left; - const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1); - let paddingLeft = 0; - let paddingRight = 0; - if (isRotated) { - if (labelsBelowTicks) { - paddingLeft = cos * first.width; - paddingRight = sin * last.height; - } else { - paddingLeft = sin * first.height; - paddingRight = cos * last.width; - } - } else if (align === 'start') { - paddingRight = last.width; - } else if (align === 'end') { - paddingLeft = first.width; - } else { - paddingLeft = first.width / 2; - paddingRight = last.width / 2; - } - this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0); - this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0); - } else { - let paddingTop = last.height / 2; - let paddingBottom = first.height / 2; - if (align === 'start') { - paddingTop = 0; - paddingBottom = first.height; - } else if (align === 'end') { - paddingTop = last.height; - paddingBottom = 0; - } - this.paddingTop = paddingTop + padding; - this.paddingBottom = paddingBottom + padding; - } - } - _handleMargins() { - if (this._margins) { - this._margins.left = Math.max(this.paddingLeft, this._margins.left); - this._margins.top = Math.max(this.paddingTop, this._margins.top); - this._margins.right = Math.max(this.paddingRight, this._margins.right); - this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom); - } - } - afterFit() { - callback(this.options.afterFit, [this]); - } - isHorizontal() { - const {axis, position} = this.options; - return position === 'top' || position === 'bottom' || axis === 'x'; - } - isFullSize() { - return this.options.fullSize; - } - _convertTicksToLabels(ticks) { - this.beforeTickToLabelConversion(); - this.generateTickLabels(ticks); - let i, ilen; - for (i = 0, ilen = ticks.length; i < ilen; i++) { - if (isNullOrUndef(ticks[i].label)) { - ticks.splice(i, 1); - ilen--; - i--; - } - } - this.afterTickToLabelConversion(); - } - _getLabelSizes() { - let labelSizes = this._labelSizes; - if (!labelSizes) { - const sampleSize = this.options.ticks.sampleSize; - let ticks = this.ticks; - if (sampleSize < ticks.length) { - ticks = sample(ticks, sampleSize); - } - this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length); - } - return labelSizes; - } - _computeLabelSizes(ticks, length) { - const {ctx, _longestTextCache: caches} = this; - const widths = []; - const heights = []; - let widestLabelSize = 0; - let highestLabelSize = 0; - let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel; - for (i = 0; i < length; ++i) { - label = ticks[i].label; - tickFont = this._resolveTickFontOptions(i); - ctx.font = fontString = tickFont.string; - cache = caches[fontString] = caches[fontString] || {data: {}, gc: []}; - lineHeight = tickFont.lineHeight; - width = height = 0; - if (!isNullOrUndef(label) && !isArray(label)) { - width = _measureText(ctx, cache.data, cache.gc, width, label); - height = lineHeight; - } else if (isArray(label)) { - for (j = 0, jlen = label.length; j < jlen; ++j) { - nestedLabel = label[j]; - if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) { - width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel); - height += lineHeight; - } - } - } - widths.push(width); - heights.push(height); - widestLabelSize = Math.max(width, widestLabelSize); - highestLabelSize = Math.max(height, highestLabelSize); - } - garbageCollect(caches, length); - const widest = widths.indexOf(widestLabelSize); - const highest = heights.indexOf(highestLabelSize); - const valueAt = (idx) => ({width: widths[idx] || 0, height: heights[idx] || 0}); - return { - first: valueAt(0), - last: valueAt(length - 1), - widest: valueAt(widest), - highest: valueAt(highest), - widths, - heights, - }; - } - getLabelForValue(value) { - return value; - } - getPixelForValue(value, index) { - return NaN; - } - getValueForPixel(pixel) {} - getPixelForTick(index) { - const ticks = this.ticks; - if (index < 0 || index > ticks.length - 1) { - return null; - } - return this.getPixelForValue(ticks[index].value); - } - getPixelForDecimal(decimal) { - if (this._reversePixels) { - decimal = 1 - decimal; - } - const pixel = this._startPixel + decimal * this._length; - return _int16Range(this._alignToPixels ? _alignPixel(this.chart, pixel, 0) : pixel); - } - getDecimalForPixel(pixel) { - const decimal = (pixel - this._startPixel) / this._length; - return this._reversePixels ? 1 - decimal : decimal; - } - getBasePixel() { - return this.getPixelForValue(this.getBaseValue()); - } - getBaseValue() { - const {min, max} = this; - return min < 0 && max < 0 ? max : - min > 0 && max > 0 ? min : - 0; - } - getContext(index) { - const ticks = this.ticks || []; - if (index >= 0 && index < ticks.length) { - const tick = ticks[index]; - return tick.$context || - (tick.$context = createTickContext(this.getContext(), index, tick)); - } - return this.$context || - (this.$context = createScaleContext(this.chart.getContext(), this)); - } - _tickSize() { - const optionTicks = this.options.ticks; - const rot = toRadians(this.labelRotation); - const cos = Math.abs(Math.cos(rot)); - const sin = Math.abs(Math.sin(rot)); - const labelSizes = this._getLabelSizes(); - const padding = optionTicks.autoSkipPadding || 0; - const w = labelSizes ? labelSizes.widest.width + padding : 0; - const h = labelSizes ? labelSizes.highest.height + padding : 0; - return this.isHorizontal() - ? h * cos > w * sin ? w / cos : h / sin - : h * sin < w * cos ? h / cos : w / sin; - } - _isVisible() { - const display = this.options.display; - if (display !== 'auto') { - return !!display; - } - return this.getMatchingVisibleMetas().length > 0; - } - _computeGridLineItems(chartArea) { - const axis = this.axis; - const chart = this.chart; - const options = this.options; - const {grid, position} = options; - const offset = grid.offset; - const isHorizontal = this.isHorizontal(); - const ticks = this.ticks; - const ticksLength = ticks.length + (offset ? 1 : 0); - const tl = getTickMarkLength(grid); - const items = []; - const borderOpts = grid.setContext(this.getContext()); - const axisWidth = borderOpts.drawBorder ? borderOpts.borderWidth : 0; - const axisHalfWidth = axisWidth / 2; - const alignBorderValue = function(pixel) { - return _alignPixel(chart, pixel, axisWidth); - }; - let borderValue, i, lineValue, alignedLineValue; - let tx1, ty1, tx2, ty2, x1, y1, x2, y2; - if (position === 'top') { - borderValue = alignBorderValue(this.bottom); - ty1 = this.bottom - tl; - ty2 = borderValue - axisHalfWidth; - y1 = alignBorderValue(chartArea.top) + axisHalfWidth; - y2 = chartArea.bottom; - } else if (position === 'bottom') { - borderValue = alignBorderValue(this.top); - y1 = chartArea.top; - y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth; - ty1 = borderValue + axisHalfWidth; - ty2 = this.top + tl; - } else if (position === 'left') { - borderValue = alignBorderValue(this.right); - tx1 = this.right - tl; - tx2 = borderValue - axisHalfWidth; - x1 = alignBorderValue(chartArea.left) + axisHalfWidth; - x2 = chartArea.right; - } else if (position === 'right') { - borderValue = alignBorderValue(this.left); - x1 = chartArea.left; - x2 = alignBorderValue(chartArea.right) - axisHalfWidth; - tx1 = borderValue + axisHalfWidth; - tx2 = this.left + tl; - } else if (axis === 'x') { - if (position === 'center') { - borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5); - } else if (isObject(position)) { - const positionAxisID = Object.keys(position)[0]; - const value = position[positionAxisID]; - borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value)); - } - y1 = chartArea.top; - y2 = chartArea.bottom; - ty1 = borderValue + axisHalfWidth; - ty2 = ty1 + tl; - } else if (axis === 'y') { - if (position === 'center') { - borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2); - } else if (isObject(position)) { - const positionAxisID = Object.keys(position)[0]; - const value = position[positionAxisID]; - borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value)); - } - tx1 = borderValue - axisHalfWidth; - tx2 = tx1 - tl; - x1 = chartArea.left; - x2 = chartArea.right; - } - const limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength); - const step = Math.max(1, Math.ceil(ticksLength / limit)); - for (i = 0; i < ticksLength; i += step) { - const optsAtIndex = grid.setContext(this.getContext(i)); - const lineWidth = optsAtIndex.lineWidth; - const lineColor = optsAtIndex.color; - const borderDash = grid.borderDash || []; - const borderDashOffset = optsAtIndex.borderDashOffset; - const tickWidth = optsAtIndex.tickWidth; - const tickColor = optsAtIndex.tickColor; - const tickBorderDash = optsAtIndex.tickBorderDash || []; - const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset; - lineValue = getPixelForGridLine(this, i, offset); - if (lineValue === undefined) { - continue; - } - alignedLineValue = _alignPixel(chart, lineValue, lineWidth); - if (isHorizontal) { - tx1 = tx2 = x1 = x2 = alignedLineValue; - } else { - ty1 = ty2 = y1 = y2 = alignedLineValue; - } - items.push({ - tx1, - ty1, - tx2, - ty2, - x1, - y1, - x2, - y2, - width: lineWidth, - color: lineColor, - borderDash, - borderDashOffset, - tickWidth, - tickColor, - tickBorderDash, - tickBorderDashOffset, - }); - } - this._ticksLength = ticksLength; - this._borderValue = borderValue; - return items; - } - _computeLabelItems(chartArea) { - const axis = this.axis; - const options = this.options; - const {position, ticks: optionTicks} = options; - const isHorizontal = this.isHorizontal(); - const ticks = this.ticks; - const {align, crossAlign, padding, mirror} = optionTicks; - const tl = getTickMarkLength(options.grid); - const tickAndPadding = tl + padding; - const hTickAndPadding = mirror ? -padding : tickAndPadding; - const rotation = -toRadians(this.labelRotation); - const items = []; - let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset; - let textBaseline = 'middle'; - if (position === 'top') { - y = this.bottom - hTickAndPadding; - textAlign = this._getXAxisLabelAlignment(); - } else if (position === 'bottom') { - y = this.top + hTickAndPadding; - textAlign = this._getXAxisLabelAlignment(); - } else if (position === 'left') { - const ret = this._getYAxisLabelAlignment(tl); - textAlign = ret.textAlign; - x = ret.x; - } else if (position === 'right') { - const ret = this._getYAxisLabelAlignment(tl); - textAlign = ret.textAlign; - x = ret.x; - } else if (axis === 'x') { - if (position === 'center') { - y = ((chartArea.top + chartArea.bottom) / 2) + tickAndPadding; - } else if (isObject(position)) { - const positionAxisID = Object.keys(position)[0]; - const value = position[positionAxisID]; - y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding; - } - textAlign = this._getXAxisLabelAlignment(); - } else if (axis === 'y') { - if (position === 'center') { - x = ((chartArea.left + chartArea.right) / 2) - tickAndPadding; - } else if (isObject(position)) { - const positionAxisID = Object.keys(position)[0]; - const value = position[positionAxisID]; - x = this.chart.scales[positionAxisID].getPixelForValue(value); - } - textAlign = this._getYAxisLabelAlignment(tl).textAlign; - } - if (axis === 'y') { - if (align === 'start') { - textBaseline = 'top'; - } else if (align === 'end') { - textBaseline = 'bottom'; - } - } - const labelSizes = this._getLabelSizes(); - for (i = 0, ilen = ticks.length; i < ilen; ++i) { - tick = ticks[i]; - label = tick.label; - const optsAtIndex = optionTicks.setContext(this.getContext(i)); - pixel = this.getPixelForTick(i) + optionTicks.labelOffset; - font = this._resolveTickFontOptions(i); - lineHeight = font.lineHeight; - lineCount = isArray(label) ? label.length : 1; - const halfCount = lineCount / 2; - const color = optsAtIndex.color; - const strokeColor = optsAtIndex.textStrokeColor; - const strokeWidth = optsAtIndex.textStrokeWidth; - if (isHorizontal) { - x = pixel; - if (position === 'top') { - if (crossAlign === 'near' || rotation !== 0) { - textOffset = -lineCount * lineHeight + lineHeight / 2; - } else if (crossAlign === 'center') { - textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight; - } else { - textOffset = -labelSizes.highest.height + lineHeight / 2; - } - } else { - if (crossAlign === 'near' || rotation !== 0) { - textOffset = lineHeight / 2; - } else if (crossAlign === 'center') { - textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight; - } else { - textOffset = labelSizes.highest.height - lineCount * lineHeight; - } - } - if (mirror) { - textOffset *= -1; - } - } else { - y = pixel; - textOffset = (1 - lineCount) * lineHeight / 2; - } - let backdrop; - if (optsAtIndex.showLabelBackdrop) { - const labelPadding = toPadding(optsAtIndex.backdropPadding); - const height = labelSizes.heights[i]; - const width = labelSizes.widths[i]; - let top = y + textOffset - labelPadding.top; - let left = x - labelPadding.left; - switch (textBaseline) { - case 'middle': - top -= height / 2; - break; - case 'bottom': - top -= height; - break; - } - switch (textAlign) { - case 'center': - left -= width / 2; - break; - case 'right': - left -= width; - break; - } - backdrop = { - left, - top, - width: width + labelPadding.width, - height: height + labelPadding.height, - color: optsAtIndex.backdropColor, - }; - } - items.push({ - rotation, - label, - font, - color, - strokeColor, - strokeWidth, - textOffset, - textAlign, - textBaseline, - translation: [x, y], - backdrop, - }); - } - return items; - } - _getXAxisLabelAlignment() { - const {position, ticks} = this.options; - const rotation = -toRadians(this.labelRotation); - if (rotation) { - return position === 'top' ? 'left' : 'right'; - } - let align = 'center'; - if (ticks.align === 'start') { - align = 'left'; - } else if (ticks.align === 'end') { - align = 'right'; - } - return align; - } - _getYAxisLabelAlignment(tl) { - const {position, ticks: {crossAlign, mirror, padding}} = this.options; - const labelSizes = this._getLabelSizes(); - const tickAndPadding = tl + padding; - const widest = labelSizes.widest.width; - let textAlign; - let x; - if (position === 'left') { - if (mirror) { - x = this.right + padding; - if (crossAlign === 'near') { - textAlign = 'left'; - } else if (crossAlign === 'center') { - textAlign = 'center'; - x += (widest / 2); - } else { - textAlign = 'right'; - x += widest; - } - } else { - x = this.right - tickAndPadding; - if (crossAlign === 'near') { - textAlign = 'right'; - } else if (crossAlign === 'center') { - textAlign = 'center'; - x -= (widest / 2); - } else { - textAlign = 'left'; - x = this.left; - } - } - } else if (position === 'right') { - if (mirror) { - x = this.left + padding; - if (crossAlign === 'near') { - textAlign = 'right'; - } else if (crossAlign === 'center') { - textAlign = 'center'; - x -= (widest / 2); - } else { - textAlign = 'left'; - x -= widest; - } - } else { - x = this.left + tickAndPadding; - if (crossAlign === 'near') { - textAlign = 'left'; - } else if (crossAlign === 'center') { - textAlign = 'center'; - x += widest / 2; - } else { - textAlign = 'right'; - x = this.right; - } - } - } else { - textAlign = 'right'; - } - return {textAlign, x}; - } - _computeLabelArea() { - if (this.options.ticks.mirror) { - return; - } - const chart = this.chart; - const position = this.options.position; - if (position === 'left' || position === 'right') { - return {top: 0, left: this.left, bottom: chart.height, right: this.right}; - } if (position === 'top' || position === 'bottom') { - return {top: this.top, left: 0, bottom: this.bottom, right: chart.width}; - } - } - drawBackground() { - const {ctx, options: {backgroundColor}, left, top, width, height} = this; - if (backgroundColor) { - ctx.save(); - ctx.fillStyle = backgroundColor; - ctx.fillRect(left, top, width, height); - ctx.restore(); - } - } - getLineWidthForValue(value) { - const grid = this.options.grid; - if (!this._isVisible() || !grid.display) { - return 0; - } - const ticks = this.ticks; - const index = ticks.findIndex(t => t.value === value); - if (index >= 0) { - const opts = grid.setContext(this.getContext(index)); - return opts.lineWidth; - } - return 0; - } - drawGrid(chartArea) { - const grid = this.options.grid; - const ctx = this.ctx; - const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea)); - let i, ilen; - const drawLine = (p1, p2, style) => { - if (!style.width || !style.color) { - return; - } - ctx.save(); - ctx.lineWidth = style.width; - ctx.strokeStyle = style.color; - ctx.setLineDash(style.borderDash || []); - ctx.lineDashOffset = style.borderDashOffset; - ctx.beginPath(); - ctx.moveTo(p1.x, p1.y); - ctx.lineTo(p2.x, p2.y); - ctx.stroke(); - ctx.restore(); - }; - if (grid.display) { - for (i = 0, ilen = items.length; i < ilen; ++i) { - const item = items[i]; - if (grid.drawOnChartArea) { - drawLine( - {x: item.x1, y: item.y1}, - {x: item.x2, y: item.y2}, - item - ); - } - if (grid.drawTicks) { - drawLine( - {x: item.tx1, y: item.ty1}, - {x: item.tx2, y: item.ty2}, - { - color: item.tickColor, - width: item.tickWidth, - borderDash: item.tickBorderDash, - borderDashOffset: item.tickBorderDashOffset - } - ); - } - } - } - } - drawBorder() { - const {chart, ctx, options: {grid}} = this; - const borderOpts = grid.setContext(this.getContext()); - const axisWidth = grid.drawBorder ? borderOpts.borderWidth : 0; - if (!axisWidth) { - return; - } - const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth; - const borderValue = this._borderValue; - let x1, x2, y1, y2; - if (this.isHorizontal()) { - x1 = _alignPixel(chart, this.left, axisWidth) - axisWidth / 2; - x2 = _alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2; - y1 = y2 = borderValue; - } else { - y1 = _alignPixel(chart, this.top, axisWidth) - axisWidth / 2; - y2 = _alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2; - x1 = x2 = borderValue; - } - ctx.save(); - ctx.lineWidth = borderOpts.borderWidth; - ctx.strokeStyle = borderOpts.borderColor; - ctx.beginPath(); - ctx.moveTo(x1, y1); - ctx.lineTo(x2, y2); - ctx.stroke(); - ctx.restore(); - } - drawLabels(chartArea) { - const optionTicks = this.options.ticks; - if (!optionTicks.display) { - return; - } - const ctx = this.ctx; - const area = this._computeLabelArea(); - if (area) { - clipArea(ctx, area); - } - const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea)); - let i, ilen; - for (i = 0, ilen = items.length; i < ilen; ++i) { - const item = items[i]; - const tickFont = item.font; - const label = item.label; - if (item.backdrop) { - ctx.fillStyle = item.backdrop.color; - ctx.fillRect(item.backdrop.left, item.backdrop.top, item.backdrop.width, item.backdrop.height); - } - let y = item.textOffset; - renderText(ctx, label, 0, y, tickFont, item); - } - if (area) { - unclipArea(ctx); - } - } - drawTitle() { - const {ctx, options: {position, title, reverse}} = this; - if (!title.display) { - return; - } - const font = toFont(title.font); - const padding = toPadding(title.padding); - const align = title.align; - let offset = font.lineHeight / 2; - if (position === 'bottom' || position === 'center' || isObject(position)) { - offset += padding.bottom; - if (isArray(title.text)) { - offset += font.lineHeight * (title.text.length - 1); - } - } else { - offset += padding.top; - } - const {titleX, titleY, maxWidth, rotation} = titleArgs(this, offset, position, align); - renderText(ctx, title.text, 0, 0, font, { - color: title.color, - maxWidth, - rotation, - textAlign: titleAlign(align, position, reverse), - textBaseline: 'middle', - translation: [titleX, titleY], - }); - } - draw(chartArea) { - if (!this._isVisible()) { - return; - } - this.drawBackground(); - this.drawGrid(chartArea); - this.drawBorder(); - this.drawTitle(); - this.drawLabels(chartArea); - } - _layers() { - const opts = this.options; - const tz = opts.ticks && opts.ticks.z || 0; - const gz = valueOrDefault(opts.grid && opts.grid.z, -1); - if (!this._isVisible() || this.draw !== Scale.prototype.draw) { - return [{ - z: tz, - draw: (chartArea) => { - this.draw(chartArea); - } - }]; - } - return [{ - z: gz, - draw: (chartArea) => { - this.drawBackground(); - this.drawGrid(chartArea); - this.drawTitle(); - } - }, { - z: gz + 1, - draw: () => { - this.drawBorder(); - } - }, { - z: tz, - draw: (chartArea) => { - this.drawLabels(chartArea); - } - }]; - } - getMatchingVisibleMetas(type) { - const metas = this.chart.getSortedVisibleDatasetMetas(); - const axisID = this.axis + 'AxisID'; - const result = []; - let i, ilen; - for (i = 0, ilen = metas.length; i < ilen; ++i) { - const meta = metas[i]; - if (meta[axisID] === this.id && (!type || meta.type === type)) { - result.push(meta); - } - } - return result; - } - _resolveTickFontOptions(index) { - const opts = this.options.ticks.setContext(this.getContext(index)); - return toFont(opts.font); - } - _maxDigits() { - const fontSize = this._resolveTickFontOptions(0).lineHeight; - return (this.isHorizontal() ? this.width : this.height) / fontSize; - } -} - -class TypedRegistry { - constructor(type, scope, override) { - this.type = type; - this.scope = scope; - this.override = override; - this.items = Object.create(null); - } - isForType(type) { - return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype); - } - register(item) { - const proto = Object.getPrototypeOf(item); - let parentScope; - if (isIChartComponent(proto)) { - parentScope = this.register(proto); - } - const items = this.items; - const id = item.id; - const scope = this.scope + '.' + id; - if (!id) { - throw new Error('class does not have id: ' + item); - } - if (id in items) { - return scope; - } - items[id] = item; - registerDefaults(item, scope, parentScope); - if (this.override) { - defaults.override(item.id, item.overrides); - } - return scope; - } - get(id) { - return this.items[id]; - } - unregister(item) { - const items = this.items; - const id = item.id; - const scope = this.scope; - if (id in items) { - delete items[id]; - } - if (scope && id in defaults[scope]) { - delete defaults[scope][id]; - if (this.override) { - delete overrides[id]; - } - } - } -} -function registerDefaults(item, scope, parentScope) { - const itemDefaults = merge(Object.create(null), [ - parentScope ? defaults.get(parentScope) : {}, - defaults.get(scope), - item.defaults - ]); - defaults.set(scope, itemDefaults); - if (item.defaultRoutes) { - routeDefaults(scope, item.defaultRoutes); - } - if (item.descriptors) { - defaults.describe(scope, item.descriptors); - } -} -function routeDefaults(scope, routes) { - Object.keys(routes).forEach(property => { - const propertyParts = property.split('.'); - const sourceName = propertyParts.pop(); - const sourceScope = [scope].concat(propertyParts).join('.'); - const parts = routes[property].split('.'); - const targetName = parts.pop(); - const targetScope = parts.join('.'); - defaults.route(sourceScope, sourceName, targetScope, targetName); - }); -} -function isIChartComponent(proto) { - return 'id' in proto && 'defaults' in proto; -} - -class Registry { - constructor() { - this.controllers = new TypedRegistry(DatasetController, 'datasets', true); - this.elements = new TypedRegistry(Element, 'elements'); - this.plugins = new TypedRegistry(Object, 'plugins'); - this.scales = new TypedRegistry(Scale, 'scales'); - this._typedRegistries = [this.controllers, this.scales, this.elements]; - } - add(...args) { - this._each('register', args); - } - remove(...args) { - this._each('unregister', args); - } - addControllers(...args) { - this._each('register', args, this.controllers); - } - addElements(...args) { - this._each('register', args, this.elements); - } - addPlugins(...args) { - this._each('register', args, this.plugins); - } - addScales(...args) { - this._each('register', args, this.scales); - } - getController(id) { - return this._get(id, this.controllers, 'controller'); - } - getElement(id) { - return this._get(id, this.elements, 'element'); - } - getPlugin(id) { - return this._get(id, this.plugins, 'plugin'); - } - getScale(id) { - return this._get(id, this.scales, 'scale'); - } - removeControllers(...args) { - this._each('unregister', args, this.controllers); - } - removeElements(...args) { - this._each('unregister', args, this.elements); - } - removePlugins(...args) { - this._each('unregister', args, this.plugins); - } - removeScales(...args) { - this._each('unregister', args, this.scales); - } - _each(method, args, typedRegistry) { - [...args].forEach(arg => { - const reg = typedRegistry || this._getRegistryForType(arg); - if (typedRegistry || reg.isForType(arg) || (reg === this.plugins && arg.id)) { - this._exec(method, reg, arg); - } else { - each(arg, item => { - const itemReg = typedRegistry || this._getRegistryForType(item); - this._exec(method, itemReg, item); - }); - } - }); - } - _exec(method, registry, component) { - const camelMethod = _capitalize(method); - callback(component['before' + camelMethod], [], component); - registry[method](component); - callback(component['after' + camelMethod], [], component); - } - _getRegistryForType(type) { - for (let i = 0; i < this._typedRegistries.length; i++) { - const reg = this._typedRegistries[i]; - if (reg.isForType(type)) { - return reg; - } - } - return this.plugins; - } - _get(id, typedRegistry, type) { - const item = typedRegistry.get(id); - if (item === undefined) { - throw new Error('"' + id + '" is not a registered ' + type + '.'); - } - return item; - } -} -var registry = new Registry(); - -class PluginService { - constructor() { - this._init = []; - } - notify(chart, hook, args, filter) { - if (hook === 'beforeInit') { - this._init = this._createDescriptors(chart, true); - this._notify(this._init, chart, 'install'); - } - const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart); - const result = this._notify(descriptors, chart, hook, args); - if (hook === 'afterDestroy') { - this._notify(descriptors, chart, 'stop'); - this._notify(this._init, chart, 'uninstall'); - } - return result; - } - _notify(descriptors, chart, hook, args) { - args = args || {}; - for (const descriptor of descriptors) { - const plugin = descriptor.plugin; - const method = plugin[hook]; - const params = [chart, args, descriptor.options]; - if (callback(method, params, plugin) === false && args.cancelable) { - return false; - } - } - return true; - } - invalidate() { - if (!isNullOrUndef(this._cache)) { - this._oldCache = this._cache; - this._cache = undefined; - } - } - _descriptors(chart) { - if (this._cache) { - return this._cache; - } - const descriptors = this._cache = this._createDescriptors(chart); - this._notifyStateChanges(chart); - return descriptors; - } - _createDescriptors(chart, all) { - const config = chart && chart.config; - const options = valueOrDefault(config.options && config.options.plugins, {}); - const plugins = allPlugins(config); - return options === false && !all ? [] : createDescriptors(chart, plugins, options, all); - } - _notifyStateChanges(chart) { - const previousDescriptors = this._oldCache || []; - const descriptors = this._cache; - const diff = (a, b) => a.filter(x => !b.some(y => x.plugin.id === y.plugin.id)); - this._notify(diff(previousDescriptors, descriptors), chart, 'stop'); - this._notify(diff(descriptors, previousDescriptors), chart, 'start'); - } -} -function allPlugins(config) { - const plugins = []; - const keys = Object.keys(registry.plugins.items); - for (let i = 0; i < keys.length; i++) { - plugins.push(registry.getPlugin(keys[i])); - } - const local = config.plugins || []; - for (let i = 0; i < local.length; i++) { - const plugin = local[i]; - if (plugins.indexOf(plugin) === -1) { - plugins.push(plugin); - } - } - return plugins; -} -function getOpts(options, all) { - if (!all && options === false) { - return null; - } - if (options === true) { - return {}; - } - return options; -} -function createDescriptors(chart, plugins, options, all) { - const result = []; - const context = chart.getContext(); - for (let i = 0; i < plugins.length; i++) { - const plugin = plugins[i]; - const id = plugin.id; - const opts = getOpts(options[id], all); - if (opts === null) { - continue; - } - result.push({ - plugin, - options: pluginOpts(chart.config, plugin, opts, context) - }); - } - return result; -} -function pluginOpts(config, plugin, opts, context) { - const keys = config.pluginScopeKeys(plugin); - const scopes = config.getOptionScopes(opts, keys); - return config.createResolver(scopes, context, [''], {scriptable: false, indexable: false, allKeys: true}); -} - -function getIndexAxis(type, options) { - const datasetDefaults = defaults.datasets[type] || {}; - const datasetOptions = (options.datasets || {})[type] || {}; - return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x'; -} -function getAxisFromDefaultScaleID(id, indexAxis) { - let axis = id; - if (id === '_index_') { - axis = indexAxis; - } else if (id === '_value_') { - axis = indexAxis === 'x' ? 'y' : 'x'; - } - return axis; -} -function getDefaultScaleIDFromAxis(axis, indexAxis) { - return axis === indexAxis ? '_index_' : '_value_'; -} -function axisFromPosition(position) { - if (position === 'top' || position === 'bottom') { - return 'x'; - } - if (position === 'left' || position === 'right') { - return 'y'; - } -} -function determineAxis(id, scaleOptions) { - if (id === 'x' || id === 'y') { - return id; - } - return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id.charAt(0).toLowerCase(); -} -function mergeScaleConfig(config, options) { - const chartDefaults = overrides[config.type] || {scales: {}}; - const configScales = options.scales || {}; - const chartIndexAxis = getIndexAxis(config.type, options); - const firstIDs = Object.create(null); - const scales = Object.create(null); - Object.keys(configScales).forEach(id => { - const scaleConf = configScales[id]; - if (!isObject(scaleConf)) { - return console.error(`Invalid scale configuration for scale: ${id}`); - } - if (scaleConf._proxy) { - return console.warn(`Ignoring resolver passed as options for scale: ${id}`); - } - const axis = determineAxis(id, scaleConf); - const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis); - const defaultScaleOptions = chartDefaults.scales || {}; - firstIDs[axis] = firstIDs[axis] || id; - scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, defaultScaleOptions[axis], defaultScaleOptions[defaultId]]); - }); - config.data.datasets.forEach(dataset => { - const type = dataset.type || config.type; - const indexAxis = dataset.indexAxis || getIndexAxis(type, options); - const datasetDefaults = overrides[type] || {}; - const defaultScaleOptions = datasetDefaults.scales || {}; - Object.keys(defaultScaleOptions).forEach(defaultID => { - const axis = getAxisFromDefaultScaleID(defaultID, indexAxis); - const id = dataset[axis + 'AxisID'] || firstIDs[axis] || axis; - scales[id] = scales[id] || Object.create(null); - mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]); - }); - }); - Object.keys(scales).forEach(key => { - const scale = scales[key]; - mergeIf(scale, [defaults.scales[scale.type], defaults.scale]); - }); - return scales; -} -function initOptions(config) { - const options = config.options || (config.options = {}); - options.plugins = valueOrDefault(options.plugins, {}); - options.scales = mergeScaleConfig(config, options); -} -function initData(data) { - data = data || {}; - data.datasets = data.datasets || []; - data.labels = data.labels || []; - return data; -} -function initConfig(config) { - config = config || {}; - config.data = initData(config.data); - initOptions(config); - return config; -} -const keyCache = new Map(); -const keysCached = new Set(); -function cachedKeys(cacheKey, generate) { - let keys = keyCache.get(cacheKey); - if (!keys) { - keys = generate(); - keyCache.set(cacheKey, keys); - keysCached.add(keys); - } - return keys; -} -const addIfFound = (set, obj, key) => { - const opts = resolveObjectKey(obj, key); - if (opts !== undefined) { - set.add(opts); - } -}; -class Config { - constructor(config) { - this._config = initConfig(config); - this._scopeCache = new Map(); - this._resolverCache = new Map(); - } - get platform() { - return this._config.platform; - } - get type() { - return this._config.type; - } - set type(type) { - this._config.type = type; - } - get data() { - return this._config.data; - } - set data(data) { - this._config.data = initData(data); - } - get options() { - return this._config.options; - } - set options(options) { - this._config.options = options; - } - get plugins() { - return this._config.plugins; - } - update() { - const config = this._config; - this.clearCache(); - initOptions(config); - } - clearCache() { - this._scopeCache.clear(); - this._resolverCache.clear(); - } - datasetScopeKeys(datasetType) { - return cachedKeys(datasetType, - () => [[ - `datasets.${datasetType}`, - '' - ]]); - } - datasetAnimationScopeKeys(datasetType, transition) { - return cachedKeys(`${datasetType}.transition.${transition}`, - () => [ - [ - `datasets.${datasetType}.transitions.${transition}`, - `transitions.${transition}`, - ], - [ - `datasets.${datasetType}`, - '' - ] - ]); - } - datasetElementScopeKeys(datasetType, elementType) { - return cachedKeys(`${datasetType}-${elementType}`, - () => [[ - `datasets.${datasetType}.elements.${elementType}`, - `datasets.${datasetType}`, - `elements.${elementType}`, - '' - ]]); - } - pluginScopeKeys(plugin) { - const id = plugin.id; - const type = this.type; - return cachedKeys(`${type}-plugin-${id}`, - () => [[ - `plugins.${id}`, - ...plugin.additionalOptionScopes || [], - ]]); - } - _cachedScopes(mainScope, resetCache) { - const _scopeCache = this._scopeCache; - let cache = _scopeCache.get(mainScope); - if (!cache || resetCache) { - cache = new Map(); - _scopeCache.set(mainScope, cache); - } - return cache; - } - getOptionScopes(mainScope, keyLists, resetCache) { - const {options, type} = this; - const cache = this._cachedScopes(mainScope, resetCache); - const cached = cache.get(keyLists); - if (cached) { - return cached; - } - const scopes = new Set(); - keyLists.forEach(keys => { - if (mainScope) { - scopes.add(mainScope); - keys.forEach(key => addIfFound(scopes, mainScope, key)); - } - keys.forEach(key => addIfFound(scopes, options, key)); - keys.forEach(key => addIfFound(scopes, overrides[type] || {}, key)); - keys.forEach(key => addIfFound(scopes, defaults, key)); - keys.forEach(key => addIfFound(scopes, descriptors, key)); - }); - const array = Array.from(scopes); - if (array.length === 0) { - array.push(Object.create(null)); - } - if (keysCached.has(keyLists)) { - cache.set(keyLists, array); - } - return array; - } - chartOptionScopes() { - const {options, type} = this; - return [ - options, - overrides[type] || {}, - defaults.datasets[type] || {}, - {type}, - defaults, - descriptors - ]; - } - resolveNamedOptions(scopes, names, context, prefixes = ['']) { - const result = {$shared: true}; - const {resolver, subPrefixes} = getResolver(this._resolverCache, scopes, prefixes); - let options = resolver; - if (needContext(resolver, names)) { - result.$shared = false; - context = isFunction(context) ? context() : context; - const subResolver = this.createResolver(scopes, context, subPrefixes); - options = _attachContext(resolver, context, subResolver); - } - for (const prop of names) { - result[prop] = options[prop]; - } - return result; - } - createResolver(scopes, context, prefixes = [''], descriptorDefaults) { - const {resolver} = getResolver(this._resolverCache, scopes, prefixes); - return isObject(context) - ? _attachContext(resolver, context, undefined, descriptorDefaults) - : resolver; - } -} -function getResolver(resolverCache, scopes, prefixes) { - let cache = resolverCache.get(scopes); - if (!cache) { - cache = new Map(); - resolverCache.set(scopes, cache); - } - const cacheKey = prefixes.join(); - let cached = cache.get(cacheKey); - if (!cached) { - const resolver = _createResolver(scopes, prefixes); - cached = { - resolver, - subPrefixes: prefixes.filter(p => !p.toLowerCase().includes('hover')) - }; - cache.set(cacheKey, cached); - } - return cached; -} -const hasFunction = value => isObject(value) - && Object.getOwnPropertyNames(value).reduce((acc, key) => acc || isFunction(value[key]), false); -function needContext(proxy, names) { - const {isScriptable, isIndexable} = _descriptors(proxy); - for (const prop of names) { - const scriptable = isScriptable(prop); - const indexable = isIndexable(prop); - const value = (indexable || scriptable) && proxy[prop]; - if ((scriptable && (isFunction(value) || hasFunction(value))) - || (indexable && isArray(value))) { - return true; - } - } - return false; -} - -var version = "3.7.1"; - -const KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea']; -function positionIsHorizontal(position, axis) { - return position === 'top' || position === 'bottom' || (KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x'); -} -function compare2Level(l1, l2) { - return function(a, b) { - return a[l1] === b[l1] - ? a[l2] - b[l2] - : a[l1] - b[l1]; - }; -} -function onAnimationsComplete(context) { - const chart = context.chart; - const animationOptions = chart.options.animation; - chart.notifyPlugins('afterRender'); - callback(animationOptions && animationOptions.onComplete, [context], chart); -} -function onAnimationProgress(context) { - const chart = context.chart; - const animationOptions = chart.options.animation; - callback(animationOptions && animationOptions.onProgress, [context], chart); -} -function getCanvas(item) { - if (_isDomSupported() && typeof item === 'string') { - item = document.getElementById(item); - } else if (item && item.length) { - item = item[0]; - } - if (item && item.canvas) { - item = item.canvas; - } - return item; -} -const instances = {}; -const getChart = (key) => { - const canvas = getCanvas(key); - return Object.values(instances).filter((c) => c.canvas === canvas).pop(); -}; -function moveNumericKeys(obj, start, move) { - const keys = Object.keys(obj); - for (const key of keys) { - const intKey = +key; - if (intKey >= start) { - const value = obj[key]; - delete obj[key]; - if (move > 0 || intKey > start) { - obj[intKey + move] = value; - } - } - } -} -function determineLastEvent(e, lastEvent, inChartArea, isClick) { - if (!inChartArea || e.type === 'mouseout') { - return null; - } - if (isClick) { - return lastEvent; - } - return e; -} -class Chart { - constructor(item, userConfig) { - const config = this.config = new Config(userConfig); - const initialCanvas = getCanvas(item); - const existingChart = getChart(initialCanvas); - if (existingChart) { - throw new Error( - 'Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' + - ' must be destroyed before the canvas can be reused.' - ); - } - const options = config.createResolver(config.chartOptionScopes(), this.getContext()); - this.platform = new (config.platform || _detectPlatform(initialCanvas))(); - this.platform.updateConfig(config); - const context = this.platform.acquireContext(initialCanvas, options.aspectRatio); - const canvas = context && context.canvas; - const height = canvas && canvas.height; - const width = canvas && canvas.width; - this.id = uid(); - this.ctx = context; - this.canvas = canvas; - this.width = width; - this.height = height; - this._options = options; - this._aspectRatio = this.aspectRatio; - this._layers = []; - this._metasets = []; - this._stacks = undefined; - this.boxes = []; - this.currentDevicePixelRatio = undefined; - this.chartArea = undefined; - this._active = []; - this._lastEvent = undefined; - this._listeners = {}; - this._responsiveListeners = undefined; - this._sortedMetasets = []; - this.scales = {}; - this._plugins = new PluginService(); - this.$proxies = {}; - this._hiddenIndices = {}; - this.attached = false; - this._animationsDisabled = undefined; - this.$context = undefined; - this._doResize = debounce(mode => this.update(mode), options.resizeDelay || 0); - this._dataChanges = []; - instances[this.id] = this; - if (!context || !canvas) { - console.error("Failed to create chart: can't acquire context from the given item"); - return; - } - animator.listen(this, 'complete', onAnimationsComplete); - animator.listen(this, 'progress', onAnimationProgress); - this._initialize(); - if (this.attached) { - this.update(); - } - } - get aspectRatio() { - const {options: {aspectRatio, maintainAspectRatio}, width, height, _aspectRatio} = this; - if (!isNullOrUndef(aspectRatio)) { - return aspectRatio; - } - if (maintainAspectRatio && _aspectRatio) { - return _aspectRatio; - } - return height ? width / height : null; - } - get data() { - return this.config.data; - } - set data(data) { - this.config.data = data; - } - get options() { - return this._options; - } - set options(options) { - this.config.options = options; - } - _initialize() { - this.notifyPlugins('beforeInit'); - if (this.options.responsive) { - this.resize(); - } else { - retinaScale(this, this.options.devicePixelRatio); - } - this.bindEvents(); - this.notifyPlugins('afterInit'); - return this; - } - clear() { - clearCanvas(this.canvas, this.ctx); - return this; - } - stop() { - animator.stop(this); - return this; - } - resize(width, height) { - if (!animator.running(this)) { - this._resize(width, height); - } else { - this._resizeBeforeDraw = {width, height}; - } - } - _resize(width, height) { - const options = this.options; - const canvas = this.canvas; - const aspectRatio = options.maintainAspectRatio && this.aspectRatio; - const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio); - const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio(); - const mode = this.width ? 'resize' : 'attach'; - this.width = newSize.width; - this.height = newSize.height; - this._aspectRatio = this.aspectRatio; - if (!retinaScale(this, newRatio, true)) { - return; - } - this.notifyPlugins('resize', {size: newSize}); - callback(options.onResize, [this, newSize], this); - if (this.attached) { - if (this._doResize(mode)) { - this.render(); - } - } - } - ensureScalesHaveIDs() { - const options = this.options; - const scalesOptions = options.scales || {}; - each(scalesOptions, (axisOptions, axisID) => { - axisOptions.id = axisID; - }); - } - buildOrUpdateScales() { - const options = this.options; - const scaleOpts = options.scales; - const scales = this.scales; - const updated = Object.keys(scales).reduce((obj, id) => { - obj[id] = false; - return obj; - }, {}); - let items = []; - if (scaleOpts) { - items = items.concat( - Object.keys(scaleOpts).map((id) => { - const scaleOptions = scaleOpts[id]; - const axis = determineAxis(id, scaleOptions); - const isRadial = axis === 'r'; - const isHorizontal = axis === 'x'; - return { - options: scaleOptions, - dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left', - dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear' - }; - }) - ); - } - each(items, (item) => { - const scaleOptions = item.options; - const id = scaleOptions.id; - const axis = determineAxis(id, scaleOptions); - const scaleType = valueOrDefault(scaleOptions.type, item.dtype); - if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) { - scaleOptions.position = item.dposition; - } - updated[id] = true; - let scale = null; - if (id in scales && scales[id].type === scaleType) { - scale = scales[id]; - } else { - const scaleClass = registry.getScale(scaleType); - scale = new scaleClass({ - id, - type: scaleType, - ctx: this.ctx, - chart: this - }); - scales[scale.id] = scale; - } - scale.init(scaleOptions, options); - }); - each(updated, (hasUpdated, id) => { - if (!hasUpdated) { - delete scales[id]; - } - }); - each(scales, (scale) => { - layouts.configure(this, scale, scale.options); - layouts.addBox(this, scale); - }); - } - _updateMetasets() { - const metasets = this._metasets; - const numData = this.data.datasets.length; - const numMeta = metasets.length; - metasets.sort((a, b) => a.index - b.index); - if (numMeta > numData) { - for (let i = numData; i < numMeta; ++i) { - this._destroyDatasetMeta(i); - } - metasets.splice(numData, numMeta - numData); - } - this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index')); - } - _removeUnreferencedMetasets() { - const {_metasets: metasets, data: {datasets}} = this; - if (metasets.length > datasets.length) { - delete this._stacks; - } - metasets.forEach((meta, index) => { - if (datasets.filter(x => x === meta._dataset).length === 0) { - this._destroyDatasetMeta(index); - } - }); - } - buildOrUpdateControllers() { - const newControllers = []; - const datasets = this.data.datasets; - let i, ilen; - this._removeUnreferencedMetasets(); - for (i = 0, ilen = datasets.length; i < ilen; i++) { - const dataset = datasets[i]; - let meta = this.getDatasetMeta(i); - const type = dataset.type || this.config.type; - if (meta.type && meta.type !== type) { - this._destroyDatasetMeta(i); - meta = this.getDatasetMeta(i); - } - meta.type = type; - meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options); - meta.order = dataset.order || 0; - meta.index = i; - meta.label = '' + dataset.label; - meta.visible = this.isDatasetVisible(i); - if (meta.controller) { - meta.controller.updateIndex(i); - meta.controller.linkScales(); - } else { - const ControllerClass = registry.getController(type); - const {datasetElementType, dataElementType} = defaults.datasets[type]; - Object.assign(ControllerClass.prototype, { - dataElementType: registry.getElement(dataElementType), - datasetElementType: datasetElementType && registry.getElement(datasetElementType) - }); - meta.controller = new ControllerClass(this, i); - newControllers.push(meta.controller); - } - } - this._updateMetasets(); - return newControllers; - } - _resetElements() { - each(this.data.datasets, (dataset, datasetIndex) => { - this.getDatasetMeta(datasetIndex).controller.reset(); - }, this); - } - reset() { - this._resetElements(); - this.notifyPlugins('reset'); - } - update(mode) { - const config = this.config; - config.update(); - const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext()); - const animsDisabled = this._animationsDisabled = !options.animation; - this._updateScales(); - this._checkEventBindings(); - this._updateHiddenIndices(); - this._plugins.invalidate(); - if (this.notifyPlugins('beforeUpdate', {mode, cancelable: true}) === false) { - return; - } - const newControllers = this.buildOrUpdateControllers(); - this.notifyPlugins('beforeElementsUpdate'); - let minPadding = 0; - for (let i = 0, ilen = this.data.datasets.length; i < ilen; i++) { - const {controller} = this.getDatasetMeta(i); - const reset = !animsDisabled && newControllers.indexOf(controller) === -1; - controller.buildOrUpdateElements(reset); - minPadding = Math.max(+controller.getMaxOverflow(), minPadding); - } - minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0; - this._updateLayout(minPadding); - if (!animsDisabled) { - each(newControllers, (controller) => { - controller.reset(); - }); - } - this._updateDatasets(mode); - this.notifyPlugins('afterUpdate', {mode}); - this._layers.sort(compare2Level('z', '_idx')); - const {_active, _lastEvent} = this; - if (_lastEvent) { - this._eventHandler(_lastEvent, true); - } else if (_active.length) { - this._updateHoverStyles(_active, _active, true); - } - this.render(); - } - _updateScales() { - each(this.scales, (scale) => { - layouts.removeBox(this, scale); - }); - this.ensureScalesHaveIDs(); - this.buildOrUpdateScales(); - } - _checkEventBindings() { - const options = this.options; - const existingEvents = new Set(Object.keys(this._listeners)); - const newEvents = new Set(options.events); - if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) { - this.unbindEvents(); - this.bindEvents(); - } - } - _updateHiddenIndices() { - const {_hiddenIndices} = this; - const changes = this._getUniformDataChanges() || []; - for (const {method, start, count} of changes) { - const move = method === '_removeElements' ? -count : count; - moveNumericKeys(_hiddenIndices, start, move); - } - } - _getUniformDataChanges() { - const _dataChanges = this._dataChanges; - if (!_dataChanges || !_dataChanges.length) { - return; - } - this._dataChanges = []; - const datasetCount = this.data.datasets.length; - const makeSet = (idx) => new Set( - _dataChanges - .filter(c => c[0] === idx) - .map((c, i) => i + ',' + c.splice(1).join(',')) - ); - const changeSet = makeSet(0); - for (let i = 1; i < datasetCount; i++) { - if (!setsEqual(changeSet, makeSet(i))) { - return; - } - } - return Array.from(changeSet) - .map(c => c.split(',')) - .map(a => ({method: a[1], start: +a[2], count: +a[3]})); - } - _updateLayout(minPadding) { - if (this.notifyPlugins('beforeLayout', {cancelable: true}) === false) { - return; - } - layouts.update(this, this.width, this.height, minPadding); - const area = this.chartArea; - const noArea = area.width <= 0 || area.height <= 0; - this._layers = []; - each(this.boxes, (box) => { - if (noArea && box.position === 'chartArea') { - return; - } - if (box.configure) { - box.configure(); - } - this._layers.push(...box._layers()); - }, this); - this._layers.forEach((item, index) => { - item._idx = index; - }); - this.notifyPlugins('afterLayout'); - } - _updateDatasets(mode) { - if (this.notifyPlugins('beforeDatasetsUpdate', {mode, cancelable: true}) === false) { - return; - } - for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) { - this.getDatasetMeta(i).controller.configure(); - } - for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) { - this._updateDataset(i, isFunction(mode) ? mode({datasetIndex: i}) : mode); - } - this.notifyPlugins('afterDatasetsUpdate', {mode}); - } - _updateDataset(index, mode) { - const meta = this.getDatasetMeta(index); - const args = {meta, index, mode, cancelable: true}; - if (this.notifyPlugins('beforeDatasetUpdate', args) === false) { - return; - } - meta.controller._update(mode); - args.cancelable = false; - this.notifyPlugins('afterDatasetUpdate', args); - } - render() { - if (this.notifyPlugins('beforeRender', {cancelable: true}) === false) { - return; - } - if (animator.has(this)) { - if (this.attached && !animator.running(this)) { - animator.start(this); - } - } else { - this.draw(); - onAnimationsComplete({chart: this}); - } - } - draw() { - let i; - if (this._resizeBeforeDraw) { - const {width, height} = this._resizeBeforeDraw; - this._resize(width, height); - this._resizeBeforeDraw = null; - } - this.clear(); - if (this.width <= 0 || this.height <= 0) { - return; - } - if (this.notifyPlugins('beforeDraw', {cancelable: true}) === false) { - return; - } - const layers = this._layers; - for (i = 0; i < layers.length && layers[i].z <= 0; ++i) { - layers[i].draw(this.chartArea); - } - this._drawDatasets(); - for (; i < layers.length; ++i) { - layers[i].draw(this.chartArea); - } - this.notifyPlugins('afterDraw'); - } - _getSortedDatasetMetas(filterVisible) { - const metasets = this._sortedMetasets; - const result = []; - let i, ilen; - for (i = 0, ilen = metasets.length; i < ilen; ++i) { - const meta = metasets[i]; - if (!filterVisible || meta.visible) { - result.push(meta); - } - } - return result; - } - getSortedVisibleDatasetMetas() { - return this._getSortedDatasetMetas(true); - } - _drawDatasets() { - if (this.notifyPlugins('beforeDatasetsDraw', {cancelable: true}) === false) { - return; - } - const metasets = this.getSortedVisibleDatasetMetas(); - for (let i = metasets.length - 1; i >= 0; --i) { - this._drawDataset(metasets[i]); - } - this.notifyPlugins('afterDatasetsDraw'); - } - _drawDataset(meta) { - const ctx = this.ctx; - const clip = meta._clip; - const useClip = !clip.disabled; - const area = this.chartArea; - const args = { - meta, - index: meta.index, - cancelable: true - }; - if (this.notifyPlugins('beforeDatasetDraw', args) === false) { - return; - } - if (useClip) { - clipArea(ctx, { - left: clip.left === false ? 0 : area.left - clip.left, - right: clip.right === false ? this.width : area.right + clip.right, - top: clip.top === false ? 0 : area.top - clip.top, - bottom: clip.bottom === false ? this.height : area.bottom + clip.bottom - }); - } - meta.controller.draw(); - if (useClip) { - unclipArea(ctx); - } - args.cancelable = false; - this.notifyPlugins('afterDatasetDraw', args); - } - getElementsAtEventForMode(e, mode, options, useFinalPosition) { - const method = Interaction.modes[mode]; - if (typeof method === 'function') { - return method(this, e, options, useFinalPosition); - } - return []; - } - getDatasetMeta(datasetIndex) { - const dataset = this.data.datasets[datasetIndex]; - const metasets = this._metasets; - let meta = metasets.filter(x => x && x._dataset === dataset).pop(); - if (!meta) { - meta = { - type: null, - data: [], - dataset: null, - controller: null, - hidden: null, - xAxisID: null, - yAxisID: null, - order: dataset && dataset.order || 0, - index: datasetIndex, - _dataset: dataset, - _parsed: [], - _sorted: false - }; - metasets.push(meta); - } - return meta; - } - getContext() { - return this.$context || (this.$context = createContext(null, {chart: this, type: 'chart'})); - } - getVisibleDatasetCount() { - return this.getSortedVisibleDatasetMetas().length; - } - isDatasetVisible(datasetIndex) { - const dataset = this.data.datasets[datasetIndex]; - if (!dataset) { - return false; - } - const meta = this.getDatasetMeta(datasetIndex); - return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden; - } - setDatasetVisibility(datasetIndex, visible) { - const meta = this.getDatasetMeta(datasetIndex); - meta.hidden = !visible; - } - toggleDataVisibility(index) { - this._hiddenIndices[index] = !this._hiddenIndices[index]; - } - getDataVisibility(index) { - return !this._hiddenIndices[index]; - } - _updateVisibility(datasetIndex, dataIndex, visible) { - const mode = visible ? 'show' : 'hide'; - const meta = this.getDatasetMeta(datasetIndex); - const anims = meta.controller._resolveAnimations(undefined, mode); - if (defined(dataIndex)) { - meta.data[dataIndex].hidden = !visible; - this.update(); - } else { - this.setDatasetVisibility(datasetIndex, visible); - anims.update(meta, {visible}); - this.update((ctx) => ctx.datasetIndex === datasetIndex ? mode : undefined); - } - } - hide(datasetIndex, dataIndex) { - this._updateVisibility(datasetIndex, dataIndex, false); - } - show(datasetIndex, dataIndex) { - this._updateVisibility(datasetIndex, dataIndex, true); - } - _destroyDatasetMeta(datasetIndex) { - const meta = this._metasets[datasetIndex]; - if (meta && meta.controller) { - meta.controller._destroy(); - } - delete this._metasets[datasetIndex]; - } - _stop() { - let i, ilen; - this.stop(); - animator.remove(this); - for (i = 0, ilen = this.data.datasets.length; i < ilen; ++i) { - this._destroyDatasetMeta(i); - } - } - destroy() { - this.notifyPlugins('beforeDestroy'); - const {canvas, ctx} = this; - this._stop(); - this.config.clearCache(); - if (canvas) { - this.unbindEvents(); - clearCanvas(canvas, ctx); - this.platform.releaseContext(ctx); - this.canvas = null; - this.ctx = null; - } - this.notifyPlugins('destroy'); - delete instances[this.id]; - this.notifyPlugins('afterDestroy'); - } - toBase64Image(...args) { - return this.canvas.toDataURL(...args); - } - bindEvents() { - this.bindUserEvents(); - if (this.options.responsive) { - this.bindResponsiveEvents(); - } else { - this.attached = true; - } - } - bindUserEvents() { - const listeners = this._listeners; - const platform = this.platform; - const _add = (type, listener) => { - platform.addEventListener(this, type, listener); - listeners[type] = listener; - }; - const listener = (e, x, y) => { - e.offsetX = x; - e.offsetY = y; - this._eventHandler(e); - }; - each(this.options.events, (type) => _add(type, listener)); - } - bindResponsiveEvents() { - if (!this._responsiveListeners) { - this._responsiveListeners = {}; - } - const listeners = this._responsiveListeners; - const platform = this.platform; - const _add = (type, listener) => { - platform.addEventListener(this, type, listener); - listeners[type] = listener; - }; - const _remove = (type, listener) => { - if (listeners[type]) { - platform.removeEventListener(this, type, listener); - delete listeners[type]; - } - }; - const listener = (width, height) => { - if (this.canvas) { - this.resize(width, height); - } - }; - let detached; - const attached = () => { - _remove('attach', attached); - this.attached = true; - this.resize(); - _add('resize', listener); - _add('detach', detached); - }; - detached = () => { - this.attached = false; - _remove('resize', listener); - this._stop(); - this._resize(0, 0); - _add('attach', attached); - }; - if (platform.isAttached(this.canvas)) { - attached(); - } else { - detached(); - } - } - unbindEvents() { - each(this._listeners, (listener, type) => { - this.platform.removeEventListener(this, type, listener); - }); - this._listeners = {}; - each(this._responsiveListeners, (listener, type) => { - this.platform.removeEventListener(this, type, listener); - }); - this._responsiveListeners = undefined; - } - updateHoverStyle(items, mode, enabled) { - const prefix = enabled ? 'set' : 'remove'; - let meta, item, i, ilen; - if (mode === 'dataset') { - meta = this.getDatasetMeta(items[0].datasetIndex); - meta.controller['_' + prefix + 'DatasetHoverStyle'](); - } - for (i = 0, ilen = items.length; i < ilen; ++i) { - item = items[i]; - const controller = item && this.getDatasetMeta(item.datasetIndex).controller; - if (controller) { - controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index); - } - } - } - getActiveElements() { - return this._active || []; - } - setActiveElements(activeElements) { - const lastActive = this._active || []; - const active = activeElements.map(({datasetIndex, index}) => { - const meta = this.getDatasetMeta(datasetIndex); - if (!meta) { - throw new Error('No dataset found at index ' + datasetIndex); - } - return { - datasetIndex, - element: meta.data[index], - index, - }; - }); - const changed = !_elementsEqual(active, lastActive); - if (changed) { - this._active = active; - this._lastEvent = null; - this._updateHoverStyles(active, lastActive); - } - } - notifyPlugins(hook, args, filter) { - return this._plugins.notify(this, hook, args, filter); - } - _updateHoverStyles(active, lastActive, replay) { - const hoverOptions = this.options.hover; - const diff = (a, b) => a.filter(x => !b.some(y => x.datasetIndex === y.datasetIndex && x.index === y.index)); - const deactivated = diff(lastActive, active); - const activated = replay ? active : diff(active, lastActive); - if (deactivated.length) { - this.updateHoverStyle(deactivated, hoverOptions.mode, false); - } - if (activated.length && hoverOptions.mode) { - this.updateHoverStyle(activated, hoverOptions.mode, true); - } - } - _eventHandler(e, replay) { - const args = { - event: e, - replay, - cancelable: true, - inChartArea: _isPointInArea(e, this.chartArea, this._minPadding) - }; - const eventFilter = (plugin) => (plugin.options.events || this.options.events).includes(e.native.type); - if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) { - return; - } - const changed = this._handleEvent(e, replay, args.inChartArea); - args.cancelable = false; - this.notifyPlugins('afterEvent', args, eventFilter); - if (changed || args.changed) { - this.render(); - } - return this; - } - _handleEvent(e, replay, inChartArea) { - const {_active: lastActive = [], options} = this; - const useFinalPosition = replay; - const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition); - const isClick = _isClickEvent(e); - const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick); - if (inChartArea) { - this._lastEvent = null; - callback(options.onHover, [e, active, this], this); - if (isClick) { - callback(options.onClick, [e, active, this], this); - } - } - const changed = !_elementsEqual(active, lastActive); - if (changed || replay) { - this._active = active; - this._updateHoverStyles(active, lastActive, replay); - } - this._lastEvent = lastEvent; - return changed; - } - _getActiveElements(e, lastActive, inChartArea, useFinalPosition) { - if (e.type === 'mouseout') { - return []; - } - if (!inChartArea) { - return lastActive; - } - const hoverOptions = this.options.hover; - return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition); - } -} -const invalidatePlugins = () => each(Chart.instances, (chart) => chart._plugins.invalidate()); -const enumerable = true; -Object.defineProperties(Chart, { - defaults: { - enumerable, - value: defaults - }, - instances: { - enumerable, - value: instances - }, - overrides: { - enumerable, - value: overrides - }, - registry: { - enumerable, - value: registry - }, - version: { - enumerable, - value: version - }, - getChart: { - enumerable, - value: getChart - }, - register: { - enumerable, - value: (...items) => { - registry.add(...items); - invalidatePlugins(); - } - }, - unregister: { - enumerable, - value: (...items) => { - registry.remove(...items); - invalidatePlugins(); - } - } -}); - -function abstract() { - throw new Error('This method is not implemented: Check that a complete date adapter is provided.'); -} -class DateAdapter { - constructor(options) { - this.options = options || {}; - } - formats() { - return abstract(); - } - parse(value, format) { - return abstract(); - } - format(timestamp, format) { - return abstract(); - } - add(timestamp, amount, unit) { - return abstract(); - } - diff(a, b, unit) { - return abstract(); - } - startOf(timestamp, unit, weekday) { - return abstract(); - } - endOf(timestamp, unit) { - return abstract(); - } -} -DateAdapter.override = function(members) { - Object.assign(DateAdapter.prototype, members); -}; -var _adapters = { - _date: DateAdapter -}; - -function getAllScaleValues(scale, type) { - if (!scale._cache.$bar) { - const visibleMetas = scale.getMatchingVisibleMetas(type); - let values = []; - for (let i = 0, ilen = visibleMetas.length; i < ilen; i++) { - values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale)); - } - scale._cache.$bar = _arrayUnique(values.sort((a, b) => a - b)); - } - return scale._cache.$bar; -} -function computeMinSampleSize(meta) { - const scale = meta.iScale; - const values = getAllScaleValues(scale, meta.type); - let min = scale._length; - let i, ilen, curr, prev; - const updateMinAndPrev = () => { - if (curr === 32767 || curr === -32768) { - return; - } - if (defined(prev)) { - min = Math.min(min, Math.abs(curr - prev) || min); - } - prev = curr; - }; - for (i = 0, ilen = values.length; i < ilen; ++i) { - curr = scale.getPixelForValue(values[i]); - updateMinAndPrev(); - } - prev = undefined; - for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) { - curr = scale.getPixelForTick(i); - updateMinAndPrev(); - } - return min; -} -function computeFitCategoryTraits(index, ruler, options, stackCount) { - const thickness = options.barThickness; - let size, ratio; - if (isNullOrUndef(thickness)) { - size = ruler.min * options.categoryPercentage; - ratio = options.barPercentage; - } else { - size = thickness * stackCount; - ratio = 1; - } - return { - chunk: size / stackCount, - ratio, - start: ruler.pixels[index] - (size / 2) - }; -} -function computeFlexCategoryTraits(index, ruler, options, stackCount) { - const pixels = ruler.pixels; - const curr = pixels[index]; - let prev = index > 0 ? pixels[index - 1] : null; - let next = index < pixels.length - 1 ? pixels[index + 1] : null; - const percent = options.categoryPercentage; - if (prev === null) { - prev = curr - (next === null ? ruler.end - ruler.start : next - curr); - } - if (next === null) { - next = curr + curr - prev; - } - const start = curr - (curr - Math.min(prev, next)) / 2 * percent; - const size = Math.abs(next - prev) / 2 * percent; - return { - chunk: size / stackCount, - ratio: options.barPercentage, - start - }; -} -function parseFloatBar(entry, item, vScale, i) { - const startValue = vScale.parse(entry[0], i); - const endValue = vScale.parse(entry[1], i); - const min = Math.min(startValue, endValue); - const max = Math.max(startValue, endValue); - let barStart = min; - let barEnd = max; - if (Math.abs(min) > Math.abs(max)) { - barStart = max; - barEnd = min; - } - item[vScale.axis] = barEnd; - item._custom = { - barStart, - barEnd, - start: startValue, - end: endValue, - min, - max - }; -} -function parseValue(entry, item, vScale, i) { - if (isArray(entry)) { - parseFloatBar(entry, item, vScale, i); - } else { - item[vScale.axis] = vScale.parse(entry, i); - } - return item; -} -function parseArrayOrPrimitive(meta, data, start, count) { - const iScale = meta.iScale; - const vScale = meta.vScale; - const labels = iScale.getLabels(); - const singleScale = iScale === vScale; - const parsed = []; - let i, ilen, item, entry; - for (i = start, ilen = start + count; i < ilen; ++i) { - entry = data[i]; - item = {}; - item[iScale.axis] = singleScale || iScale.parse(labels[i], i); - parsed.push(parseValue(entry, item, vScale, i)); - } - return parsed; -} -function isFloatBar(custom) { - return custom && custom.barStart !== undefined && custom.barEnd !== undefined; -} -function barSign(size, vScale, actualBase) { - if (size !== 0) { - return sign(size); - } - return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1); -} -function borderProps(properties) { - let reverse, start, end, top, bottom; - if (properties.horizontal) { - reverse = properties.base > properties.x; - start = 'left'; - end = 'right'; - } else { - reverse = properties.base < properties.y; - start = 'bottom'; - end = 'top'; - } - if (reverse) { - top = 'end'; - bottom = 'start'; - } else { - top = 'start'; - bottom = 'end'; - } - return {start, end, reverse, top, bottom}; -} -function setBorderSkipped(properties, options, stack, index) { - let edge = options.borderSkipped; - const res = {}; - if (!edge) { - properties.borderSkipped = res; - return; - } - const {start, end, reverse, top, bottom} = borderProps(properties); - if (edge === 'middle' && stack) { - properties.enableBorderRadius = true; - if ((stack._top || 0) === index) { - edge = top; - } else if ((stack._bottom || 0) === index) { - edge = bottom; - } else { - res[parseEdge(bottom, start, end, reverse)] = true; - edge = top; - } - } - res[parseEdge(edge, start, end, reverse)] = true; - properties.borderSkipped = res; -} -function parseEdge(edge, a, b, reverse) { - if (reverse) { - edge = swap(edge, a, b); - edge = startEnd(edge, b, a); - } else { - edge = startEnd(edge, a, b); - } - return edge; -} -function swap(orig, v1, v2) { - return orig === v1 ? v2 : orig === v2 ? v1 : orig; -} -function startEnd(v, start, end) { - return v === 'start' ? start : v === 'end' ? end : v; -} -function setInflateAmount(properties, {inflateAmount}, ratio) { - properties.inflateAmount = inflateAmount === 'auto' - ? ratio === 1 ? 0.33 : 0 - : inflateAmount; -} -class BarController extends DatasetController { - parsePrimitiveData(meta, data, start, count) { - return parseArrayOrPrimitive(meta, data, start, count); - } - parseArrayData(meta, data, start, count) { - return parseArrayOrPrimitive(meta, data, start, count); - } - parseObjectData(meta, data, start, count) { - const {iScale, vScale} = meta; - const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing; - const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey; - const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey; - const parsed = []; - let i, ilen, item, obj; - for (i = start, ilen = start + count; i < ilen; ++i) { - obj = data[i]; - item = {}; - item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i); - parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i)); - } - return parsed; - } - updateRangeFromParsed(range, scale, parsed, stack) { - super.updateRangeFromParsed(range, scale, parsed, stack); - const custom = parsed._custom; - if (custom && scale === this._cachedMeta.vScale) { - range.min = Math.min(range.min, custom.min); - range.max = Math.max(range.max, custom.max); - } - } - getMaxOverflow() { - return 0; - } - getLabelAndValue(index) { - const meta = this._cachedMeta; - const {iScale, vScale} = meta; - const parsed = this.getParsed(index); - const custom = parsed._custom; - const value = isFloatBar(custom) - ? '[' + custom.start + ', ' + custom.end + ']' - : '' + vScale.getLabelForValue(parsed[vScale.axis]); - return { - label: '' + iScale.getLabelForValue(parsed[iScale.axis]), - value - }; - } - initialize() { - this.enableOptionSharing = true; - super.initialize(); - const meta = this._cachedMeta; - meta.stack = this.getDataset().stack; - } - update(mode) { - const meta = this._cachedMeta; - this.updateElements(meta.data, 0, meta.data.length, mode); - } - updateElements(bars, start, count, mode) { - const reset = mode === 'reset'; - const {index, _cachedMeta: {vScale}} = this; - const base = vScale.getBasePixel(); - const horizontal = vScale.isHorizontal(); - const ruler = this._getRuler(); - const firstOpts = this.resolveDataElementOptions(start, mode); - const sharedOptions = this.getSharedOptions(firstOpts); - const includeOptions = this.includeOptions(mode, sharedOptions); - this.updateSharedOptions(sharedOptions, mode, firstOpts); - for (let i = start; i < start + count; i++) { - const parsed = this.getParsed(i); - const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {base, head: base} : this._calculateBarValuePixels(i); - const ipixels = this._calculateBarIndexPixels(i, ruler); - const stack = (parsed._stacks || {})[vScale.axis]; - const properties = { - horizontal, - base: vpixels.base, - enableBorderRadius: !stack || isFloatBar(parsed._custom) || (index === stack._top || index === stack._bottom), - x: horizontal ? vpixels.head : ipixels.center, - y: horizontal ? ipixels.center : vpixels.head, - height: horizontal ? ipixels.size : Math.abs(vpixels.size), - width: horizontal ? Math.abs(vpixels.size) : ipixels.size - }; - if (includeOptions) { - properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode); - } - const options = properties.options || bars[i].options; - setBorderSkipped(properties, options, stack, index); - setInflateAmount(properties, options, ruler.ratio); - this.updateElement(bars[i], i, properties, mode); - } - } - _getStacks(last, dataIndex) { - const meta = this._cachedMeta; - const iScale = meta.iScale; - const metasets = iScale.getMatchingVisibleMetas(this._type); - const stacked = iScale.options.stacked; - const ilen = metasets.length; - const stacks = []; - let i, item; - for (i = 0; i < ilen; ++i) { - item = metasets[i]; - if (!item.controller.options.grouped) { - continue; - } - if (typeof dataIndex !== 'undefined') { - const val = item.controller.getParsed(dataIndex)[ - item.controller._cachedMeta.vScale.axis - ]; - if (isNullOrUndef(val) || isNaN(val)) { - continue; - } - } - if (stacked === false || stacks.indexOf(item.stack) === -1 || - (stacked === undefined && item.stack === undefined)) { - stacks.push(item.stack); - } - if (item.index === last) { - break; - } - } - if (!stacks.length) { - stacks.push(undefined); - } - return stacks; - } - _getStackCount(index) { - return this._getStacks(undefined, index).length; - } - _getStackIndex(datasetIndex, name, dataIndex) { - const stacks = this._getStacks(datasetIndex, dataIndex); - const index = (name !== undefined) - ? stacks.indexOf(name) - : -1; - return (index === -1) - ? stacks.length - 1 - : index; - } - _getRuler() { - const opts = this.options; - const meta = this._cachedMeta; - const iScale = meta.iScale; - const pixels = []; - let i, ilen; - for (i = 0, ilen = meta.data.length; i < ilen; ++i) { - pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i)); - } - const barThickness = opts.barThickness; - const min = barThickness || computeMinSampleSize(meta); - return { - min, - pixels, - start: iScale._startPixel, - end: iScale._endPixel, - stackCount: this._getStackCount(), - scale: iScale, - grouped: opts.grouped, - ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage - }; - } - _calculateBarValuePixels(index) { - const {_cachedMeta: {vScale, _stacked}, options: {base: baseValue, minBarLength}} = this; - const actualBase = baseValue || 0; - const parsed = this.getParsed(index); - const custom = parsed._custom; - const floating = isFloatBar(custom); - let value = parsed[vScale.axis]; - let start = 0; - let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value; - let head, size; - if (length !== value) { - start = length - value; - length = value; - } - if (floating) { - value = custom.barStart; - length = custom.barEnd - custom.barStart; - if (value !== 0 && sign(value) !== sign(custom.barEnd)) { - start = 0; - } - start += value; - } - const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start; - let base = vScale.getPixelForValue(startValue); - if (this.chart.getDataVisibility(index)) { - head = vScale.getPixelForValue(start + length); - } else { - head = base; - } - size = head - base; - if (Math.abs(size) < minBarLength) { - size = barSign(size, vScale, actualBase) * minBarLength; - if (value === actualBase) { - base -= size / 2; - } - head = base + size; - } - if (base === vScale.getPixelForValue(actualBase)) { - const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2; - base += halfGrid; - size -= halfGrid; - } - return { - size, - base, - head, - center: head + size / 2 - }; - } - _calculateBarIndexPixels(index, ruler) { - const scale = ruler.scale; - const options = this.options; - const skipNull = options.skipNull; - const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity); - let center, size; - if (ruler.grouped) { - const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount; - const range = options.barThickness === 'flex' - ? computeFlexCategoryTraits(index, ruler, options, stackCount) - : computeFitCategoryTraits(index, ruler, options, stackCount); - const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined); - center = range.start + (range.chunk * stackIndex) + (range.chunk / 2); - size = Math.min(maxBarThickness, range.chunk * range.ratio); - } else { - center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index); - size = Math.min(maxBarThickness, ruler.min * ruler.ratio); - } - return { - base: center - size / 2, - head: center + size / 2, - center, - size - }; - } - draw() { - const meta = this._cachedMeta; - const vScale = meta.vScale; - const rects = meta.data; - const ilen = rects.length; - let i = 0; - for (; i < ilen; ++i) { - if (this.getParsed(i)[vScale.axis] !== null) { - rects[i].draw(this._ctx); - } - } - } -} -BarController.id = 'bar'; -BarController.defaults = { - datasetElementType: false, - dataElementType: 'bar', - categoryPercentage: 0.8, - barPercentage: 0.9, - grouped: true, - animations: { - numbers: { - type: 'number', - properties: ['x', 'y', 'base', 'width', 'height'] - } - } -}; -BarController.overrides = { - scales: { - _index_: { - type: 'category', - offset: true, - grid: { - offset: true - } - }, - _value_: { - type: 'linear', - beginAtZero: true, - } - } -}; - -class BubbleController extends DatasetController { - initialize() { - this.enableOptionSharing = true; - super.initialize(); - } - parsePrimitiveData(meta, data, start, count) { - const parsed = super.parsePrimitiveData(meta, data, start, count); - for (let i = 0; i < parsed.length; i++) { - parsed[i]._custom = this.resolveDataElementOptions(i + start).radius; - } - return parsed; - } - parseArrayData(meta, data, start, count) { - const parsed = super.parseArrayData(meta, data, start, count); - for (let i = 0; i < parsed.length; i++) { - const item = data[start + i]; - parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius); - } - return parsed; - } - parseObjectData(meta, data, start, count) { - const parsed = super.parseObjectData(meta, data, start, count); - for (let i = 0; i < parsed.length; i++) { - const item = data[start + i]; - parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius); - } - return parsed; - } - getMaxOverflow() { - const data = this._cachedMeta.data; - let max = 0; - for (let i = data.length - 1; i >= 0; --i) { - max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2); - } - return max > 0 && max; - } - getLabelAndValue(index) { - const meta = this._cachedMeta; - const {xScale, yScale} = meta; - const parsed = this.getParsed(index); - const x = xScale.getLabelForValue(parsed.x); - const y = yScale.getLabelForValue(parsed.y); - const r = parsed._custom; - return { - label: meta.label, - value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')' - }; - } - update(mode) { - const points = this._cachedMeta.data; - this.updateElements(points, 0, points.length, mode); - } - updateElements(points, start, count, mode) { - const reset = mode === 'reset'; - const {iScale, vScale} = this._cachedMeta; - const firstOpts = this.resolveDataElementOptions(start, mode); - const sharedOptions = this.getSharedOptions(firstOpts); - const includeOptions = this.includeOptions(mode, sharedOptions); - const iAxis = iScale.axis; - const vAxis = vScale.axis; - for (let i = start; i < start + count; i++) { - const point = points[i]; - const parsed = !reset && this.getParsed(i); - const properties = {}; - const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]); - const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]); - properties.skip = isNaN(iPixel) || isNaN(vPixel); - if (includeOptions) { - properties.options = this.resolveDataElementOptions(i, point.active ? 'active' : mode); - if (reset) { - properties.options.radius = 0; - } - } - this.updateElement(point, i, properties, mode); - } - this.updateSharedOptions(sharedOptions, mode, firstOpts); - } - resolveDataElementOptions(index, mode) { - const parsed = this.getParsed(index); - let values = super.resolveDataElementOptions(index, mode); - if (values.$shared) { - values = Object.assign({}, values, {$shared: false}); - } - const radius = values.radius; - if (mode !== 'active') { - values.radius = 0; - } - values.radius += valueOrDefault(parsed && parsed._custom, radius); - return values; - } -} -BubbleController.id = 'bubble'; -BubbleController.defaults = { - datasetElementType: false, - dataElementType: 'point', - animations: { - numbers: { - type: 'number', - properties: ['x', 'y', 'borderWidth', 'radius'] - } - } -}; -BubbleController.overrides = { - scales: { - x: { - type: 'linear' - }, - y: { - type: 'linear' - } - }, - plugins: { - tooltip: { - callbacks: { - title() { - return ''; - } - } - } - } -}; - -function getRatioAndOffset(rotation, circumference, cutout) { - let ratioX = 1; - let ratioY = 1; - let offsetX = 0; - let offsetY = 0; - if (circumference < TAU) { - const startAngle = rotation; - const endAngle = startAngle + circumference; - const startX = Math.cos(startAngle); - const startY = Math.sin(startAngle); - const endX = Math.cos(endAngle); - const endY = Math.sin(endAngle); - const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout); - const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout); - const maxX = calcMax(0, startX, endX); - const maxY = calcMax(HALF_PI, startY, endY); - const minX = calcMin(PI, startX, endX); - const minY = calcMin(PI + HALF_PI, startY, endY); - ratioX = (maxX - minX) / 2; - ratioY = (maxY - minY) / 2; - offsetX = -(maxX + minX) / 2; - offsetY = -(maxY + minY) / 2; - } - return {ratioX, ratioY, offsetX, offsetY}; -} -class DoughnutController extends DatasetController { - constructor(chart, datasetIndex) { - super(chart, datasetIndex); - this.enableOptionSharing = true; - this.innerRadius = undefined; - this.outerRadius = undefined; - this.offsetX = undefined; - this.offsetY = undefined; - } - linkScales() {} - parse(start, count) { - const data = this.getDataset().data; - const meta = this._cachedMeta; - if (this._parsing === false) { - meta._parsed = data; - } else { - let getter = (i) => +data[i]; - if (isObject(data[start])) { - const {key = 'value'} = this._parsing; - getter = (i) => +resolveObjectKey(data[i], key); - } - let i, ilen; - for (i = start, ilen = start + count; i < ilen; ++i) { - meta._parsed[i] = getter(i); - } - } - } - _getRotation() { - return toRadians(this.options.rotation - 90); - } - _getCircumference() { - return toRadians(this.options.circumference); - } - _getRotationExtents() { - let min = TAU; - let max = -TAU; - for (let i = 0; i < this.chart.data.datasets.length; ++i) { - if (this.chart.isDatasetVisible(i)) { - const controller = this.chart.getDatasetMeta(i).controller; - const rotation = controller._getRotation(); - const circumference = controller._getCircumference(); - min = Math.min(min, rotation); - max = Math.max(max, rotation + circumference); - } - } - return { - rotation: min, - circumference: max - min, - }; - } - update(mode) { - const chart = this.chart; - const {chartArea} = chart; - const meta = this._cachedMeta; - const arcs = meta.data; - const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing; - const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0); - const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1); - const chartWeight = this._getRingWeight(this.index); - const {circumference, rotation} = this._getRotationExtents(); - const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout); - const maxWidth = (chartArea.width - spacing) / ratioX; - const maxHeight = (chartArea.height - spacing) / ratioY; - const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0); - const outerRadius = toDimension(this.options.radius, maxRadius); - const innerRadius = Math.max(outerRadius * cutout, 0); - const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal(); - this.offsetX = offsetX * outerRadius; - this.offsetY = offsetY * outerRadius; - meta.total = this.calculateTotal(); - this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index); - this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0); - this.updateElements(arcs, 0, arcs.length, mode); - } - _circumference(i, reset) { - const opts = this.options; - const meta = this._cachedMeta; - const circumference = this._getCircumference(); - if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) { - return 0; - } - return this.calculateCircumference(meta._parsed[i] * circumference / TAU); - } - updateElements(arcs, start, count, mode) { - const reset = mode === 'reset'; - const chart = this.chart; - const chartArea = chart.chartArea; - const opts = chart.options; - const animationOpts = opts.animation; - const centerX = (chartArea.left + chartArea.right) / 2; - const centerY = (chartArea.top + chartArea.bottom) / 2; - const animateScale = reset && animationOpts.animateScale; - const innerRadius = animateScale ? 0 : this.innerRadius; - const outerRadius = animateScale ? 0 : this.outerRadius; - const firstOpts = this.resolveDataElementOptions(start, mode); - const sharedOptions = this.getSharedOptions(firstOpts); - const includeOptions = this.includeOptions(mode, sharedOptions); - let startAngle = this._getRotation(); - let i; - for (i = 0; i < start; ++i) { - startAngle += this._circumference(i, reset); - } - for (i = start; i < start + count; ++i) { - const circumference = this._circumference(i, reset); - const arc = arcs[i]; - const properties = { - x: centerX + this.offsetX, - y: centerY + this.offsetY, - startAngle, - endAngle: startAngle + circumference, - circumference, - outerRadius, - innerRadius - }; - if (includeOptions) { - properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode); - } - startAngle += circumference; - this.updateElement(arc, i, properties, mode); - } - this.updateSharedOptions(sharedOptions, mode, firstOpts); - } - calculateTotal() { - const meta = this._cachedMeta; - const metaData = meta.data; - let total = 0; - let i; - for (i = 0; i < metaData.length; i++) { - const value = meta._parsed[i]; - if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) { - total += Math.abs(value); - } - } - return total; - } - calculateCircumference(value) { - const total = this._cachedMeta.total; - if (total > 0 && !isNaN(value)) { - return TAU * (Math.abs(value) / total); - } - return 0; - } - getLabelAndValue(index) { - const meta = this._cachedMeta; - const chart = this.chart; - const labels = chart.data.labels || []; - const value = formatNumber(meta._parsed[index], chart.options.locale); - return { - label: labels[index] || '', - value, - }; - } - getMaxBorderWidth(arcs) { - let max = 0; - const chart = this.chart; - let i, ilen, meta, controller, options; - if (!arcs) { - for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) { - if (chart.isDatasetVisible(i)) { - meta = chart.getDatasetMeta(i); - arcs = meta.data; - controller = meta.controller; - break; - } - } - } - if (!arcs) { - return 0; - } - for (i = 0, ilen = arcs.length; i < ilen; ++i) { - options = controller.resolveDataElementOptions(i); - if (options.borderAlign !== 'inner') { - max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0); - } - } - return max; - } - getMaxOffset(arcs) { - let max = 0; - for (let i = 0, ilen = arcs.length; i < ilen; ++i) { - const options = this.resolveDataElementOptions(i); - max = Math.max(max, options.offset || 0, options.hoverOffset || 0); - } - return max; - } - _getRingWeightOffset(datasetIndex) { - let ringWeightOffset = 0; - for (let i = 0; i < datasetIndex; ++i) { - if (this.chart.isDatasetVisible(i)) { - ringWeightOffset += this._getRingWeight(i); - } - } - return ringWeightOffset; - } - _getRingWeight(datasetIndex) { - return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0); - } - _getVisibleDatasetWeightTotal() { - return this._getRingWeightOffset(this.chart.data.datasets.length) || 1; - } -} -DoughnutController.id = 'doughnut'; -DoughnutController.defaults = { - datasetElementType: false, - dataElementType: 'arc', - animation: { - animateRotate: true, - animateScale: false - }, - animations: { - numbers: { - type: 'number', - properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing'] - }, - }, - cutout: '50%', - rotation: 0, - circumference: 360, - radius: '100%', - spacing: 0, - indexAxis: 'r', -}; -DoughnutController.descriptors = { - _scriptable: (name) => name !== 'spacing', - _indexable: (name) => name !== 'spacing', -}; -DoughnutController.overrides = { - aspectRatio: 1, - plugins: { - legend: { - labels: { - generateLabels(chart) { - const data = chart.data; - if (data.labels.length && data.datasets.length) { - const {labels: {pointStyle}} = chart.legend.options; - return data.labels.map((label, i) => { - const meta = chart.getDatasetMeta(0); - const style = meta.controller.getStyle(i); - return { - text: label, - fillStyle: style.backgroundColor, - strokeStyle: style.borderColor, - lineWidth: style.borderWidth, - pointStyle: pointStyle, - hidden: !chart.getDataVisibility(i), - index: i - }; - }); - } - return []; - } - }, - onClick(e, legendItem, legend) { - legend.chart.toggleDataVisibility(legendItem.index); - legend.chart.update(); - } - }, - tooltip: { - callbacks: { - title() { - return ''; - }, - label(tooltipItem) { - let dataLabel = tooltipItem.label; - const value = ': ' + tooltipItem.formattedValue; - if (isArray(dataLabel)) { - dataLabel = dataLabel.slice(); - dataLabel[0] += value; - } else { - dataLabel += value; - } - return dataLabel; - } - } - } - } -}; - -class LineController extends DatasetController { - initialize() { - this.enableOptionSharing = true; - super.initialize(); - } - update(mode) { - const meta = this._cachedMeta; - const {dataset: line, data: points = [], _dataset} = meta; - const animationsDisabled = this.chart._animationsDisabled; - let {start, count} = getStartAndCountOfVisiblePoints(meta, points, animationsDisabled); - this._drawStart = start; - this._drawCount = count; - if (scaleRangesChanged(meta)) { - start = 0; - count = points.length; - } - line._chart = this.chart; - line._datasetIndex = this.index; - line._decimated = !!_dataset._decimated; - line.points = points; - const options = this.resolveDatasetElementOptions(mode); - if (!this.options.showLine) { - options.borderWidth = 0; - } - options.segment = this.options.segment; - this.updateElement(line, undefined, { - animated: !animationsDisabled, - options - }, mode); - this.updateElements(points, start, count, mode); - } - updateElements(points, start, count, mode) { - const reset = mode === 'reset'; - const {iScale, vScale, _stacked, _dataset} = this._cachedMeta; - const firstOpts = this.resolveDataElementOptions(start, mode); - const sharedOptions = this.getSharedOptions(firstOpts); - const includeOptions = this.includeOptions(mode, sharedOptions); - const iAxis = iScale.axis; - const vAxis = vScale.axis; - const {spanGaps, segment} = this.options; - const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY; - const directUpdate = this.chart._animationsDisabled || reset || mode === 'none'; - let prevParsed = start > 0 && this.getParsed(start - 1); - for (let i = start; i < start + count; ++i) { - const point = points[i]; - const parsed = this.getParsed(i); - const properties = directUpdate ? point : {}; - const nullData = isNullOrUndef(parsed[vAxis]); - const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i); - const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i); - properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData; - properties.stop = i > 0 && (parsed[iAxis] - prevParsed[iAxis]) > maxGapLength; - if (segment) { - properties.parsed = parsed; - properties.raw = _dataset.data[i]; - } - if (includeOptions) { - properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode); - } - if (!directUpdate) { - this.updateElement(point, i, properties, mode); - } - prevParsed = parsed; - } - this.updateSharedOptions(sharedOptions, mode, firstOpts); - } - getMaxOverflow() { - const meta = this._cachedMeta; - const dataset = meta.dataset; - const border = dataset.options && dataset.options.borderWidth || 0; - const data = meta.data || []; - if (!data.length) { - return border; - } - const firstPoint = data[0].size(this.resolveDataElementOptions(0)); - const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1)); - return Math.max(border, firstPoint, lastPoint) / 2; - } - draw() { - const meta = this._cachedMeta; - meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis); - super.draw(); - } -} -LineController.id = 'line'; -LineController.defaults = { - datasetElementType: 'line', - dataElementType: 'point', - showLine: true, - spanGaps: false, -}; -LineController.overrides = { - scales: { - _index_: { - type: 'category', - }, - _value_: { - type: 'linear', - }, - } -}; -function getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) { - const pointCount = points.length; - let start = 0; - let count = pointCount; - if (meta._sorted) { - const {iScale, _parsed} = meta; - const axis = iScale.axis; - const {min, max, minDefined, maxDefined} = iScale.getUserBounds(); - if (minDefined) { - start = _limitValue(Math.min( - _lookupByKey(_parsed, iScale.axis, min).lo, - animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo), - 0, pointCount - 1); - } - if (maxDefined) { - count = _limitValue(Math.max( - _lookupByKey(_parsed, iScale.axis, max).hi + 1, - animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max)).hi + 1), - start, pointCount) - start; - } else { - count = pointCount - start; - } - } - return {start, count}; -} -function scaleRangesChanged(meta) { - const {xScale, yScale, _scaleRanges} = meta; - const newRanges = { - xmin: xScale.min, - xmax: xScale.max, - ymin: yScale.min, - ymax: yScale.max - }; - if (!_scaleRanges) { - meta._scaleRanges = newRanges; - return true; - } - const changed = _scaleRanges.xmin !== xScale.min - || _scaleRanges.xmax !== xScale.max - || _scaleRanges.ymin !== yScale.min - || _scaleRanges.ymax !== yScale.max; - Object.assign(_scaleRanges, newRanges); - return changed; -} - -class PolarAreaController extends DatasetController { - constructor(chart, datasetIndex) { - super(chart, datasetIndex); - this.innerRadius = undefined; - this.outerRadius = undefined; - } - getLabelAndValue(index) { - const meta = this._cachedMeta; - const chart = this.chart; - const labels = chart.data.labels || []; - const value = formatNumber(meta._parsed[index].r, chart.options.locale); - return { - label: labels[index] || '', - value, - }; - } - update(mode) { - const arcs = this._cachedMeta.data; - this._updateRadius(); - this.updateElements(arcs, 0, arcs.length, mode); - } - _updateRadius() { - const chart = this.chart; - const chartArea = chart.chartArea; - const opts = chart.options; - const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); - const outerRadius = Math.max(minSize / 2, 0); - const innerRadius = Math.max(opts.cutoutPercentage ? (outerRadius / 100) * (opts.cutoutPercentage) : 1, 0); - const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount(); - this.outerRadius = outerRadius - (radiusLength * this.index); - this.innerRadius = this.outerRadius - radiusLength; - } - updateElements(arcs, start, count, mode) { - const reset = mode === 'reset'; - const chart = this.chart; - const dataset = this.getDataset(); - const opts = chart.options; - const animationOpts = opts.animation; - const scale = this._cachedMeta.rScale; - const centerX = scale.xCenter; - const centerY = scale.yCenter; - const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI; - let angle = datasetStartAngle; - let i; - const defaultAngle = 360 / this.countVisibleElements(); - for (i = 0; i < start; ++i) { - angle += this._computeAngle(i, mode, defaultAngle); - } - for (i = start; i < start + count; i++) { - const arc = arcs[i]; - let startAngle = angle; - let endAngle = angle + this._computeAngle(i, mode, defaultAngle); - let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(dataset.data[i]) : 0; - angle = endAngle; - if (reset) { - if (animationOpts.animateScale) { - outerRadius = 0; - } - if (animationOpts.animateRotate) { - startAngle = endAngle = datasetStartAngle; - } - } - const properties = { - x: centerX, - y: centerY, - innerRadius: 0, - outerRadius, - startAngle, - endAngle, - options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode) - }; - this.updateElement(arc, i, properties, mode); - } - } - countVisibleElements() { - const dataset = this.getDataset(); - const meta = this._cachedMeta; - let count = 0; - meta.data.forEach((element, index) => { - if (!isNaN(dataset.data[index]) && this.chart.getDataVisibility(index)) { - count++; - } - }); - return count; - } - _computeAngle(index, mode, defaultAngle) { - return this.chart.getDataVisibility(index) - ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle) - : 0; - } -} -PolarAreaController.id = 'polarArea'; -PolarAreaController.defaults = { - dataElementType: 'arc', - animation: { - animateRotate: true, - animateScale: true - }, - animations: { - numbers: { - type: 'number', - properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius'] - }, - }, - indexAxis: 'r', - startAngle: 0, -}; -PolarAreaController.overrides = { - aspectRatio: 1, - plugins: { - legend: { - labels: { - generateLabels(chart) { - const data = chart.data; - if (data.labels.length && data.datasets.length) { - const {labels: {pointStyle}} = chart.legend.options; - return data.labels.map((label, i) => { - const meta = chart.getDatasetMeta(0); - const style = meta.controller.getStyle(i); - return { - text: label, - fillStyle: style.backgroundColor, - strokeStyle: style.borderColor, - lineWidth: style.borderWidth, - pointStyle: pointStyle, - hidden: !chart.getDataVisibility(i), - index: i - }; - }); - } - return []; - } - }, - onClick(e, legendItem, legend) { - legend.chart.toggleDataVisibility(legendItem.index); - legend.chart.update(); - } - }, - tooltip: { - callbacks: { - title() { - return ''; - }, - label(context) { - return context.chart.data.labels[context.dataIndex] + ': ' + context.formattedValue; - } - } - } - }, - scales: { - r: { - type: 'radialLinear', - angleLines: { - display: false - }, - beginAtZero: true, - grid: { - circular: true - }, - pointLabels: { - display: false - }, - startAngle: 0 - } - } -}; - -class PieController extends DoughnutController { -} -PieController.id = 'pie'; -PieController.defaults = { - cutout: 0, - rotation: 0, - circumference: 360, - radius: '100%' -}; - -class RadarController extends DatasetController { - getLabelAndValue(index) { - const vScale = this._cachedMeta.vScale; - const parsed = this.getParsed(index); - return { - label: vScale.getLabels()[index], - value: '' + vScale.getLabelForValue(parsed[vScale.axis]) - }; - } - update(mode) { - const meta = this._cachedMeta; - const line = meta.dataset; - const points = meta.data || []; - const labels = meta.iScale.getLabels(); - line.points = points; - if (mode !== 'resize') { - const options = this.resolveDatasetElementOptions(mode); - if (!this.options.showLine) { - options.borderWidth = 0; - } - const properties = { - _loop: true, - _fullLoop: labels.length === points.length, - options - }; - this.updateElement(line, undefined, properties, mode); - } - this.updateElements(points, 0, points.length, mode); - } - updateElements(points, start, count, mode) { - const dataset = this.getDataset(); - const scale = this._cachedMeta.rScale; - const reset = mode === 'reset'; - for (let i = start; i < start + count; i++) { - const point = points[i]; - const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode); - const pointPosition = scale.getPointPositionForValue(i, dataset.data[i]); - const x = reset ? scale.xCenter : pointPosition.x; - const y = reset ? scale.yCenter : pointPosition.y; - const properties = { - x, - y, - angle: pointPosition.angle, - skip: isNaN(x) || isNaN(y), - options - }; - this.updateElement(point, i, properties, mode); - } - } -} -RadarController.id = 'radar'; -RadarController.defaults = { - datasetElementType: 'line', - dataElementType: 'point', - indexAxis: 'r', - showLine: true, - elements: { - line: { - fill: 'start' - } - }, -}; -RadarController.overrides = { - aspectRatio: 1, - scales: { - r: { - type: 'radialLinear', - } - } -}; - -class ScatterController extends LineController { -} -ScatterController.id = 'scatter'; -ScatterController.defaults = { - showLine: false, - fill: false -}; -ScatterController.overrides = { - interaction: { - mode: 'point' - }, - plugins: { - tooltip: { - callbacks: { - title() { - return ''; - }, - label(item) { - return '(' + item.label + ', ' + item.formattedValue + ')'; - } - } - } - }, - scales: { - x: { - type: 'linear' - }, - y: { - type: 'linear' - } - } -}; - -var controllers = /*#__PURE__*/Object.freeze({ -__proto__: null, -BarController: BarController, -BubbleController: BubbleController, -DoughnutController: DoughnutController, -LineController: LineController, -PolarAreaController: PolarAreaController, -PieController: PieController, -RadarController: RadarController, -ScatterController: ScatterController -}); - -function clipArc(ctx, element, endAngle) { - const {startAngle, pixelMargin, x, y, outerRadius, innerRadius} = element; - let angleMargin = pixelMargin / outerRadius; - ctx.beginPath(); - ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin); - if (innerRadius > pixelMargin) { - angleMargin = pixelMargin / innerRadius; - ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true); - } else { - ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI); - } - ctx.closePath(); - ctx.clip(); -} -function toRadiusCorners(value) { - return _readValueToProps(value, ['outerStart', 'outerEnd', 'innerStart', 'innerEnd']); -} -function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) { - const o = toRadiusCorners(arc.options.borderRadius); - const halfThickness = (outerRadius - innerRadius) / 2; - const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2); - const computeOuterLimit = (val) => { - const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2; - return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit)); - }; - return { - outerStart: computeOuterLimit(o.outerStart), - outerEnd: computeOuterLimit(o.outerEnd), - innerStart: _limitValue(o.innerStart, 0, innerLimit), - innerEnd: _limitValue(o.innerEnd, 0, innerLimit), - }; -} -function rThetaToXY(r, theta, x, y) { - return { - x: x + r * Math.cos(theta), - y: y + r * Math.sin(theta), - }; -} -function pathArc(ctx, element, offset, spacing, end) { - const {x, y, startAngle: start, pixelMargin, innerRadius: innerR} = element; - const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0); - const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0; - let spacingOffset = 0; - const alpha = end - start; - if (spacing) { - const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0; - const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0; - const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2; - const adjustedAngle = avNogSpacingRadius !== 0 ? (alpha * avNogSpacingRadius) / (avNogSpacingRadius + spacing) : alpha; - spacingOffset = (alpha - adjustedAngle) / 2; - } - const beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius; - const angleOffset = (alpha - beta) / 2; - const startAngle = start + angleOffset + spacingOffset; - const endAngle = end - angleOffset - spacingOffset; - const {outerStart, outerEnd, innerStart, innerEnd} = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle); - const outerStartAdjustedRadius = outerRadius - outerStart; - const outerEndAdjustedRadius = outerRadius - outerEnd; - const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius; - const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius; - const innerStartAdjustedRadius = innerRadius + innerStart; - const innerEndAdjustedRadius = innerRadius + innerEnd; - const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius; - const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius; - ctx.beginPath(); - ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerEndAdjustedAngle); - if (outerEnd > 0) { - const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y); - ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI); - } - const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y); - ctx.lineTo(p4.x, p4.y); - if (innerEnd > 0) { - const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y); - ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI); - } - ctx.arc(x, y, innerRadius, endAngle - (innerEnd / innerRadius), startAngle + (innerStart / innerRadius), true); - if (innerStart > 0) { - const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y); - ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI); - } - const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y); - ctx.lineTo(p8.x, p8.y); - if (outerStart > 0) { - const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y); - ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle); - } - ctx.closePath(); -} -function drawArc(ctx, element, offset, spacing) { - const {fullCircles, startAngle, circumference} = element; - let endAngle = element.endAngle; - if (fullCircles) { - pathArc(ctx, element, offset, spacing, startAngle + TAU); - for (let i = 0; i < fullCircles; ++i) { - ctx.fill(); - } - if (!isNaN(circumference)) { - endAngle = startAngle + circumference % TAU; - if (circumference % TAU === 0) { - endAngle += TAU; - } - } - } - pathArc(ctx, element, offset, spacing, endAngle); - ctx.fill(); - return endAngle; -} -function drawFullCircleBorders(ctx, element, inner) { - const {x, y, startAngle, pixelMargin, fullCircles} = element; - const outerRadius = Math.max(element.outerRadius - pixelMargin, 0); - const innerRadius = element.innerRadius + pixelMargin; - let i; - if (inner) { - clipArc(ctx, element, startAngle + TAU); - } - ctx.beginPath(); - ctx.arc(x, y, innerRadius, startAngle + TAU, startAngle, true); - for (i = 0; i < fullCircles; ++i) { - ctx.stroke(); - } - ctx.beginPath(); - ctx.arc(x, y, outerRadius, startAngle, startAngle + TAU); - for (i = 0; i < fullCircles; ++i) { - ctx.stroke(); - } -} -function drawBorder(ctx, element, offset, spacing, endAngle) { - const {options} = element; - const {borderWidth, borderJoinStyle} = options; - const inner = options.borderAlign === 'inner'; - if (!borderWidth) { - return; - } - if (inner) { - ctx.lineWidth = borderWidth * 2; - ctx.lineJoin = borderJoinStyle || 'round'; - } else { - ctx.lineWidth = borderWidth; - ctx.lineJoin = borderJoinStyle || 'bevel'; - } - if (element.fullCircles) { - drawFullCircleBorders(ctx, element, inner); - } - if (inner) { - clipArc(ctx, element, endAngle); - } - pathArc(ctx, element, offset, spacing, endAngle); - ctx.stroke(); -} -class ArcElement extends Element { - constructor(cfg) { - super(); - this.options = undefined; - this.circumference = undefined; - this.startAngle = undefined; - this.endAngle = undefined; - this.innerRadius = undefined; - this.outerRadius = undefined; - this.pixelMargin = 0; - this.fullCircles = 0; - if (cfg) { - Object.assign(this, cfg); - } - } - inRange(chartX, chartY, useFinalPosition) { - const point = this.getProps(['x', 'y'], useFinalPosition); - const {angle, distance} = getAngleFromPoint(point, {x: chartX, y: chartY}); - const {startAngle, endAngle, innerRadius, outerRadius, circumference} = this.getProps([ - 'startAngle', - 'endAngle', - 'innerRadius', - 'outerRadius', - 'circumference' - ], useFinalPosition); - const rAdjust = this.options.spacing / 2; - const _circumference = valueOrDefault(circumference, endAngle - startAngle); - const betweenAngles = _circumference >= TAU || _angleBetween(angle, startAngle, endAngle); - const withinRadius = _isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust); - return (betweenAngles && withinRadius); - } - getCenterPoint(useFinalPosition) { - const {x, y, startAngle, endAngle, innerRadius, outerRadius} = this.getProps([ - 'x', - 'y', - 'startAngle', - 'endAngle', - 'innerRadius', - 'outerRadius', - 'circumference', - ], useFinalPosition); - const {offset, spacing} = this.options; - const halfAngle = (startAngle + endAngle) / 2; - const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2; - return { - x: x + Math.cos(halfAngle) * halfRadius, - y: y + Math.sin(halfAngle) * halfRadius - }; - } - tooltipPosition(useFinalPosition) { - return this.getCenterPoint(useFinalPosition); - } - draw(ctx) { - const {options, circumference} = this; - const offset = (options.offset || 0) / 2; - const spacing = (options.spacing || 0) / 2; - this.pixelMargin = (options.borderAlign === 'inner') ? 0.33 : 0; - this.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0; - if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) { - return; - } - ctx.save(); - let radiusOffset = 0; - if (offset) { - radiusOffset = offset / 2; - const halfAngle = (this.startAngle + this.endAngle) / 2; - ctx.translate(Math.cos(halfAngle) * radiusOffset, Math.sin(halfAngle) * radiusOffset); - if (this.circumference >= PI) { - radiusOffset = offset; - } - } - ctx.fillStyle = options.backgroundColor; - ctx.strokeStyle = options.borderColor; - const endAngle = drawArc(ctx, this, radiusOffset, spacing); - drawBorder(ctx, this, radiusOffset, spacing, endAngle); - ctx.restore(); - } -} -ArcElement.id = 'arc'; -ArcElement.defaults = { - borderAlign: 'center', - borderColor: '#fff', - borderJoinStyle: undefined, - borderRadius: 0, - borderWidth: 2, - offset: 0, - spacing: 0, - angle: undefined, -}; -ArcElement.defaultRoutes = { - backgroundColor: 'backgroundColor' -}; - -function setStyle(ctx, options, style = options) { - ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle); - ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash)); - ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset); - ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle); - ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth); - ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor); -} -function lineTo(ctx, previous, target) { - ctx.lineTo(target.x, target.y); -} -function getLineMethod(options) { - if (options.stepped) { - return _steppedLineTo; - } - if (options.tension || options.cubicInterpolationMode === 'monotone') { - return _bezierCurveTo; - } - return lineTo; -} -function pathVars(points, segment, params = {}) { - const count = points.length; - const {start: paramsStart = 0, end: paramsEnd = count - 1} = params; - const {start: segmentStart, end: segmentEnd} = segment; - const start = Math.max(paramsStart, segmentStart); - const end = Math.min(paramsEnd, segmentEnd); - const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd; - return { - count, - start, - loop: segment.loop, - ilen: end < start && !outside ? count + end - start : end - start - }; -} -function pathSegment(ctx, line, segment, params) { - const {points, options} = line; - const {count, start, loop, ilen} = pathVars(points, segment, params); - const lineMethod = getLineMethod(options); - let {move = true, reverse} = params || {}; - let i, point, prev; - for (i = 0; i <= ilen; ++i) { - point = points[(start + (reverse ? ilen - i : i)) % count]; - if (point.skip) { - continue; - } else if (move) { - ctx.moveTo(point.x, point.y); - move = false; - } else { - lineMethod(ctx, prev, point, reverse, options.stepped); - } - prev = point; - } - if (loop) { - point = points[(start + (reverse ? ilen : 0)) % count]; - lineMethod(ctx, prev, point, reverse, options.stepped); - } - return !!loop; -} -function fastPathSegment(ctx, line, segment, params) { - const points = line.points; - const {count, start, ilen} = pathVars(points, segment, params); - const {move = true, reverse} = params || {}; - let avgX = 0; - let countX = 0; - let i, point, prevX, minY, maxY, lastY; - const pointIndex = (index) => (start + (reverse ? ilen - index : index)) % count; - const drawX = () => { - if (minY !== maxY) { - ctx.lineTo(avgX, maxY); - ctx.lineTo(avgX, minY); - ctx.lineTo(avgX, lastY); - } - }; - if (move) { - point = points[pointIndex(0)]; - ctx.moveTo(point.x, point.y); - } - for (i = 0; i <= ilen; ++i) { - point = points[pointIndex(i)]; - if (point.skip) { - continue; - } - const x = point.x; - const y = point.y; - const truncX = x | 0; - if (truncX === prevX) { - if (y < minY) { - minY = y; - } else if (y > maxY) { - maxY = y; - } - avgX = (countX * avgX + x) / ++countX; - } else { - drawX(); - ctx.lineTo(x, y); - prevX = truncX; - countX = 0; - minY = maxY = y; - } - lastY = y; - } - drawX(); -} -function _getSegmentMethod(line) { - const opts = line.options; - const borderDash = opts.borderDash && opts.borderDash.length; - const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash; - return useFastPath ? fastPathSegment : pathSegment; -} -function _getInterpolationMethod(options) { - if (options.stepped) { - return _steppedInterpolation; - } - if (options.tension || options.cubicInterpolationMode === 'monotone') { - return _bezierInterpolation; - } - return _pointInLine; -} -function strokePathWithCache(ctx, line, start, count) { - let path = line._path; - if (!path) { - path = line._path = new Path2D(); - if (line.path(path, start, count)) { - path.closePath(); - } - } - setStyle(ctx, line.options); - ctx.stroke(path); -} -function strokePathDirect(ctx, line, start, count) { - const {segments, options} = line; - const segmentMethod = _getSegmentMethod(line); - for (const segment of segments) { - setStyle(ctx, options, segment.style); - ctx.beginPath(); - if (segmentMethod(ctx, line, segment, {start, end: start + count - 1})) { - ctx.closePath(); - } - ctx.stroke(); - } -} -const usePath2D = typeof Path2D === 'function'; -function draw(ctx, line, start, count) { - if (usePath2D && !line.options.segment) { - strokePathWithCache(ctx, line, start, count); - } else { - strokePathDirect(ctx, line, start, count); - } -} -class LineElement extends Element { - constructor(cfg) { - super(); - this.animated = true; - this.options = undefined; - this._chart = undefined; - this._loop = undefined; - this._fullLoop = undefined; - this._path = undefined; - this._points = undefined; - this._segments = undefined; - this._decimated = false; - this._pointsUpdated = false; - this._datasetIndex = undefined; - if (cfg) { - Object.assign(this, cfg); - } - } - updateControlPoints(chartArea, indexAxis) { - const options = this.options; - if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) { - const loop = options.spanGaps ? this._loop : this._fullLoop; - _updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis); - this._pointsUpdated = true; - } - } - set points(points) { - this._points = points; - delete this._segments; - delete this._path; - this._pointsUpdated = false; - } - get points() { - return this._points; - } - get segments() { - return this._segments || (this._segments = _computeSegments(this, this.options.segment)); - } - first() { - const segments = this.segments; - const points = this.points; - return segments.length && points[segments[0].start]; - } - last() { - const segments = this.segments; - const points = this.points; - const count = segments.length; - return count && points[segments[count - 1].end]; - } - interpolate(point, property) { - const options = this.options; - const value = point[property]; - const points = this.points; - const segments = _boundSegments(this, {property, start: value, end: value}); - if (!segments.length) { - return; - } - const result = []; - const _interpolate = _getInterpolationMethod(options); - let i, ilen; - for (i = 0, ilen = segments.length; i < ilen; ++i) { - const {start, end} = segments[i]; - const p1 = points[start]; - const p2 = points[end]; - if (p1 === p2) { - result.push(p1); - continue; - } - const t = Math.abs((value - p1[property]) / (p2[property] - p1[property])); - const interpolated = _interpolate(p1, p2, t, options.stepped); - interpolated[property] = point[property]; - result.push(interpolated); - } - return result.length === 1 ? result[0] : result; - } - pathSegment(ctx, segment, params) { - const segmentMethod = _getSegmentMethod(this); - return segmentMethod(ctx, this, segment, params); - } - path(ctx, start, count) { - const segments = this.segments; - const segmentMethod = _getSegmentMethod(this); - let loop = this._loop; - start = start || 0; - count = count || (this.points.length - start); - for (const segment of segments) { - loop &= segmentMethod(ctx, this, segment, {start, end: start + count - 1}); - } - return !!loop; - } - draw(ctx, chartArea, start, count) { - const options = this.options || {}; - const points = this.points || []; - if (points.length && options.borderWidth) { - ctx.save(); - draw(ctx, this, start, count); - ctx.restore(); - } - if (this.animated) { - this._pointsUpdated = false; - this._path = undefined; - } - } -} -LineElement.id = 'line'; -LineElement.defaults = { - borderCapStyle: 'butt', - borderDash: [], - borderDashOffset: 0, - borderJoinStyle: 'miter', - borderWidth: 3, - capBezierPoints: true, - cubicInterpolationMode: 'default', - fill: false, - spanGaps: false, - stepped: false, - tension: 0, -}; -LineElement.defaultRoutes = { - backgroundColor: 'backgroundColor', - borderColor: 'borderColor' -}; -LineElement.descriptors = { - _scriptable: true, - _indexable: (name) => name !== 'borderDash' && name !== 'fill', -}; - -function inRange$1(el, pos, axis, useFinalPosition) { - const options = el.options; - const {[axis]: value} = el.getProps([axis], useFinalPosition); - return (Math.abs(pos - value) < options.radius + options.hitRadius); -} -class PointElement extends Element { - constructor(cfg) { - super(); - this.options = undefined; - this.parsed = undefined; - this.skip = undefined; - this.stop = undefined; - if (cfg) { - Object.assign(this, cfg); - } - } - inRange(mouseX, mouseY, useFinalPosition) { - const options = this.options; - const {x, y} = this.getProps(['x', 'y'], useFinalPosition); - return ((Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2)) < Math.pow(options.hitRadius + options.radius, 2)); - } - inXRange(mouseX, useFinalPosition) { - return inRange$1(this, mouseX, 'x', useFinalPosition); - } - inYRange(mouseY, useFinalPosition) { - return inRange$1(this, mouseY, 'y', useFinalPosition); - } - getCenterPoint(useFinalPosition) { - const {x, y} = this.getProps(['x', 'y'], useFinalPosition); - return {x, y}; - } - size(options) { - options = options || this.options || {}; - let radius = options.radius || 0; - radius = Math.max(radius, radius && options.hoverRadius || 0); - const borderWidth = radius && options.borderWidth || 0; - return (radius + borderWidth) * 2; - } - draw(ctx, area) { - const options = this.options; - if (this.skip || options.radius < 0.1 || !_isPointInArea(this, area, this.size(options) / 2)) { - return; - } - ctx.strokeStyle = options.borderColor; - ctx.lineWidth = options.borderWidth; - ctx.fillStyle = options.backgroundColor; - drawPoint(ctx, options, this.x, this.y); - } - getRange() { - const options = this.options || {}; - return options.radius + options.hitRadius; - } -} -PointElement.id = 'point'; -PointElement.defaults = { - borderWidth: 1, - hitRadius: 1, - hoverBorderWidth: 1, - hoverRadius: 4, - pointStyle: 'circle', - radius: 3, - rotation: 0 -}; -PointElement.defaultRoutes = { - backgroundColor: 'backgroundColor', - borderColor: 'borderColor' -}; - -function getBarBounds(bar, useFinalPosition) { - const {x, y, base, width, height} = bar.getProps(['x', 'y', 'base', 'width', 'height'], useFinalPosition); - let left, right, top, bottom, half; - if (bar.horizontal) { - half = height / 2; - left = Math.min(x, base); - right = Math.max(x, base); - top = y - half; - bottom = y + half; - } else { - half = width / 2; - left = x - half; - right = x + half; - top = Math.min(y, base); - bottom = Math.max(y, base); - } - return {left, top, right, bottom}; -} -function skipOrLimit(skip, value, min, max) { - return skip ? 0 : _limitValue(value, min, max); -} -function parseBorderWidth(bar, maxW, maxH) { - const value = bar.options.borderWidth; - const skip = bar.borderSkipped; - const o = toTRBL(value); - return { - t: skipOrLimit(skip.top, o.top, 0, maxH), - r: skipOrLimit(skip.right, o.right, 0, maxW), - b: skipOrLimit(skip.bottom, o.bottom, 0, maxH), - l: skipOrLimit(skip.left, o.left, 0, maxW) - }; -} -function parseBorderRadius(bar, maxW, maxH) { - const {enableBorderRadius} = bar.getProps(['enableBorderRadius']); - const value = bar.options.borderRadius; - const o = toTRBLCorners(value); - const maxR = Math.min(maxW, maxH); - const skip = bar.borderSkipped; - const enableBorder = enableBorderRadius || isObject(value); - return { - topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR), - topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR), - bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR), - bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR) - }; -} -function boundingRects(bar) { - const bounds = getBarBounds(bar); - const width = bounds.right - bounds.left; - const height = bounds.bottom - bounds.top; - const border = parseBorderWidth(bar, width / 2, height / 2); - const radius = parseBorderRadius(bar, width / 2, height / 2); - return { - outer: { - x: bounds.left, - y: bounds.top, - w: width, - h: height, - radius - }, - inner: { - x: bounds.left + border.l, - y: bounds.top + border.t, - w: width - border.l - border.r, - h: height - border.t - border.b, - radius: { - topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)), - topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)), - bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)), - bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r)), - } - } - }; -} -function inRange(bar, x, y, useFinalPosition) { - const skipX = x === null; - const skipY = y === null; - const skipBoth = skipX && skipY; - const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition); - return bounds - && (skipX || _isBetween(x, bounds.left, bounds.right)) - && (skipY || _isBetween(y, bounds.top, bounds.bottom)); -} -function hasRadius(radius) { - return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight; -} -function addNormalRectPath(ctx, rect) { - ctx.rect(rect.x, rect.y, rect.w, rect.h); -} -function inflateRect(rect, amount, refRect = {}) { - const x = rect.x !== refRect.x ? -amount : 0; - const y = rect.y !== refRect.y ? -amount : 0; - const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x; - const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y; - return { - x: rect.x + x, - y: rect.y + y, - w: rect.w + w, - h: rect.h + h, - radius: rect.radius - }; -} -class BarElement extends Element { - constructor(cfg) { - super(); - this.options = undefined; - this.horizontal = undefined; - this.base = undefined; - this.width = undefined; - this.height = undefined; - this.inflateAmount = undefined; - if (cfg) { - Object.assign(this, cfg); - } - } - draw(ctx) { - const {inflateAmount, options: {borderColor, backgroundColor}} = this; - const {inner, outer} = boundingRects(this); - const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath; - ctx.save(); - if (outer.w !== inner.w || outer.h !== inner.h) { - ctx.beginPath(); - addRectPath(ctx, inflateRect(outer, inflateAmount, inner)); - ctx.clip(); - addRectPath(ctx, inflateRect(inner, -inflateAmount, outer)); - ctx.fillStyle = borderColor; - ctx.fill('evenodd'); - } - ctx.beginPath(); - addRectPath(ctx, inflateRect(inner, inflateAmount)); - ctx.fillStyle = backgroundColor; - ctx.fill(); - ctx.restore(); - } - inRange(mouseX, mouseY, useFinalPosition) { - return inRange(this, mouseX, mouseY, useFinalPosition); - } - inXRange(mouseX, useFinalPosition) { - return inRange(this, mouseX, null, useFinalPosition); - } - inYRange(mouseY, useFinalPosition) { - return inRange(this, null, mouseY, useFinalPosition); - } - getCenterPoint(useFinalPosition) { - const {x, y, base, horizontal} = this.getProps(['x', 'y', 'base', 'horizontal'], useFinalPosition); - return { - x: horizontal ? (x + base) / 2 : x, - y: horizontal ? y : (y + base) / 2 - }; - } - getRange(axis) { - return axis === 'x' ? this.width / 2 : this.height / 2; - } -} -BarElement.id = 'bar'; -BarElement.defaults = { - borderSkipped: 'start', - borderWidth: 0, - borderRadius: 0, - inflateAmount: 'auto', - pointStyle: undefined -}; -BarElement.defaultRoutes = { - backgroundColor: 'backgroundColor', - borderColor: 'borderColor' -}; - -var elements = /*#__PURE__*/Object.freeze({ -__proto__: null, -ArcElement: ArcElement, -LineElement: LineElement, -PointElement: PointElement, -BarElement: BarElement -}); - -function lttbDecimation(data, start, count, availableWidth, options) { - const samples = options.samples || availableWidth; - if (samples >= count) { - return data.slice(start, start + count); - } - const decimated = []; - const bucketWidth = (count - 2) / (samples - 2); - let sampledIndex = 0; - const endIndex = start + count - 1; - let a = start; - let i, maxAreaPoint, maxArea, area, nextA; - decimated[sampledIndex++] = data[a]; - for (i = 0; i < samples - 2; i++) { - let avgX = 0; - let avgY = 0; - let j; - const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start; - const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start; - const avgRangeLength = avgRangeEnd - avgRangeStart; - for (j = avgRangeStart; j < avgRangeEnd; j++) { - avgX += data[j].x; - avgY += data[j].y; - } - avgX /= avgRangeLength; - avgY /= avgRangeLength; - const rangeOffs = Math.floor(i * bucketWidth) + 1 + start; - const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start; - const {x: pointAx, y: pointAy} = data[a]; - maxArea = area = -1; - for (j = rangeOffs; j < rangeTo; j++) { - area = 0.5 * Math.abs( - (pointAx - avgX) * (data[j].y - pointAy) - - (pointAx - data[j].x) * (avgY - pointAy) - ); - if (area > maxArea) { - maxArea = area; - maxAreaPoint = data[j]; - nextA = j; - } - } - decimated[sampledIndex++] = maxAreaPoint; - a = nextA; - } - decimated[sampledIndex++] = data[endIndex]; - return decimated; -} -function minMaxDecimation(data, start, count, availableWidth) { - let avgX = 0; - let countX = 0; - let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY; - const decimated = []; - const endIndex = start + count - 1; - const xMin = data[start].x; - const xMax = data[endIndex].x; - const dx = xMax - xMin; - for (i = start; i < start + count; ++i) { - point = data[i]; - x = (point.x - xMin) / dx * availableWidth; - y = point.y; - const truncX = x | 0; - if (truncX === prevX) { - if (y < minY) { - minY = y; - minIndex = i; - } else if (y > maxY) { - maxY = y; - maxIndex = i; - } - avgX = (countX * avgX + point.x) / ++countX; - } else { - const lastIndex = i - 1; - if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) { - const intermediateIndex1 = Math.min(minIndex, maxIndex); - const intermediateIndex2 = Math.max(minIndex, maxIndex); - if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) { - decimated.push({ - ...data[intermediateIndex1], - x: avgX, - }); - } - if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) { - decimated.push({ - ...data[intermediateIndex2], - x: avgX - }); - } - } - if (i > 0 && lastIndex !== startIndex) { - decimated.push(data[lastIndex]); - } - decimated.push(point); - prevX = truncX; - countX = 0; - minY = maxY = y; - minIndex = maxIndex = startIndex = i; - } - } - return decimated; -} -function cleanDecimatedDataset(dataset) { - if (dataset._decimated) { - const data = dataset._data; - delete dataset._decimated; - delete dataset._data; - Object.defineProperty(dataset, 'data', {value: data}); - } -} -function cleanDecimatedData(chart) { - chart.data.datasets.forEach((dataset) => { - cleanDecimatedDataset(dataset); - }); -} -function getStartAndCountOfVisiblePointsSimplified(meta, points) { - const pointCount = points.length; - let start = 0; - let count; - const {iScale} = meta; - const {min, max, minDefined, maxDefined} = iScale.getUserBounds(); - if (minDefined) { - start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1); - } - if (maxDefined) { - count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start; - } else { - count = pointCount - start; - } - return {start, count}; -} -var plugin_decimation = { - id: 'decimation', - defaults: { - algorithm: 'min-max', - enabled: false, - }, - beforeElementsUpdate: (chart, args, options) => { - if (!options.enabled) { - cleanDecimatedData(chart); - return; - } - const availableWidth = chart.width; - chart.data.datasets.forEach((dataset, datasetIndex) => { - const {_data, indexAxis} = dataset; - const meta = chart.getDatasetMeta(datasetIndex); - const data = _data || dataset.data; - if (resolve([indexAxis, chart.options.indexAxis]) === 'y') { - return; - } - if (meta.type !== 'line') { - return; - } - const xAxis = chart.scales[meta.xAxisID]; - if (xAxis.type !== 'linear' && xAxis.type !== 'time') { - return; - } - if (chart.options.parsing) { - return; - } - let {start, count} = getStartAndCountOfVisiblePointsSimplified(meta, data); - const threshold = options.threshold || 4 * availableWidth; - if (count <= threshold) { - cleanDecimatedDataset(dataset); - return; - } - if (isNullOrUndef(_data)) { - dataset._data = data; - delete dataset.data; - Object.defineProperty(dataset, 'data', { - configurable: true, - enumerable: true, - get: function() { - return this._decimated; - }, - set: function(d) { - this._data = d; - } - }); - } - let decimated; - switch (options.algorithm) { - case 'lttb': - decimated = lttbDecimation(data, start, count, availableWidth, options); - break; - case 'min-max': - decimated = minMaxDecimation(data, start, count, availableWidth); - break; - default: - throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`); - } - dataset._decimated = decimated; - }); - }, - destroy(chart) { - cleanDecimatedData(chart); - } -}; - -function getLineByIndex(chart, index) { - const meta = chart.getDatasetMeta(index); - const visible = meta && chart.isDatasetVisible(index); - return visible ? meta.dataset : null; -} -function parseFillOption(line) { - const options = line.options; - const fillOption = options.fill; - let fill = valueOrDefault(fillOption && fillOption.target, fillOption); - if (fill === undefined) { - fill = !!options.backgroundColor; - } - if (fill === false || fill === null) { - return false; - } - if (fill === true) { - return 'origin'; - } - return fill; -} -function decodeFill(line, index, count) { - const fill = parseFillOption(line); - if (isObject(fill)) { - return isNaN(fill.value) ? false : fill; - } - let target = parseFloat(fill); - if (isNumberFinite(target) && Math.floor(target) === target) { - if (fill[0] === '-' || fill[0] === '+') { - target = index + target; - } - if (target === index || target < 0 || target >= count) { - return false; - } - return target; - } - return ['origin', 'start', 'end', 'stack', 'shape'].indexOf(fill) >= 0 && fill; -} -function computeLinearBoundary(source) { - const {scale = {}, fill} = source; - let target = null; - let horizontal; - if (fill === 'start') { - target = scale.bottom; - } else if (fill === 'end') { - target = scale.top; - } else if (isObject(fill)) { - target = scale.getPixelForValue(fill.value); - } else if (scale.getBasePixel) { - target = scale.getBasePixel(); - } - if (isNumberFinite(target)) { - horizontal = scale.isHorizontal(); - return { - x: horizontal ? target : null, - y: horizontal ? null : target - }; - } - return null; -} -class simpleArc { - constructor(opts) { - this.x = opts.x; - this.y = opts.y; - this.radius = opts.radius; - } - pathSegment(ctx, bounds, opts) { - const {x, y, radius} = this; - bounds = bounds || {start: 0, end: TAU}; - ctx.arc(x, y, radius, bounds.end, bounds.start, true); - return !opts.bounds; - } - interpolate(point) { - const {x, y, radius} = this; - const angle = point.angle; - return { - x: x + Math.cos(angle) * radius, - y: y + Math.sin(angle) * radius, - angle - }; - } -} -function computeCircularBoundary(source) { - const {scale, fill} = source; - const options = scale.options; - const length = scale.getLabels().length; - const target = []; - const start = options.reverse ? scale.max : scale.min; - const end = options.reverse ? scale.min : scale.max; - let i, center, value; - if (fill === 'start') { - value = start; - } else if (fill === 'end') { - value = end; - } else if (isObject(fill)) { - value = fill.value; - } else { - value = scale.getBaseValue(); - } - if (options.grid.circular) { - center = scale.getPointPositionForValue(0, start); - return new simpleArc({ - x: center.x, - y: center.y, - radius: scale.getDistanceFromCenterForValue(value) - }); - } - for (i = 0; i < length; ++i) { - target.push(scale.getPointPositionForValue(i, value)); - } - return target; -} -function computeBoundary(source) { - const scale = source.scale || {}; - if (scale.getPointPositionForValue) { - return computeCircularBoundary(source); - } - return computeLinearBoundary(source); -} -function findSegmentEnd(start, end, points) { - for (;end > start; end--) { - const point = points[end]; - if (!isNaN(point.x) && !isNaN(point.y)) { - break; - } - } - return end; -} -function pointsFromSegments(boundary, line) { - const {x = null, y = null} = boundary || {}; - const linePoints = line.points; - const points = []; - line.segments.forEach(({start, end}) => { - end = findSegmentEnd(start, end, linePoints); - const first = linePoints[start]; - const last = linePoints[end]; - if (y !== null) { - points.push({x: first.x, y}); - points.push({x: last.x, y}); - } else if (x !== null) { - points.push({x, y: first.y}); - points.push({x, y: last.y}); - } - }); - return points; -} -function buildStackLine(source) { - const {scale, index, line} = source; - const points = []; - const segments = line.segments; - const sourcePoints = line.points; - const linesBelow = getLinesBelow(scale, index); - linesBelow.push(createBoundaryLine({x: null, y: scale.bottom}, line)); - for (let i = 0; i < segments.length; i++) { - const segment = segments[i]; - for (let j = segment.start; j <= segment.end; j++) { - addPointsBelow(points, sourcePoints[j], linesBelow); - } - } - return new LineElement({points, options: {}}); -} -function getLinesBelow(scale, index) { - const below = []; - const metas = scale.getMatchingVisibleMetas('line'); - for (let i = 0; i < metas.length; i++) { - const meta = metas[i]; - if (meta.index === index) { - break; - } - if (!meta.hidden) { - below.unshift(meta.dataset); - } - } - return below; -} -function addPointsBelow(points, sourcePoint, linesBelow) { - const postponed = []; - for (let j = 0; j < linesBelow.length; j++) { - const line = linesBelow[j]; - const {first, last, point} = findPoint(line, sourcePoint, 'x'); - if (!point || (first && last)) { - continue; - } - if (first) { - postponed.unshift(point); - } else { - points.push(point); - if (!last) { - break; - } - } - } - points.push(...postponed); -} -function findPoint(line, sourcePoint, property) { - const point = line.interpolate(sourcePoint, property); - if (!point) { - return {}; - } - const pointValue = point[property]; - const segments = line.segments; - const linePoints = line.points; - let first = false; - let last = false; - for (let i = 0; i < segments.length; i++) { - const segment = segments[i]; - const firstValue = linePoints[segment.start][property]; - const lastValue = linePoints[segment.end][property]; - if (_isBetween(pointValue, firstValue, lastValue)) { - first = pointValue === firstValue; - last = pointValue === lastValue; - break; - } - } - return {first, last, point}; -} -function getTarget(source) { - const {chart, fill, line} = source; - if (isNumberFinite(fill)) { - return getLineByIndex(chart, fill); - } - if (fill === 'stack') { - return buildStackLine(source); - } - if (fill === 'shape') { - return true; - } - const boundary = computeBoundary(source); - if (boundary instanceof simpleArc) { - return boundary; - } - return createBoundaryLine(boundary, line); -} -function createBoundaryLine(boundary, line) { - let points = []; - let _loop = false; - if (isArray(boundary)) { - _loop = true; - points = boundary; - } else { - points = pointsFromSegments(boundary, line); - } - return points.length ? new LineElement({ - points, - options: {tension: 0}, - _loop, - _fullLoop: _loop - }) : null; -} -function resolveTarget(sources, index, propagate) { - const source = sources[index]; - let fill = source.fill; - const visited = [index]; - let target; - if (!propagate) { - return fill; - } - while (fill !== false && visited.indexOf(fill) === -1) { - if (!isNumberFinite(fill)) { - return fill; - } - target = sources[fill]; - if (!target) { - return false; - } - if (target.visible) { - return fill; - } - visited.push(fill); - fill = target.fill; - } - return false; -} -function _clip(ctx, target, clipY) { - const {segments, points} = target; - let first = true; - let lineLoop = false; - ctx.beginPath(); - for (const segment of segments) { - const {start, end} = segment; - const firstPoint = points[start]; - const lastPoint = points[findSegmentEnd(start, end, points)]; - if (first) { - ctx.moveTo(firstPoint.x, firstPoint.y); - first = false; - } else { - ctx.lineTo(firstPoint.x, clipY); - ctx.lineTo(firstPoint.x, firstPoint.y); - } - lineLoop = !!target.pathSegment(ctx, segment, {move: lineLoop}); - if (lineLoop) { - ctx.closePath(); - } else { - ctx.lineTo(lastPoint.x, clipY); - } - } - ctx.lineTo(target.first().x, clipY); - ctx.closePath(); - ctx.clip(); -} -function getBounds(property, first, last, loop) { - if (loop) { - return; - } - let start = first[property]; - let end = last[property]; - if (property === 'angle') { - start = _normalizeAngle(start); - end = _normalizeAngle(end); - } - return {property, start, end}; -} -function _getEdge(a, b, prop, fn) { - if (a && b) { - return fn(a[prop], b[prop]); - } - return a ? a[prop] : b ? b[prop] : 0; -} -function _segments(line, target, property) { - const segments = line.segments; - const points = line.points; - const tpoints = target.points; - const parts = []; - for (const segment of segments) { - let {start, end} = segment; - end = findSegmentEnd(start, end, points); - const bounds = getBounds(property, points[start], points[end], segment.loop); - if (!target.segments) { - parts.push({ - source: segment, - target: bounds, - start: points[start], - end: points[end] - }); - continue; - } - const targetSegments = _boundSegments(target, bounds); - for (const tgt of targetSegments) { - const subBounds = getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop); - const fillSources = _boundSegment(segment, points, subBounds); - for (const fillSource of fillSources) { - parts.push({ - source: fillSource, - target: tgt, - start: { - [property]: _getEdge(bounds, subBounds, 'start', Math.max) - }, - end: { - [property]: _getEdge(bounds, subBounds, 'end', Math.min) - } - }); - } - } - } - return parts; -} -function clipBounds(ctx, scale, bounds) { - const {top, bottom} = scale.chart.chartArea; - const {property, start, end} = bounds || {}; - if (property === 'x') { - ctx.beginPath(); - ctx.rect(start, top, end - start, bottom - top); - ctx.clip(); - } -} -function interpolatedLineTo(ctx, target, point, property) { - const interpolatedPoint = target.interpolate(point, property); - if (interpolatedPoint) { - ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y); - } -} -function _fill(ctx, cfg) { - const {line, target, property, color, scale} = cfg; - const segments = _segments(line, target, property); - for (const {source: src, target: tgt, start, end} of segments) { - const {style: {backgroundColor = color} = {}} = src; - const notShape = target !== true; - ctx.save(); - ctx.fillStyle = backgroundColor; - clipBounds(ctx, scale, notShape && getBounds(property, start, end)); - ctx.beginPath(); - const lineLoop = !!line.pathSegment(ctx, src); - let loop; - if (notShape) { - if (lineLoop) { - ctx.closePath(); - } else { - interpolatedLineTo(ctx, target, end, property); - } - const targetLoop = !!target.pathSegment(ctx, tgt, {move: lineLoop, reverse: true}); - loop = lineLoop && targetLoop; - if (!loop) { - interpolatedLineTo(ctx, target, start, property); - } - } - ctx.closePath(); - ctx.fill(loop ? 'evenodd' : 'nonzero'); - ctx.restore(); - } -} -function doFill(ctx, cfg) { - const {line, target, above, below, area, scale} = cfg; - const property = line._loop ? 'angle' : cfg.axis; - ctx.save(); - if (property === 'x' && below !== above) { - _clip(ctx, target, area.top); - _fill(ctx, {line, target, color: above, scale, property}); - ctx.restore(); - ctx.save(); - _clip(ctx, target, area.bottom); - } - _fill(ctx, {line, target, color: below, scale, property}); - ctx.restore(); -} -function drawfill(ctx, source, area) { - const target = getTarget(source); - const {line, scale, axis} = source; - const lineOpts = line.options; - const fillOption = lineOpts.fill; - const color = lineOpts.backgroundColor; - const {above = color, below = color} = fillOption || {}; - if (target && line.points.length) { - clipArea(ctx, area); - doFill(ctx, {line, target, above, below, area, scale, axis}); - unclipArea(ctx); - } -} -var plugin_filler = { - id: 'filler', - afterDatasetsUpdate(chart, _args, options) { - const count = (chart.data.datasets || []).length; - const sources = []; - let meta, i, line, source; - for (i = 0; i < count; ++i) { - meta = chart.getDatasetMeta(i); - line = meta.dataset; - source = null; - if (line && line.options && line instanceof LineElement) { - source = { - visible: chart.isDatasetVisible(i), - index: i, - fill: decodeFill(line, i, count), - chart, - axis: meta.controller.options.indexAxis, - scale: meta.vScale, - line, - }; - } - meta.$filler = source; - sources.push(source); - } - for (i = 0; i < count; ++i) { - source = sources[i]; - if (!source || source.fill === false) { - continue; - } - source.fill = resolveTarget(sources, i, options.propagate); - } - }, - beforeDraw(chart, _args, options) { - const draw = options.drawTime === 'beforeDraw'; - const metasets = chart.getSortedVisibleDatasetMetas(); - const area = chart.chartArea; - for (let i = metasets.length - 1; i >= 0; --i) { - const source = metasets[i].$filler; - if (!source) { - continue; - } - source.line.updateControlPoints(area, source.axis); - if (draw) { - drawfill(chart.ctx, source, area); - } - } - }, - beforeDatasetsDraw(chart, _args, options) { - if (options.drawTime !== 'beforeDatasetsDraw') { - return; - } - const metasets = chart.getSortedVisibleDatasetMetas(); - for (let i = metasets.length - 1; i >= 0; --i) { - const source = metasets[i].$filler; - if (source) { - drawfill(chart.ctx, source, chart.chartArea); - } - } - }, - beforeDatasetDraw(chart, args, options) { - const source = args.meta.$filler; - if (!source || source.fill === false || options.drawTime !== 'beforeDatasetDraw') { - return; - } - drawfill(chart.ctx, source, chart.chartArea); - }, - defaults: { - propagate: true, - drawTime: 'beforeDatasetDraw' - } -}; - -const getBoxSize = (labelOpts, fontSize) => { - let {boxHeight = fontSize, boxWidth = fontSize} = labelOpts; - if (labelOpts.usePointStyle) { - boxHeight = Math.min(boxHeight, fontSize); - boxWidth = Math.min(boxWidth, fontSize); - } - return { - boxWidth, - boxHeight, - itemHeight: Math.max(fontSize, boxHeight) - }; -}; -const itemsEqual = (a, b) => a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index; -class Legend extends Element { - constructor(config) { - super(); - this._added = false; - this.legendHitBoxes = []; - this._hoveredItem = null; - this.doughnutMode = false; - this.chart = config.chart; - this.options = config.options; - this.ctx = config.ctx; - this.legendItems = undefined; - this.columnSizes = undefined; - this.lineWidths = undefined; - this.maxHeight = undefined; - this.maxWidth = undefined; - this.top = undefined; - this.bottom = undefined; - this.left = undefined; - this.right = undefined; - this.height = undefined; - this.width = undefined; - this._margins = undefined; - this.position = undefined; - this.weight = undefined; - this.fullSize = undefined; - } - update(maxWidth, maxHeight, margins) { - this.maxWidth = maxWidth; - this.maxHeight = maxHeight; - this._margins = margins; - this.setDimensions(); - this.buildLabels(); - this.fit(); - } - setDimensions() { - if (this.isHorizontal()) { - this.width = this.maxWidth; - this.left = this._margins.left; - this.right = this.width; - } else { - this.height = this.maxHeight; - this.top = this._margins.top; - this.bottom = this.height; - } - } - buildLabels() { - const labelOpts = this.options.labels || {}; - let legendItems = callback(labelOpts.generateLabels, [this.chart], this) || []; - if (labelOpts.filter) { - legendItems = legendItems.filter((item) => labelOpts.filter(item, this.chart.data)); - } - if (labelOpts.sort) { - legendItems = legendItems.sort((a, b) => labelOpts.sort(a, b, this.chart.data)); - } - if (this.options.reverse) { - legendItems.reverse(); - } - this.legendItems = legendItems; - } - fit() { - const {options, ctx} = this; - if (!options.display) { - this.width = this.height = 0; - return; - } - const labelOpts = options.labels; - const labelFont = toFont(labelOpts.font); - const fontSize = labelFont.size; - const titleHeight = this._computeTitleHeight(); - const {boxWidth, itemHeight} = getBoxSize(labelOpts, fontSize); - let width, height; - ctx.font = labelFont.string; - if (this.isHorizontal()) { - width = this.maxWidth; - height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10; - } else { - height = this.maxHeight; - width = this._fitCols(titleHeight, fontSize, boxWidth, itemHeight) + 10; - } - this.width = Math.min(width, options.maxWidth || this.maxWidth); - this.height = Math.min(height, options.maxHeight || this.maxHeight); - } - _fitRows(titleHeight, fontSize, boxWidth, itemHeight) { - const {ctx, maxWidth, options: {labels: {padding}}} = this; - const hitboxes = this.legendHitBoxes = []; - const lineWidths = this.lineWidths = [0]; - const lineHeight = itemHeight + padding; - let totalHeight = titleHeight; - ctx.textAlign = 'left'; - ctx.textBaseline = 'middle'; - let row = -1; - let top = -lineHeight; - this.legendItems.forEach((legendItem, i) => { - const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; - if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) { - totalHeight += lineHeight; - lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0; - top += lineHeight; - row++; - } - hitboxes[i] = {left: 0, top, row, width: itemWidth, height: itemHeight}; - lineWidths[lineWidths.length - 1] += itemWidth + padding; - }); - return totalHeight; - } - _fitCols(titleHeight, fontSize, boxWidth, itemHeight) { - const {ctx, maxHeight, options: {labels: {padding}}} = this; - const hitboxes = this.legendHitBoxes = []; - const columnSizes = this.columnSizes = []; - const heightLimit = maxHeight - titleHeight; - let totalWidth = padding; - let currentColWidth = 0; - let currentColHeight = 0; - let left = 0; - let col = 0; - this.legendItems.forEach((legendItem, i) => { - const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; - if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) { - totalWidth += currentColWidth + padding; - columnSizes.push({width: currentColWidth, height: currentColHeight}); - left += currentColWidth + padding; - col++; - currentColWidth = currentColHeight = 0; - } - hitboxes[i] = {left, top: currentColHeight, col, width: itemWidth, height: itemHeight}; - currentColWidth = Math.max(currentColWidth, itemWidth); - currentColHeight += itemHeight + padding; - }); - totalWidth += currentColWidth; - columnSizes.push({width: currentColWidth, height: currentColHeight}); - return totalWidth; - } - adjustHitBoxes() { - if (!this.options.display) { - return; - } - const titleHeight = this._computeTitleHeight(); - const {legendHitBoxes: hitboxes, options: {align, labels: {padding}, rtl}} = this; - const rtlHelper = getRtlAdapter(rtl, this.left, this.width); - if (this.isHorizontal()) { - let row = 0; - let left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]); - for (const hitbox of hitboxes) { - if (row !== hitbox.row) { - row = hitbox.row; - left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]); - } - hitbox.top += this.top + titleHeight + padding; - hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width); - left += hitbox.width + padding; - } - } else { - let col = 0; - let top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height); - for (const hitbox of hitboxes) { - if (hitbox.col !== col) { - col = hitbox.col; - top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height); - } - hitbox.top = top; - hitbox.left += this.left + padding; - hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width); - top += hitbox.height + padding; - } - } - } - isHorizontal() { - return this.options.position === 'top' || this.options.position === 'bottom'; - } - draw() { - if (this.options.display) { - const ctx = this.ctx; - clipArea(ctx, this); - this._draw(); - unclipArea(ctx); - } - } - _draw() { - const {options: opts, columnSizes, lineWidths, ctx} = this; - const {align, labels: labelOpts} = opts; - const defaultColor = defaults.color; - const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width); - const labelFont = toFont(labelOpts.font); - const {color: fontColor, padding} = labelOpts; - const fontSize = labelFont.size; - const halfFontSize = fontSize / 2; - let cursor; - this.drawTitle(); - ctx.textAlign = rtlHelper.textAlign('left'); - ctx.textBaseline = 'middle'; - ctx.lineWidth = 0.5; - ctx.font = labelFont.string; - const {boxWidth, boxHeight, itemHeight} = getBoxSize(labelOpts, fontSize); - const drawLegendBox = function(x, y, legendItem) { - if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) { - return; - } - ctx.save(); - const lineWidth = valueOrDefault(legendItem.lineWidth, 1); - ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor); - ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt'); - ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0); - ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter'); - ctx.lineWidth = lineWidth; - ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor); - ctx.setLineDash(valueOrDefault(legendItem.lineDash, [])); - if (labelOpts.usePointStyle) { - const drawOptions = { - radius: boxWidth * Math.SQRT2 / 2, - pointStyle: legendItem.pointStyle, - rotation: legendItem.rotation, - borderWidth: lineWidth - }; - const centerX = rtlHelper.xPlus(x, boxWidth / 2); - const centerY = y + halfFontSize; - drawPoint(ctx, drawOptions, centerX, centerY); - } else { - const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0); - const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth); - const borderRadius = toTRBLCorners(legendItem.borderRadius); - ctx.beginPath(); - if (Object.values(borderRadius).some(v => v !== 0)) { - addRoundedRectPath(ctx, { - x: xBoxLeft, - y: yBoxTop, - w: boxWidth, - h: boxHeight, - radius: borderRadius, - }); - } else { - ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight); - } - ctx.fill(); - if (lineWidth !== 0) { - ctx.stroke(); - } - } - ctx.restore(); - }; - const fillText = function(x, y, legendItem) { - renderText(ctx, legendItem.text, x, y + (itemHeight / 2), labelFont, { - strikethrough: legendItem.hidden, - textAlign: rtlHelper.textAlign(legendItem.textAlign) - }); - }; - const isHorizontal = this.isHorizontal(); - const titleHeight = this._computeTitleHeight(); - if (isHorizontal) { - cursor = { - x: _alignStartEnd(align, this.left + padding, this.right - lineWidths[0]), - y: this.top + padding + titleHeight, - line: 0 - }; - } else { - cursor = { - x: this.left + padding, - y: _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height), - line: 0 - }; - } - overrideTextDirection(this.ctx, opts.textDirection); - const lineHeight = itemHeight + padding; - this.legendItems.forEach((legendItem, i) => { - ctx.strokeStyle = legendItem.fontColor || fontColor; - ctx.fillStyle = legendItem.fontColor || fontColor; - const textWidth = ctx.measureText(legendItem.text).width; - const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign)); - const width = boxWidth + halfFontSize + textWidth; - let x = cursor.x; - let y = cursor.y; - rtlHelper.setWidth(this.width); - if (isHorizontal) { - if (i > 0 && x + width + padding > this.right) { - y = cursor.y += lineHeight; - cursor.line++; - x = cursor.x = _alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]); - } - } else if (i > 0 && y + lineHeight > this.bottom) { - x = cursor.x = x + columnSizes[cursor.line].width + padding; - cursor.line++; - y = cursor.y = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height); - } - const realX = rtlHelper.x(x); - drawLegendBox(realX, y, legendItem); - x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl); - fillText(rtlHelper.x(x), y, legendItem); - if (isHorizontal) { - cursor.x += width + padding; - } else { - cursor.y += lineHeight; - } - }); - restoreTextDirection(this.ctx, opts.textDirection); - } - drawTitle() { - const opts = this.options; - const titleOpts = opts.title; - const titleFont = toFont(titleOpts.font); - const titlePadding = toPadding(titleOpts.padding); - if (!titleOpts.display) { - return; - } - const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width); - const ctx = this.ctx; - const position = titleOpts.position; - const halfFontSize = titleFont.size / 2; - const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize; - let y; - let left = this.left; - let maxWidth = this.width; - if (this.isHorizontal()) { - maxWidth = Math.max(...this.lineWidths); - y = this.top + topPaddingPlusHalfFontSize; - left = _alignStartEnd(opts.align, left, this.right - maxWidth); - } else { - const maxHeight = this.columnSizes.reduce((acc, size) => Math.max(acc, size.height), 0); - y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight()); - } - const x = _alignStartEnd(position, left, left + maxWidth); - ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position)); - ctx.textBaseline = 'middle'; - ctx.strokeStyle = titleOpts.color; - ctx.fillStyle = titleOpts.color; - ctx.font = titleFont.string; - renderText(ctx, titleOpts.text, x, y, titleFont); - } - _computeTitleHeight() { - const titleOpts = this.options.title; - const titleFont = toFont(titleOpts.font); - const titlePadding = toPadding(titleOpts.padding); - return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0; - } - _getLegendItemAt(x, y) { - let i, hitBox, lh; - if (_isBetween(x, this.left, this.right) - && _isBetween(y, this.top, this.bottom)) { - lh = this.legendHitBoxes; - for (i = 0; i < lh.length; ++i) { - hitBox = lh[i]; - if (_isBetween(x, hitBox.left, hitBox.left + hitBox.width) - && _isBetween(y, hitBox.top, hitBox.top + hitBox.height)) { - return this.legendItems[i]; - } - } - } - return null; - } - handleEvent(e) { - const opts = this.options; - if (!isListened(e.type, opts)) { - return; - } - const hoveredItem = this._getLegendItemAt(e.x, e.y); - if (e.type === 'mousemove') { - const previous = this._hoveredItem; - const sameItem = itemsEqual(previous, hoveredItem); - if (previous && !sameItem) { - callback(opts.onLeave, [e, previous, this], this); - } - this._hoveredItem = hoveredItem; - if (hoveredItem && !sameItem) { - callback(opts.onHover, [e, hoveredItem, this], this); - } - } else if (hoveredItem) { - callback(opts.onClick, [e, hoveredItem, this], this); - } - } -} -function isListened(type, opts) { - if (type === 'mousemove' && (opts.onHover || opts.onLeave)) { - return true; - } - if (opts.onClick && (type === 'click' || type === 'mouseup')) { - return true; - } - return false; -} -var plugin_legend = { - id: 'legend', - _element: Legend, - start(chart, _args, options) { - const legend = chart.legend = new Legend({ctx: chart.ctx, options, chart}); - layouts.configure(chart, legend, options); - layouts.addBox(chart, legend); - }, - stop(chart) { - layouts.removeBox(chart, chart.legend); - delete chart.legend; - }, - beforeUpdate(chart, _args, options) { - const legend = chart.legend; - layouts.configure(chart, legend, options); - legend.options = options; - }, - afterUpdate(chart) { - const legend = chart.legend; - legend.buildLabels(); - legend.adjustHitBoxes(); - }, - afterEvent(chart, args) { - if (!args.replay) { - chart.legend.handleEvent(args.event); - } - }, - defaults: { - display: true, - position: 'top', - align: 'center', - fullSize: true, - reverse: false, - weight: 1000, - onClick(e, legendItem, legend) { - const index = legendItem.datasetIndex; - const ci = legend.chart; - if (ci.isDatasetVisible(index)) { - ci.hide(index); - legendItem.hidden = true; - } else { - ci.show(index); - legendItem.hidden = false; - } - }, - onHover: null, - onLeave: null, - labels: { - color: (ctx) => ctx.chart.options.color, - boxWidth: 40, - padding: 10, - generateLabels(chart) { - const datasets = chart.data.datasets; - const {labels: {usePointStyle, pointStyle, textAlign, color}} = chart.legend.options; - return chart._getSortedDatasetMetas().map((meta) => { - const style = meta.controller.getStyle(usePointStyle ? 0 : undefined); - const borderWidth = toPadding(style.borderWidth); - return { - text: datasets[meta.index].label, - fillStyle: style.backgroundColor, - fontColor: color, - hidden: !meta.visible, - lineCap: style.borderCapStyle, - lineDash: style.borderDash, - lineDashOffset: style.borderDashOffset, - lineJoin: style.borderJoinStyle, - lineWidth: (borderWidth.width + borderWidth.height) / 4, - strokeStyle: style.borderColor, - pointStyle: pointStyle || style.pointStyle, - rotation: style.rotation, - textAlign: textAlign || style.textAlign, - borderRadius: 0, - datasetIndex: meta.index - }; - }, this); - } - }, - title: { - color: (ctx) => ctx.chart.options.color, - display: false, - position: 'center', - text: '', - } - }, - descriptors: { - _scriptable: (name) => !name.startsWith('on'), - labels: { - _scriptable: (name) => !['generateLabels', 'filter', 'sort'].includes(name), - } - }, -}; - -class Title extends Element { - constructor(config) { - super(); - this.chart = config.chart; - this.options = config.options; - this.ctx = config.ctx; - this._padding = undefined; - this.top = undefined; - this.bottom = undefined; - this.left = undefined; - this.right = undefined; - this.width = undefined; - this.height = undefined; - this.position = undefined; - this.weight = undefined; - this.fullSize = undefined; - } - update(maxWidth, maxHeight) { - const opts = this.options; - this.left = 0; - this.top = 0; - if (!opts.display) { - this.width = this.height = this.right = this.bottom = 0; - return; - } - this.width = this.right = maxWidth; - this.height = this.bottom = maxHeight; - const lineCount = isArray(opts.text) ? opts.text.length : 1; - this._padding = toPadding(opts.padding); - const textSize = lineCount * toFont(opts.font).lineHeight + this._padding.height; - if (this.isHorizontal()) { - this.height = textSize; - } else { - this.width = textSize; - } - } - isHorizontal() { - const pos = this.options.position; - return pos === 'top' || pos === 'bottom'; - } - _drawArgs(offset) { - const {top, left, bottom, right, options} = this; - const align = options.align; - let rotation = 0; - let maxWidth, titleX, titleY; - if (this.isHorizontal()) { - titleX = _alignStartEnd(align, left, right); - titleY = top + offset; - maxWidth = right - left; - } else { - if (options.position === 'left') { - titleX = left + offset; - titleY = _alignStartEnd(align, bottom, top); - rotation = PI * -0.5; - } else { - titleX = right - offset; - titleY = _alignStartEnd(align, top, bottom); - rotation = PI * 0.5; - } - maxWidth = bottom - top; - } - return {titleX, titleY, maxWidth, rotation}; - } - draw() { - const ctx = this.ctx; - const opts = this.options; - if (!opts.display) { - return; - } - const fontOpts = toFont(opts.font); - const lineHeight = fontOpts.lineHeight; - const offset = lineHeight / 2 + this._padding.top; - const {titleX, titleY, maxWidth, rotation} = this._drawArgs(offset); - renderText(ctx, opts.text, 0, 0, fontOpts, { - color: opts.color, - maxWidth, - rotation, - textAlign: _toLeftRightCenter(opts.align), - textBaseline: 'middle', - translation: [titleX, titleY], - }); - } -} -function createTitle(chart, titleOpts) { - const title = new Title({ - ctx: chart.ctx, - options: titleOpts, - chart - }); - layouts.configure(chart, title, titleOpts); - layouts.addBox(chart, title); - chart.titleBlock = title; -} -var plugin_title = { - id: 'title', - _element: Title, - start(chart, _args, options) { - createTitle(chart, options); - }, - stop(chart) { - const titleBlock = chart.titleBlock; - layouts.removeBox(chart, titleBlock); - delete chart.titleBlock; - }, - beforeUpdate(chart, _args, options) { - const title = chart.titleBlock; - layouts.configure(chart, title, options); - title.options = options; - }, - defaults: { - align: 'center', - display: false, - font: { - weight: 'bold', - }, - fullSize: true, - padding: 10, - position: 'top', - text: '', - weight: 2000 - }, - defaultRoutes: { - color: 'color' - }, - descriptors: { - _scriptable: true, - _indexable: false, - }, -}; - -const map = new WeakMap(); -var plugin_subtitle = { - id: 'subtitle', - start(chart, _args, options) { - const title = new Title({ - ctx: chart.ctx, - options, - chart - }); - layouts.configure(chart, title, options); - layouts.addBox(chart, title); - map.set(chart, title); - }, - stop(chart) { - layouts.removeBox(chart, map.get(chart)); - map.delete(chart); - }, - beforeUpdate(chart, _args, options) { - const title = map.get(chart); - layouts.configure(chart, title, options); - title.options = options; - }, - defaults: { - align: 'center', - display: false, - font: { - weight: 'normal', - }, - fullSize: true, - padding: 0, - position: 'top', - text: '', - weight: 1500 - }, - defaultRoutes: { - color: 'color' - }, - descriptors: { - _scriptable: true, - _indexable: false, - }, -}; - -const positioners = { - average(items) { - if (!items.length) { - return false; - } - let i, len; - let x = 0; - let y = 0; - let count = 0; - for (i = 0, len = items.length; i < len; ++i) { - const el = items[i].element; - if (el && el.hasValue()) { - const pos = el.tooltipPosition(); - x += pos.x; - y += pos.y; - ++count; - } - } - return { - x: x / count, - y: y / count - }; - }, - nearest(items, eventPosition) { - if (!items.length) { - return false; - } - let x = eventPosition.x; - let y = eventPosition.y; - let minDistance = Number.POSITIVE_INFINITY; - let i, len, nearestElement; - for (i = 0, len = items.length; i < len; ++i) { - const el = items[i].element; - if (el && el.hasValue()) { - const center = el.getCenterPoint(); - const d = distanceBetweenPoints(eventPosition, center); - if (d < minDistance) { - minDistance = d; - nearestElement = el; - } - } - } - if (nearestElement) { - const tp = nearestElement.tooltipPosition(); - x = tp.x; - y = tp.y; - } - return { - x, - y - }; - } -}; -function pushOrConcat(base, toPush) { - if (toPush) { - if (isArray(toPush)) { - Array.prototype.push.apply(base, toPush); - } else { - base.push(toPush); - } - } - return base; -} -function splitNewlines(str) { - if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) { - return str.split('\n'); - } - return str; -} -function createTooltipItem(chart, item) { - const {element, datasetIndex, index} = item; - const controller = chart.getDatasetMeta(datasetIndex).controller; - const {label, value} = controller.getLabelAndValue(index); - return { - chart, - label, - parsed: controller.getParsed(index), - raw: chart.data.datasets[datasetIndex].data[index], - formattedValue: value, - dataset: controller.getDataset(), - dataIndex: index, - datasetIndex, - element - }; -} -function getTooltipSize(tooltip, options) { - const ctx = tooltip.chart.ctx; - const {body, footer, title} = tooltip; - const {boxWidth, boxHeight} = options; - const bodyFont = toFont(options.bodyFont); - const titleFont = toFont(options.titleFont); - const footerFont = toFont(options.footerFont); - const titleLineCount = title.length; - const footerLineCount = footer.length; - const bodyLineItemCount = body.length; - const padding = toPadding(options.padding); - let height = padding.height; - let width = 0; - let combinedBodyLength = body.reduce((count, bodyItem) => count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0); - combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length; - if (titleLineCount) { - height += titleLineCount * titleFont.lineHeight - + (titleLineCount - 1) * options.titleSpacing - + options.titleMarginBottom; - } - if (combinedBodyLength) { - const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight; - height += bodyLineItemCount * bodyLineHeight - + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight - + (combinedBodyLength - 1) * options.bodySpacing; - } - if (footerLineCount) { - height += options.footerMarginTop - + footerLineCount * footerFont.lineHeight - + (footerLineCount - 1) * options.footerSpacing; - } - let widthPadding = 0; - const maxLineWidth = function(line) { - width = Math.max(width, ctx.measureText(line).width + widthPadding); - }; - ctx.save(); - ctx.font = titleFont.string; - each(tooltip.title, maxLineWidth); - ctx.font = bodyFont.string; - each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth); - widthPadding = options.displayColors ? (boxWidth + 2 + options.boxPadding) : 0; - each(body, (bodyItem) => { - each(bodyItem.before, maxLineWidth); - each(bodyItem.lines, maxLineWidth); - each(bodyItem.after, maxLineWidth); - }); - widthPadding = 0; - ctx.font = footerFont.string; - each(tooltip.footer, maxLineWidth); - ctx.restore(); - width += padding.width; - return {width, height}; -} -function determineYAlign(chart, size) { - const {y, height} = size; - if (y < height / 2) { - return 'top'; - } else if (y > (chart.height - height / 2)) { - return 'bottom'; - } - return 'center'; -} -function doesNotFitWithAlign(xAlign, chart, options, size) { - const {x, width} = size; - const caret = options.caretSize + options.caretPadding; - if (xAlign === 'left' && x + width + caret > chart.width) { - return true; - } - if (xAlign === 'right' && x - width - caret < 0) { - return true; - } -} -function determineXAlign(chart, options, size, yAlign) { - const {x, width} = size; - const {width: chartWidth, chartArea: {left, right}} = chart; - let xAlign = 'center'; - if (yAlign === 'center') { - xAlign = x <= (left + right) / 2 ? 'left' : 'right'; - } else if (x <= width / 2) { - xAlign = 'left'; - } else if (x >= chartWidth - width / 2) { - xAlign = 'right'; - } - if (doesNotFitWithAlign(xAlign, chart, options, size)) { - xAlign = 'center'; - } - return xAlign; -} -function determineAlignment(chart, options, size) { - const yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size); - return { - xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign), - yAlign - }; -} -function alignX(size, xAlign) { - let {x, width} = size; - if (xAlign === 'right') { - x -= width; - } else if (xAlign === 'center') { - x -= (width / 2); - } - return x; -} -function alignY(size, yAlign, paddingAndSize) { - let {y, height} = size; - if (yAlign === 'top') { - y += paddingAndSize; - } else if (yAlign === 'bottom') { - y -= height + paddingAndSize; - } else { - y -= (height / 2); - } - return y; -} -function getBackgroundPoint(options, size, alignment, chart) { - const {caretSize, caretPadding, cornerRadius} = options; - const {xAlign, yAlign} = alignment; - const paddingAndSize = caretSize + caretPadding; - const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(cornerRadius); - let x = alignX(size, xAlign); - const y = alignY(size, yAlign, paddingAndSize); - if (yAlign === 'center') { - if (xAlign === 'left') { - x += paddingAndSize; - } else if (xAlign === 'right') { - x -= paddingAndSize; - } - } else if (xAlign === 'left') { - x -= Math.max(topLeft, bottomLeft) + caretSize; - } else if (xAlign === 'right') { - x += Math.max(topRight, bottomRight) + caretSize; - } - return { - x: _limitValue(x, 0, chart.width - size.width), - y: _limitValue(y, 0, chart.height - size.height) - }; -} -function getAlignedX(tooltip, align, options) { - const padding = toPadding(options.padding); - return align === 'center' - ? tooltip.x + tooltip.width / 2 - : align === 'right' - ? tooltip.x + tooltip.width - padding.right - : tooltip.x + padding.left; -} -function getBeforeAfterBodyLines(callback) { - return pushOrConcat([], splitNewlines(callback)); -} -function createTooltipContext(parent, tooltip, tooltipItems) { - return createContext(parent, { - tooltip, - tooltipItems, - type: 'tooltip' - }); -} -function overrideCallbacks(callbacks, context) { - const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks; - return override ? callbacks.override(override) : callbacks; -} -class Tooltip extends Element { - constructor(config) { - super(); - this.opacity = 0; - this._active = []; - this._eventPosition = undefined; - this._size = undefined; - this._cachedAnimations = undefined; - this._tooltipItems = []; - this.$animations = undefined; - this.$context = undefined; - this.chart = config.chart || config._chart; - this._chart = this.chart; - this.options = config.options; - this.dataPoints = undefined; - this.title = undefined; - this.beforeBody = undefined; - this.body = undefined; - this.afterBody = undefined; - this.footer = undefined; - this.xAlign = undefined; - this.yAlign = undefined; - this.x = undefined; - this.y = undefined; - this.height = undefined; - this.width = undefined; - this.caretX = undefined; - this.caretY = undefined; - this.labelColors = undefined; - this.labelPointStyles = undefined; - this.labelTextColors = undefined; - } - initialize(options) { - this.options = options; - this._cachedAnimations = undefined; - this.$context = undefined; - } - _resolveAnimations() { - const cached = this._cachedAnimations; - if (cached) { - return cached; - } - const chart = this.chart; - const options = this.options.setContext(this.getContext()); - const opts = options.enabled && chart.options.animation && options.animations; - const animations = new Animations(this.chart, opts); - if (opts._cacheable) { - this._cachedAnimations = Object.freeze(animations); - } - return animations; - } - getContext() { - return this.$context || - (this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems)); - } - getTitle(context, options) { - const {callbacks} = options; - const beforeTitle = callbacks.beforeTitle.apply(this, [context]); - const title = callbacks.title.apply(this, [context]); - const afterTitle = callbacks.afterTitle.apply(this, [context]); - let lines = []; - lines = pushOrConcat(lines, splitNewlines(beforeTitle)); - lines = pushOrConcat(lines, splitNewlines(title)); - lines = pushOrConcat(lines, splitNewlines(afterTitle)); - return lines; - } - getBeforeBody(tooltipItems, options) { - return getBeforeAfterBodyLines(options.callbacks.beforeBody.apply(this, [tooltipItems])); - } - getBody(tooltipItems, options) { - const {callbacks} = options; - const bodyItems = []; - each(tooltipItems, (context) => { - const bodyItem = { - before: [], - lines: [], - after: [] - }; - const scoped = overrideCallbacks(callbacks, context); - pushOrConcat(bodyItem.before, splitNewlines(scoped.beforeLabel.call(this, context))); - pushOrConcat(bodyItem.lines, scoped.label.call(this, context)); - pushOrConcat(bodyItem.after, splitNewlines(scoped.afterLabel.call(this, context))); - bodyItems.push(bodyItem); - }); - return bodyItems; - } - getAfterBody(tooltipItems, options) { - return getBeforeAfterBodyLines(options.callbacks.afterBody.apply(this, [tooltipItems])); - } - getFooter(tooltipItems, options) { - const {callbacks} = options; - const beforeFooter = callbacks.beforeFooter.apply(this, [tooltipItems]); - const footer = callbacks.footer.apply(this, [tooltipItems]); - const afterFooter = callbacks.afterFooter.apply(this, [tooltipItems]); - let lines = []; - lines = pushOrConcat(lines, splitNewlines(beforeFooter)); - lines = pushOrConcat(lines, splitNewlines(footer)); - lines = pushOrConcat(lines, splitNewlines(afterFooter)); - return lines; - } - _createItems(options) { - const active = this._active; - const data = this.chart.data; - const labelColors = []; - const labelPointStyles = []; - const labelTextColors = []; - let tooltipItems = []; - let i, len; - for (i = 0, len = active.length; i < len; ++i) { - tooltipItems.push(createTooltipItem(this.chart, active[i])); - } - if (options.filter) { - tooltipItems = tooltipItems.filter((element, index, array) => options.filter(element, index, array, data)); - } - if (options.itemSort) { - tooltipItems = tooltipItems.sort((a, b) => options.itemSort(a, b, data)); - } - each(tooltipItems, (context) => { - const scoped = overrideCallbacks(options.callbacks, context); - labelColors.push(scoped.labelColor.call(this, context)); - labelPointStyles.push(scoped.labelPointStyle.call(this, context)); - labelTextColors.push(scoped.labelTextColor.call(this, context)); - }); - this.labelColors = labelColors; - this.labelPointStyles = labelPointStyles; - this.labelTextColors = labelTextColors; - this.dataPoints = tooltipItems; - return tooltipItems; - } - update(changed, replay) { - const options = this.options.setContext(this.getContext()); - const active = this._active; - let properties; - let tooltipItems = []; - if (!active.length) { - if (this.opacity !== 0) { - properties = { - opacity: 0 - }; - } - } else { - const position = positioners[options.position].call(this, active, this._eventPosition); - tooltipItems = this._createItems(options); - this.title = this.getTitle(tooltipItems, options); - this.beforeBody = this.getBeforeBody(tooltipItems, options); - this.body = this.getBody(tooltipItems, options); - this.afterBody = this.getAfterBody(tooltipItems, options); - this.footer = this.getFooter(tooltipItems, options); - const size = this._size = getTooltipSize(this, options); - const positionAndSize = Object.assign({}, position, size); - const alignment = determineAlignment(this.chart, options, positionAndSize); - const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart); - this.xAlign = alignment.xAlign; - this.yAlign = alignment.yAlign; - properties = { - opacity: 1, - x: backgroundPoint.x, - y: backgroundPoint.y, - width: size.width, - height: size.height, - caretX: position.x, - caretY: position.y - }; - } - this._tooltipItems = tooltipItems; - this.$context = undefined; - if (properties) { - this._resolveAnimations().update(this, properties); - } - if (changed && options.external) { - options.external.call(this, {chart: this.chart, tooltip: this, replay}); - } - } - drawCaret(tooltipPoint, ctx, size, options) { - const caretPosition = this.getCaretPosition(tooltipPoint, size, options); - ctx.lineTo(caretPosition.x1, caretPosition.y1); - ctx.lineTo(caretPosition.x2, caretPosition.y2); - ctx.lineTo(caretPosition.x3, caretPosition.y3); - } - getCaretPosition(tooltipPoint, size, options) { - const {xAlign, yAlign} = this; - const {caretSize, cornerRadius} = options; - const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(cornerRadius); - const {x: ptX, y: ptY} = tooltipPoint; - const {width, height} = size; - let x1, x2, x3, y1, y2, y3; - if (yAlign === 'center') { - y2 = ptY + (height / 2); - if (xAlign === 'left') { - x1 = ptX; - x2 = x1 - caretSize; - y1 = y2 + caretSize; - y3 = y2 - caretSize; - } else { - x1 = ptX + width; - x2 = x1 + caretSize; - y1 = y2 - caretSize; - y3 = y2 + caretSize; - } - x3 = x1; - } else { - if (xAlign === 'left') { - x2 = ptX + Math.max(topLeft, bottomLeft) + (caretSize); - } else if (xAlign === 'right') { - x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize; - } else { - x2 = this.caretX; - } - if (yAlign === 'top') { - y1 = ptY; - y2 = y1 - caretSize; - x1 = x2 - caretSize; - x3 = x2 + caretSize; - } else { - y1 = ptY + height; - y2 = y1 + caretSize; - x1 = x2 + caretSize; - x3 = x2 - caretSize; - } - y3 = y1; - } - return {x1, x2, x3, y1, y2, y3}; - } - drawTitle(pt, ctx, options) { - const title = this.title; - const length = title.length; - let titleFont, titleSpacing, i; - if (length) { - const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width); - pt.x = getAlignedX(this, options.titleAlign, options); - ctx.textAlign = rtlHelper.textAlign(options.titleAlign); - ctx.textBaseline = 'middle'; - titleFont = toFont(options.titleFont); - titleSpacing = options.titleSpacing; - ctx.fillStyle = options.titleColor; - ctx.font = titleFont.string; - for (i = 0; i < length; ++i) { - ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2); - pt.y += titleFont.lineHeight + titleSpacing; - if (i + 1 === length) { - pt.y += options.titleMarginBottom - titleSpacing; - } - } - } - } - _drawColorBox(ctx, pt, i, rtlHelper, options) { - const labelColors = this.labelColors[i]; - const labelPointStyle = this.labelPointStyles[i]; - const {boxHeight, boxWidth, boxPadding} = options; - const bodyFont = toFont(options.bodyFont); - const colorX = getAlignedX(this, 'left', options); - const rtlColorX = rtlHelper.x(colorX); - const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0; - const colorY = pt.y + yOffSet; - if (options.usePointStyle) { - const drawOptions = { - radius: Math.min(boxWidth, boxHeight) / 2, - pointStyle: labelPointStyle.pointStyle, - rotation: labelPointStyle.rotation, - borderWidth: 1 - }; - const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2; - const centerY = colorY + boxHeight / 2; - ctx.strokeStyle = options.multiKeyBackground; - ctx.fillStyle = options.multiKeyBackground; - drawPoint(ctx, drawOptions, centerX, centerY); - ctx.strokeStyle = labelColors.borderColor; - ctx.fillStyle = labelColors.backgroundColor; - drawPoint(ctx, drawOptions, centerX, centerY); - } else { - ctx.lineWidth = labelColors.borderWidth || 1; - ctx.strokeStyle = labelColors.borderColor; - ctx.setLineDash(labelColors.borderDash || []); - ctx.lineDashOffset = labelColors.borderDashOffset || 0; - const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth - boxPadding); - const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - boxPadding - 2); - const borderRadius = toTRBLCorners(labelColors.borderRadius); - if (Object.values(borderRadius).some(v => v !== 0)) { - ctx.beginPath(); - ctx.fillStyle = options.multiKeyBackground; - addRoundedRectPath(ctx, { - x: outerX, - y: colorY, - w: boxWidth, - h: boxHeight, - radius: borderRadius, - }); - ctx.fill(); - ctx.stroke(); - ctx.fillStyle = labelColors.backgroundColor; - ctx.beginPath(); - addRoundedRectPath(ctx, { - x: innerX, - y: colorY + 1, - w: boxWidth - 2, - h: boxHeight - 2, - radius: borderRadius, - }); - ctx.fill(); - } else { - ctx.fillStyle = options.multiKeyBackground; - ctx.fillRect(outerX, colorY, boxWidth, boxHeight); - ctx.strokeRect(outerX, colorY, boxWidth, boxHeight); - ctx.fillStyle = labelColors.backgroundColor; - ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2); - } - } - ctx.fillStyle = this.labelTextColors[i]; - } - drawBody(pt, ctx, options) { - const {body} = this; - const {bodySpacing, bodyAlign, displayColors, boxHeight, boxWidth, boxPadding} = options; - const bodyFont = toFont(options.bodyFont); - let bodyLineHeight = bodyFont.lineHeight; - let xLinePadding = 0; - const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width); - const fillLineOfText = function(line) { - ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2); - pt.y += bodyLineHeight + bodySpacing; - }; - const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign); - let bodyItem, textColor, lines, i, j, ilen, jlen; - ctx.textAlign = bodyAlign; - ctx.textBaseline = 'middle'; - ctx.font = bodyFont.string; - pt.x = getAlignedX(this, bodyAlignForCalculation, options); - ctx.fillStyle = options.bodyColor; - each(this.beforeBody, fillLineOfText); - xLinePadding = displayColors && bodyAlignForCalculation !== 'right' - ? bodyAlign === 'center' ? (boxWidth / 2 + boxPadding) : (boxWidth + 2 + boxPadding) - : 0; - for (i = 0, ilen = body.length; i < ilen; ++i) { - bodyItem = body[i]; - textColor = this.labelTextColors[i]; - ctx.fillStyle = textColor; - each(bodyItem.before, fillLineOfText); - lines = bodyItem.lines; - if (displayColors && lines.length) { - this._drawColorBox(ctx, pt, i, rtlHelper, options); - bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight); - } - for (j = 0, jlen = lines.length; j < jlen; ++j) { - fillLineOfText(lines[j]); - bodyLineHeight = bodyFont.lineHeight; - } - each(bodyItem.after, fillLineOfText); - } - xLinePadding = 0; - bodyLineHeight = bodyFont.lineHeight; - each(this.afterBody, fillLineOfText); - pt.y -= bodySpacing; - } - drawFooter(pt, ctx, options) { - const footer = this.footer; - const length = footer.length; - let footerFont, i; - if (length) { - const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width); - pt.x = getAlignedX(this, options.footerAlign, options); - pt.y += options.footerMarginTop; - ctx.textAlign = rtlHelper.textAlign(options.footerAlign); - ctx.textBaseline = 'middle'; - footerFont = toFont(options.footerFont); - ctx.fillStyle = options.footerColor; - ctx.font = footerFont.string; - for (i = 0; i < length; ++i) { - ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2); - pt.y += footerFont.lineHeight + options.footerSpacing; - } - } - } - drawBackground(pt, ctx, tooltipSize, options) { - const {xAlign, yAlign} = this; - const {x, y} = pt; - const {width, height} = tooltipSize; - const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(options.cornerRadius); - ctx.fillStyle = options.backgroundColor; - ctx.strokeStyle = options.borderColor; - ctx.lineWidth = options.borderWidth; - ctx.beginPath(); - ctx.moveTo(x + topLeft, y); - if (yAlign === 'top') { - this.drawCaret(pt, ctx, tooltipSize, options); - } - ctx.lineTo(x + width - topRight, y); - ctx.quadraticCurveTo(x + width, y, x + width, y + topRight); - if (yAlign === 'center' && xAlign === 'right') { - this.drawCaret(pt, ctx, tooltipSize, options); - } - ctx.lineTo(x + width, y + height - bottomRight); - ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height); - if (yAlign === 'bottom') { - this.drawCaret(pt, ctx, tooltipSize, options); - } - ctx.lineTo(x + bottomLeft, y + height); - ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft); - if (yAlign === 'center' && xAlign === 'left') { - this.drawCaret(pt, ctx, tooltipSize, options); - } - ctx.lineTo(x, y + topLeft); - ctx.quadraticCurveTo(x, y, x + topLeft, y); - ctx.closePath(); - ctx.fill(); - if (options.borderWidth > 0) { - ctx.stroke(); - } - } - _updateAnimationTarget(options) { - const chart = this.chart; - const anims = this.$animations; - const animX = anims && anims.x; - const animY = anims && anims.y; - if (animX || animY) { - const position = positioners[options.position].call(this, this._active, this._eventPosition); - if (!position) { - return; - } - const size = this._size = getTooltipSize(this, options); - const positionAndSize = Object.assign({}, position, this._size); - const alignment = determineAlignment(chart, options, positionAndSize); - const point = getBackgroundPoint(options, positionAndSize, alignment, chart); - if (animX._to !== point.x || animY._to !== point.y) { - this.xAlign = alignment.xAlign; - this.yAlign = alignment.yAlign; - this.width = size.width; - this.height = size.height; - this.caretX = position.x; - this.caretY = position.y; - this._resolveAnimations().update(this, point); - } - } - } - draw(ctx) { - const options = this.options.setContext(this.getContext()); - let opacity = this.opacity; - if (!opacity) { - return; - } - this._updateAnimationTarget(options); - const tooltipSize = { - width: this.width, - height: this.height - }; - const pt = { - x: this.x, - y: this.y - }; - opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity; - const padding = toPadding(options.padding); - const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length; - if (options.enabled && hasTooltipContent) { - ctx.save(); - ctx.globalAlpha = opacity; - this.drawBackground(pt, ctx, tooltipSize, options); - overrideTextDirection(ctx, options.textDirection); - pt.y += padding.top; - this.drawTitle(pt, ctx, options); - this.drawBody(pt, ctx, options); - this.drawFooter(pt, ctx, options); - restoreTextDirection(ctx, options.textDirection); - ctx.restore(); - } - } - getActiveElements() { - return this._active || []; - } - setActiveElements(activeElements, eventPosition) { - const lastActive = this._active; - const active = activeElements.map(({datasetIndex, index}) => { - const meta = this.chart.getDatasetMeta(datasetIndex); - if (!meta) { - throw new Error('Cannot find a dataset at index ' + datasetIndex); - } - return { - datasetIndex, - element: meta.data[index], - index, - }; - }); - const changed = !_elementsEqual(lastActive, active); - const positionChanged = this._positionChanged(active, eventPosition); - if (changed || positionChanged) { - this._active = active; - this._eventPosition = eventPosition; - this._ignoreReplayEvents = true; - this.update(true); - } - } - handleEvent(e, replay, inChartArea = true) { - if (replay && this._ignoreReplayEvents) { - return false; - } - this._ignoreReplayEvents = false; - const options = this.options; - const lastActive = this._active || []; - const active = this._getActiveElements(e, lastActive, replay, inChartArea); - const positionChanged = this._positionChanged(active, e); - const changed = replay || !_elementsEqual(active, lastActive) || positionChanged; - if (changed) { - this._active = active; - if (options.enabled || options.external) { - this._eventPosition = { - x: e.x, - y: e.y - }; - this.update(true, replay); - } - } - return changed; - } - _getActiveElements(e, lastActive, replay, inChartArea) { - const options = this.options; - if (e.type === 'mouseout') { - return []; - } - if (!inChartArea) { - return lastActive; - } - const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay); - if (options.reverse) { - active.reverse(); - } - return active; - } - _positionChanged(active, e) { - const {caretX, caretY, options} = this; - const position = positioners[options.position].call(this, active, e); - return position !== false && (caretX !== position.x || caretY !== position.y); - } -} -Tooltip.positioners = positioners; -var plugin_tooltip = { - id: 'tooltip', - _element: Tooltip, - positioners, - afterInit(chart, _args, options) { - if (options) { - chart.tooltip = new Tooltip({chart, options}); - } - }, - beforeUpdate(chart, _args, options) { - if (chart.tooltip) { - chart.tooltip.initialize(options); - } - }, - reset(chart, _args, options) { - if (chart.tooltip) { - chart.tooltip.initialize(options); - } - }, - afterDraw(chart) { - const tooltip = chart.tooltip; - const args = { - tooltip - }; - if (chart.notifyPlugins('beforeTooltipDraw', args) === false) { - return; - } - if (tooltip) { - tooltip.draw(chart.ctx); - } - chart.notifyPlugins('afterTooltipDraw', args); - }, - afterEvent(chart, args) { - if (chart.tooltip) { - const useFinalPosition = args.replay; - if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) { - args.changed = true; - } - } - }, - defaults: { - enabled: true, - external: null, - position: 'average', - backgroundColor: 'rgba(0,0,0,0.8)', - titleColor: '#fff', - titleFont: { - weight: 'bold', - }, - titleSpacing: 2, - titleMarginBottom: 6, - titleAlign: 'left', - bodyColor: '#fff', - bodySpacing: 2, - bodyFont: { - }, - bodyAlign: 'left', - footerColor: '#fff', - footerSpacing: 2, - footerMarginTop: 6, - footerFont: { - weight: 'bold', - }, - footerAlign: 'left', - padding: 6, - caretPadding: 2, - caretSize: 5, - cornerRadius: 6, - boxHeight: (ctx, opts) => opts.bodyFont.size, - boxWidth: (ctx, opts) => opts.bodyFont.size, - multiKeyBackground: '#fff', - displayColors: true, - boxPadding: 0, - borderColor: 'rgba(0,0,0,0)', - borderWidth: 0, - animation: { - duration: 400, - easing: 'easeOutQuart', - }, - animations: { - numbers: { - type: 'number', - properties: ['x', 'y', 'width', 'height', 'caretX', 'caretY'], - }, - opacity: { - easing: 'linear', - duration: 200 - } - }, - callbacks: { - beforeTitle: noop, - title(tooltipItems) { - if (tooltipItems.length > 0) { - const item = tooltipItems[0]; - const labels = item.chart.data.labels; - const labelCount = labels ? labels.length : 0; - if (this && this.options && this.options.mode === 'dataset') { - return item.dataset.label || ''; - } else if (item.label) { - return item.label; - } else if (labelCount > 0 && item.dataIndex < labelCount) { - return labels[item.dataIndex]; - } - } - return ''; - }, - afterTitle: noop, - beforeBody: noop, - beforeLabel: noop, - label(tooltipItem) { - if (this && this.options && this.options.mode === 'dataset') { - return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue; - } - let label = tooltipItem.dataset.label || ''; - if (label) { - label += ': '; - } - const value = tooltipItem.formattedValue; - if (!isNullOrUndef(value)) { - label += value; - } - return label; - }, - labelColor(tooltipItem) { - const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex); - const options = meta.controller.getStyle(tooltipItem.dataIndex); - return { - borderColor: options.borderColor, - backgroundColor: options.backgroundColor, - borderWidth: options.borderWidth, - borderDash: options.borderDash, - borderDashOffset: options.borderDashOffset, - borderRadius: 0, - }; - }, - labelTextColor() { - return this.options.bodyColor; - }, - labelPointStyle(tooltipItem) { - const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex); - const options = meta.controller.getStyle(tooltipItem.dataIndex); - return { - pointStyle: options.pointStyle, - rotation: options.rotation, - }; - }, - afterLabel: noop, - afterBody: noop, - beforeFooter: noop, - footer: noop, - afterFooter: noop - } - }, - defaultRoutes: { - bodyFont: 'font', - footerFont: 'font', - titleFont: 'font' - }, - descriptors: { - _scriptable: (name) => name !== 'filter' && name !== 'itemSort' && name !== 'external', - _indexable: false, - callbacks: { - _scriptable: false, - _indexable: false, - }, - animation: { - _fallback: false - }, - animations: { - _fallback: 'animation' - } - }, - additionalOptionScopes: ['interaction'] -}; - -var plugins = /*#__PURE__*/Object.freeze({ -__proto__: null, -Decimation: plugin_decimation, -Filler: plugin_filler, -Legend: plugin_legend, -SubTitle: plugin_subtitle, -Title: plugin_title, -Tooltip: plugin_tooltip -}); - -const addIfString = (labels, raw, index, addedLabels) => { - if (typeof raw === 'string') { - index = labels.push(raw) - 1; - addedLabels.unshift({index, label: raw}); - } else if (isNaN(raw)) { - index = null; - } - return index; -}; -function findOrAddLabel(labels, raw, index, addedLabels) { - const first = labels.indexOf(raw); - if (first === -1) { - return addIfString(labels, raw, index, addedLabels); - } - const last = labels.lastIndexOf(raw); - return first !== last ? index : first; -} -const validIndex = (index, max) => index === null ? null : _limitValue(Math.round(index), 0, max); -class CategoryScale extends Scale { - constructor(cfg) { - super(cfg); - this._startValue = undefined; - this._valueRange = 0; - this._addedLabels = []; - } - init(scaleOptions) { - const added = this._addedLabels; - if (added.length) { - const labels = this.getLabels(); - for (const {index, label} of added) { - if (labels[index] === label) { - labels.splice(index, 1); - } - } - this._addedLabels = []; - } - super.init(scaleOptions); - } - parse(raw, index) { - if (isNullOrUndef(raw)) { - return null; - } - const labels = this.getLabels(); - index = isFinite(index) && labels[index] === raw ? index - : findOrAddLabel(labels, raw, valueOrDefault(index, raw), this._addedLabels); - return validIndex(index, labels.length - 1); - } - determineDataLimits() { - const {minDefined, maxDefined} = this.getUserBounds(); - let {min, max} = this.getMinMax(true); - if (this.options.bounds === 'ticks') { - if (!minDefined) { - min = 0; - } - if (!maxDefined) { - max = this.getLabels().length - 1; - } - } - this.min = min; - this.max = max; - } - buildTicks() { - const min = this.min; - const max = this.max; - const offset = this.options.offset; - const ticks = []; - let labels = this.getLabels(); - labels = (min === 0 && max === labels.length - 1) ? labels : labels.slice(min, max + 1); - this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1); - this._startValue = this.min - (offset ? 0.5 : 0); - for (let value = min; value <= max; value++) { - ticks.push({value}); - } - return ticks; - } - getLabelForValue(value) { - const labels = this.getLabels(); - if (value >= 0 && value < labels.length) { - return labels[value]; - } - return value; - } - configure() { - super.configure(); - if (!this.isHorizontal()) { - this._reversePixels = !this._reversePixels; - } - } - getPixelForValue(value) { - if (typeof value !== 'number') { - value = this.parse(value); - } - return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange); - } - getPixelForTick(index) { - const ticks = this.ticks; - if (index < 0 || index > ticks.length - 1) { - return null; - } - return this.getPixelForValue(ticks[index].value); - } - getValueForPixel(pixel) { - return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange); - } - getBasePixel() { - return this.bottom; - } -} -CategoryScale.id = 'category'; -CategoryScale.defaults = { - ticks: { - callback: CategoryScale.prototype.getLabelForValue - } -}; - -function generateTicks$1(generationOptions, dataRange) { - const ticks = []; - const MIN_SPACING = 1e-14; - const {bounds, step, min, max, precision, count, maxTicks, maxDigits, includeBounds} = generationOptions; - const unit = step || 1; - const maxSpaces = maxTicks - 1; - const {min: rmin, max: rmax} = dataRange; - const minDefined = !isNullOrUndef(min); - const maxDefined = !isNullOrUndef(max); - const countDefined = !isNullOrUndef(count); - const minSpacing = (rmax - rmin) / (maxDigits + 1); - let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit; - let factor, niceMin, niceMax, numSpaces; - if (spacing < MIN_SPACING && !minDefined && !maxDefined) { - return [{value: rmin}, {value: rmax}]; - } - numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing); - if (numSpaces > maxSpaces) { - spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit; - } - if (!isNullOrUndef(precision)) { - factor = Math.pow(10, precision); - spacing = Math.ceil(spacing * factor) / factor; - } - if (bounds === 'ticks') { - niceMin = Math.floor(rmin / spacing) * spacing; - niceMax = Math.ceil(rmax / spacing) * spacing; - } else { - niceMin = rmin; - niceMax = rmax; - } - if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) { - numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks)); - spacing = (max - min) / numSpaces; - niceMin = min; - niceMax = max; - } else if (countDefined) { - niceMin = minDefined ? min : niceMin; - niceMax = maxDefined ? max : niceMax; - numSpaces = count - 1; - spacing = (niceMax - niceMin) / numSpaces; - } else { - numSpaces = (niceMax - niceMin) / spacing; - if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { - numSpaces = Math.round(numSpaces); - } else { - numSpaces = Math.ceil(numSpaces); - } - } - const decimalPlaces = Math.max( - _decimalPlaces(spacing), - _decimalPlaces(niceMin) - ); - factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision); - niceMin = Math.round(niceMin * factor) / factor; - niceMax = Math.round(niceMax * factor) / factor; - let j = 0; - if (minDefined) { - if (includeBounds && niceMin !== min) { - ticks.push({value: min}); - if (niceMin < min) { - j++; - } - if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) { - j++; - } - } else if (niceMin < min) { - j++; - } - } - for (; j < numSpaces; ++j) { - ticks.push({value: Math.round((niceMin + j * spacing) * factor) / factor}); - } - if (maxDefined && includeBounds && niceMax !== max) { - if (ticks.length && almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) { - ticks[ticks.length - 1].value = max; - } else { - ticks.push({value: max}); - } - } else if (!maxDefined || niceMax === max) { - ticks.push({value: niceMax}); - } - return ticks; -} -function relativeLabelSize(value, minSpacing, {horizontal, minRotation}) { - const rad = toRadians(minRotation); - const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001; - const length = 0.75 * minSpacing * ('' + value).length; - return Math.min(minSpacing / ratio, length); -} -class LinearScaleBase extends Scale { - constructor(cfg) { - super(cfg); - this.start = undefined; - this.end = undefined; - this._startValue = undefined; - this._endValue = undefined; - this._valueRange = 0; - } - parse(raw, index) { - if (isNullOrUndef(raw)) { - return null; - } - if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) { - return null; - } - return +raw; - } - handleTickRangeOptions() { - const {beginAtZero} = this.options; - const {minDefined, maxDefined} = this.getUserBounds(); - let {min, max} = this; - const setMin = v => (min = minDefined ? min : v); - const setMax = v => (max = maxDefined ? max : v); - if (beginAtZero) { - const minSign = sign(min); - const maxSign = sign(max); - if (minSign < 0 && maxSign < 0) { - setMax(0); - } else if (minSign > 0 && maxSign > 0) { - setMin(0); - } - } - if (min === max) { - let offset = 1; - if (max >= Number.MAX_SAFE_INTEGER || min <= Number.MIN_SAFE_INTEGER) { - offset = Math.abs(max * 0.05); - } - setMax(max + offset); - if (!beginAtZero) { - setMin(min - offset); - } - } - this.min = min; - this.max = max; - } - getTickLimit() { - const tickOpts = this.options.ticks; - let {maxTicksLimit, stepSize} = tickOpts; - let maxTicks; - if (stepSize) { - maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1; - if (maxTicks > 1000) { - console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`); - maxTicks = 1000; - } - } else { - maxTicks = this.computeTickLimit(); - maxTicksLimit = maxTicksLimit || 11; - } - if (maxTicksLimit) { - maxTicks = Math.min(maxTicksLimit, maxTicks); - } - return maxTicks; - } - computeTickLimit() { - return Number.POSITIVE_INFINITY; - } - buildTicks() { - const opts = this.options; - const tickOpts = opts.ticks; - let maxTicks = this.getTickLimit(); - maxTicks = Math.max(2, maxTicks); - const numericGeneratorOptions = { - maxTicks, - bounds: opts.bounds, - min: opts.min, - max: opts.max, - precision: tickOpts.precision, - step: tickOpts.stepSize, - count: tickOpts.count, - maxDigits: this._maxDigits(), - horizontal: this.isHorizontal(), - minRotation: tickOpts.minRotation || 0, - includeBounds: tickOpts.includeBounds !== false - }; - const dataRange = this._range || this; - const ticks = generateTicks$1(numericGeneratorOptions, dataRange); - if (opts.bounds === 'ticks') { - _setMinAndMaxByKey(ticks, this, 'value'); - } - if (opts.reverse) { - ticks.reverse(); - this.start = this.max; - this.end = this.min; - } else { - this.start = this.min; - this.end = this.max; - } - return ticks; - } - configure() { - const ticks = this.ticks; - let start = this.min; - let end = this.max; - super.configure(); - if (this.options.offset && ticks.length) { - const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2; - start -= offset; - end += offset; - } - this._startValue = start; - this._endValue = end; - this._valueRange = end - start; - } - getLabelForValue(value) { - return formatNumber(value, this.chart.options.locale, this.options.ticks.format); - } -} - -class LinearScale extends LinearScaleBase { - determineDataLimits() { - const {min, max} = this.getMinMax(true); - this.min = isNumberFinite(min) ? min : 0; - this.max = isNumberFinite(max) ? max : 1; - this.handleTickRangeOptions(); - } - computeTickLimit() { - const horizontal = this.isHorizontal(); - const length = horizontal ? this.width : this.height; - const minRotation = toRadians(this.options.ticks.minRotation); - const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001; - const tickFont = this._resolveTickFontOptions(0); - return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio)); - } - getPixelForValue(value) { - return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange); - } - getValueForPixel(pixel) { - return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange; - } -} -LinearScale.id = 'linear'; -LinearScale.defaults = { - ticks: { - callback: Ticks.formatters.numeric - } -}; - -function isMajor(tickVal) { - const remain = tickVal / (Math.pow(10, Math.floor(log10(tickVal)))); - return remain === 1; -} -function generateTicks(generationOptions, dataRange) { - const endExp = Math.floor(log10(dataRange.max)); - const endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp)); - const ticks = []; - let tickVal = finiteOrDefault(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min)))); - let exp = Math.floor(log10(tickVal)); - let significand = Math.floor(tickVal / Math.pow(10, exp)); - let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1; - do { - ticks.push({value: tickVal, major: isMajor(tickVal)}); - ++significand; - if (significand === 10) { - significand = 1; - ++exp; - precision = exp >= 0 ? 1 : precision; - } - tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision; - } while (exp < endExp || (exp === endExp && significand < endSignificand)); - const lastTick = finiteOrDefault(generationOptions.max, tickVal); - ticks.push({value: lastTick, major: isMajor(tickVal)}); - return ticks; -} -class LogarithmicScale extends Scale { - constructor(cfg) { - super(cfg); - this.start = undefined; - this.end = undefined; - this._startValue = undefined; - this._valueRange = 0; - } - parse(raw, index) { - const value = LinearScaleBase.prototype.parse.apply(this, [raw, index]); - if (value === 0) { - this._zero = true; - return undefined; - } - return isNumberFinite(value) && value > 0 ? value : null; - } - determineDataLimits() { - const {min, max} = this.getMinMax(true); - this.min = isNumberFinite(min) ? Math.max(0, min) : null; - this.max = isNumberFinite(max) ? Math.max(0, max) : null; - if (this.options.beginAtZero) { - this._zero = true; - } - this.handleTickRangeOptions(); - } - handleTickRangeOptions() { - const {minDefined, maxDefined} = this.getUserBounds(); - let min = this.min; - let max = this.max; - const setMin = v => (min = minDefined ? min : v); - const setMax = v => (max = maxDefined ? max : v); - const exp = (v, m) => Math.pow(10, Math.floor(log10(v)) + m); - if (min === max) { - if (min <= 0) { - setMin(1); - setMax(10); - } else { - setMin(exp(min, -1)); - setMax(exp(max, +1)); - } - } - if (min <= 0) { - setMin(exp(max, -1)); - } - if (max <= 0) { - setMax(exp(min, +1)); - } - if (this._zero && this.min !== this._suggestedMin && min === exp(this.min, 0)) { - setMin(exp(min, -1)); - } - this.min = min; - this.max = max; - } - buildTicks() { - const opts = this.options; - const generationOptions = { - min: this._userMin, - max: this._userMax - }; - const ticks = generateTicks(generationOptions, this); - if (opts.bounds === 'ticks') { - _setMinAndMaxByKey(ticks, this, 'value'); - } - if (opts.reverse) { - ticks.reverse(); - this.start = this.max; - this.end = this.min; - } else { - this.start = this.min; - this.end = this.max; - } - return ticks; - } - getLabelForValue(value) { - return value === undefined - ? '0' - : formatNumber(value, this.chart.options.locale, this.options.ticks.format); - } - configure() { - const start = this.min; - super.configure(); - this._startValue = log10(start); - this._valueRange = log10(this.max) - log10(start); - } - getPixelForValue(value) { - if (value === undefined || value === 0) { - value = this.min; - } - if (value === null || isNaN(value)) { - return NaN; - } - return this.getPixelForDecimal(value === this.min - ? 0 - : (log10(value) - this._startValue) / this._valueRange); - } - getValueForPixel(pixel) { - const decimal = this.getDecimalForPixel(pixel); - return Math.pow(10, this._startValue + decimal * this._valueRange); - } -} -LogarithmicScale.id = 'logarithmic'; -LogarithmicScale.defaults = { - ticks: { - callback: Ticks.formatters.logarithmic, - major: { - enabled: true - } - } -}; - -function getTickBackdropHeight(opts) { - const tickOpts = opts.ticks; - if (tickOpts.display && opts.display) { - const padding = toPadding(tickOpts.backdropPadding); - return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height; - } - return 0; -} -function measureLabelSize(ctx, font, label) { - label = isArray(label) ? label : [label]; - return { - w: _longestText(ctx, font.string, label), - h: label.length * font.lineHeight - }; -} -function determineLimits(angle, pos, size, min, max) { - if (angle === min || angle === max) { - return { - start: pos - (size / 2), - end: pos + (size / 2) - }; - } else if (angle < min || angle > max) { - return { - start: pos - size, - end: pos - }; - } - return { - start: pos, - end: pos + size - }; -} -function fitWithPointLabels(scale) { - const orig = { - l: scale.left + scale._padding.left, - r: scale.right - scale._padding.right, - t: scale.top + scale._padding.top, - b: scale.bottom - scale._padding.bottom - }; - const limits = Object.assign({}, orig); - const labelSizes = []; - const padding = []; - const valueCount = scale._pointLabels.length; - const pointLabelOpts = scale.options.pointLabels; - const additionalAngle = pointLabelOpts.centerPointLabels ? PI / valueCount : 0; - for (let i = 0; i < valueCount; i++) { - const opts = pointLabelOpts.setContext(scale.getPointLabelContext(i)); - padding[i] = opts.padding; - const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle); - const plFont = toFont(opts.font); - const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]); - labelSizes[i] = textSize; - const angleRadians = _normalizeAngle(scale.getIndexAngle(i) + additionalAngle); - const angle = Math.round(toDegrees(angleRadians)); - const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180); - const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270); - updateLimits(limits, orig, angleRadians, hLimits, vLimits); - } - scale.setCenterPoint( - orig.l - limits.l, - limits.r - orig.r, - orig.t - limits.t, - limits.b - orig.b - ); - scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding); -} -function updateLimits(limits, orig, angle, hLimits, vLimits) { - const sin = Math.abs(Math.sin(angle)); - const cos = Math.abs(Math.cos(angle)); - let x = 0; - let y = 0; - if (hLimits.start < orig.l) { - x = (orig.l - hLimits.start) / sin; - limits.l = Math.min(limits.l, orig.l - x); - } else if (hLimits.end > orig.r) { - x = (hLimits.end - orig.r) / sin; - limits.r = Math.max(limits.r, orig.r + x); - } - if (vLimits.start < orig.t) { - y = (orig.t - vLimits.start) / cos; - limits.t = Math.min(limits.t, orig.t - y); - } else if (vLimits.end > orig.b) { - y = (vLimits.end - orig.b) / cos; - limits.b = Math.max(limits.b, orig.b + y); - } -} -function buildPointLabelItems(scale, labelSizes, padding) { - const items = []; - const valueCount = scale._pointLabels.length; - const opts = scale.options; - const extra = getTickBackdropHeight(opts) / 2; - const outerDistance = scale.drawingArea; - const additionalAngle = opts.pointLabels.centerPointLabels ? PI / valueCount : 0; - for (let i = 0; i < valueCount; i++) { - const pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + padding[i], additionalAngle); - const angle = Math.round(toDegrees(_normalizeAngle(pointLabelPosition.angle + HALF_PI))); - const size = labelSizes[i]; - const y = yForAngle(pointLabelPosition.y, size.h, angle); - const textAlign = getTextAlignForAngle(angle); - const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign); - items.push({ - x: pointLabelPosition.x, - y, - textAlign, - left, - top: y, - right: left + size.w, - bottom: y + size.h - }); - } - return items; -} -function getTextAlignForAngle(angle) { - if (angle === 0 || angle === 180) { - return 'center'; - } else if (angle < 180) { - return 'left'; - } - return 'right'; -} -function leftForTextAlign(x, w, align) { - if (align === 'right') { - x -= w; - } else if (align === 'center') { - x -= (w / 2); - } - return x; -} -function yForAngle(y, h, angle) { - if (angle === 90 || angle === 270) { - y -= (h / 2); - } else if (angle > 270 || angle < 90) { - y -= h; - } - return y; -} -function drawPointLabels(scale, labelCount) { - const {ctx, options: {pointLabels}} = scale; - for (let i = labelCount - 1; i >= 0; i--) { - const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i)); - const plFont = toFont(optsAtIndex.font); - const {x, y, textAlign, left, top, right, bottom} = scale._pointLabelItems[i]; - const {backdropColor} = optsAtIndex; - if (!isNullOrUndef(backdropColor)) { - const padding = toPadding(optsAtIndex.backdropPadding); - ctx.fillStyle = backdropColor; - ctx.fillRect(left - padding.left, top - padding.top, right - left + padding.width, bottom - top + padding.height); - } - renderText( - ctx, - scale._pointLabels[i], - x, - y + (plFont.lineHeight / 2), - plFont, - { - color: optsAtIndex.color, - textAlign: textAlign, - textBaseline: 'middle' - } - ); - } -} -function pathRadiusLine(scale, radius, circular, labelCount) { - const {ctx} = scale; - if (circular) { - ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU); - } else { - let pointPosition = scale.getPointPosition(0, radius); - ctx.moveTo(pointPosition.x, pointPosition.y); - for (let i = 1; i < labelCount; i++) { - pointPosition = scale.getPointPosition(i, radius); - ctx.lineTo(pointPosition.x, pointPosition.y); - } - } -} -function drawRadiusLine(scale, gridLineOpts, radius, labelCount) { - const ctx = scale.ctx; - const circular = gridLineOpts.circular; - const {color, lineWidth} = gridLineOpts; - if ((!circular && !labelCount) || !color || !lineWidth || radius < 0) { - return; - } - ctx.save(); - ctx.strokeStyle = color; - ctx.lineWidth = lineWidth; - ctx.setLineDash(gridLineOpts.borderDash); - ctx.lineDashOffset = gridLineOpts.borderDashOffset; - ctx.beginPath(); - pathRadiusLine(scale, radius, circular, labelCount); - ctx.closePath(); - ctx.stroke(); - ctx.restore(); -} -function createPointLabelContext(parent, index, label) { - return createContext(parent, { - label, - index, - type: 'pointLabel' - }); -} -class RadialLinearScale extends LinearScaleBase { - constructor(cfg) { - super(cfg); - this.xCenter = undefined; - this.yCenter = undefined; - this.drawingArea = undefined; - this._pointLabels = []; - this._pointLabelItems = []; - } - setDimensions() { - const padding = this._padding = toPadding(getTickBackdropHeight(this.options) / 2); - const w = this.width = this.maxWidth - padding.width; - const h = this.height = this.maxHeight - padding.height; - this.xCenter = Math.floor(this.left + w / 2 + padding.left); - this.yCenter = Math.floor(this.top + h / 2 + padding.top); - this.drawingArea = Math.floor(Math.min(w, h) / 2); - } - determineDataLimits() { - const {min, max} = this.getMinMax(false); - this.min = isNumberFinite(min) && !isNaN(min) ? min : 0; - this.max = isNumberFinite(max) && !isNaN(max) ? max : 0; - this.handleTickRangeOptions(); - } - computeTickLimit() { - return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options)); - } - generateTickLabels(ticks) { - LinearScaleBase.prototype.generateTickLabels.call(this, ticks); - this._pointLabels = this.getLabels() - .map((value, index) => { - const label = callback(this.options.pointLabels.callback, [value, index], this); - return label || label === 0 ? label : ''; - }) - .filter((v, i) => this.chart.getDataVisibility(i)); - } - fit() { - const opts = this.options; - if (opts.display && opts.pointLabels.display) { - fitWithPointLabels(this); - } else { - this.setCenterPoint(0, 0, 0, 0); - } - } - setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) { - this.xCenter += Math.floor((leftMovement - rightMovement) / 2); - this.yCenter += Math.floor((topMovement - bottomMovement) / 2); - this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement)); - } - getIndexAngle(index) { - const angleMultiplier = TAU / (this._pointLabels.length || 1); - const startAngle = this.options.startAngle || 0; - return _normalizeAngle(index * angleMultiplier + toRadians(startAngle)); - } - getDistanceFromCenterForValue(value) { - if (isNullOrUndef(value)) { - return NaN; - } - const scalingFactor = this.drawingArea / (this.max - this.min); - if (this.options.reverse) { - return (this.max - value) * scalingFactor; - } - return (value - this.min) * scalingFactor; - } - getValueForDistanceFromCenter(distance) { - if (isNullOrUndef(distance)) { - return NaN; - } - const scaledDistance = distance / (this.drawingArea / (this.max - this.min)); - return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance; - } - getPointLabelContext(index) { - const pointLabels = this._pointLabels || []; - if (index >= 0 && index < pointLabels.length) { - const pointLabel = pointLabels[index]; - return createPointLabelContext(this.getContext(), index, pointLabel); - } - } - getPointPosition(index, distanceFromCenter, additionalAngle = 0) { - const angle = this.getIndexAngle(index) - HALF_PI + additionalAngle; - return { - x: Math.cos(angle) * distanceFromCenter + this.xCenter, - y: Math.sin(angle) * distanceFromCenter + this.yCenter, - angle - }; - } - getPointPositionForValue(index, value) { - return this.getPointPosition(index, this.getDistanceFromCenterForValue(value)); - } - getBasePosition(index) { - return this.getPointPositionForValue(index || 0, this.getBaseValue()); - } - getPointLabelPosition(index) { - const {left, top, right, bottom} = this._pointLabelItems[index]; - return { - left, - top, - right, - bottom, - }; - } - drawBackground() { - const {backgroundColor, grid: {circular}} = this.options; - if (backgroundColor) { - const ctx = this.ctx; - ctx.save(); - ctx.beginPath(); - pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length); - ctx.closePath(); - ctx.fillStyle = backgroundColor; - ctx.fill(); - ctx.restore(); - } - } - drawGrid() { - const ctx = this.ctx; - const opts = this.options; - const {angleLines, grid} = opts; - const labelCount = this._pointLabels.length; - let i, offset, position; - if (opts.pointLabels.display) { - drawPointLabels(this, labelCount); - } - if (grid.display) { - this.ticks.forEach((tick, index) => { - if (index !== 0) { - offset = this.getDistanceFromCenterForValue(tick.value); - const optsAtIndex = grid.setContext(this.getContext(index - 1)); - drawRadiusLine(this, optsAtIndex, offset, labelCount); - } - }); - } - if (angleLines.display) { - ctx.save(); - for (i = labelCount - 1; i >= 0; i--) { - const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i)); - const {color, lineWidth} = optsAtIndex; - if (!lineWidth || !color) { - continue; - } - ctx.lineWidth = lineWidth; - ctx.strokeStyle = color; - ctx.setLineDash(optsAtIndex.borderDash); - ctx.lineDashOffset = optsAtIndex.borderDashOffset; - offset = this.getDistanceFromCenterForValue(opts.ticks.reverse ? this.min : this.max); - position = this.getPointPosition(i, offset); - ctx.beginPath(); - ctx.moveTo(this.xCenter, this.yCenter); - ctx.lineTo(position.x, position.y); - ctx.stroke(); - } - ctx.restore(); - } - } - drawBorder() {} - drawLabels() { - const ctx = this.ctx; - const opts = this.options; - const tickOpts = opts.ticks; - if (!tickOpts.display) { - return; - } - const startAngle = this.getIndexAngle(0); - let offset, width; - ctx.save(); - ctx.translate(this.xCenter, this.yCenter); - ctx.rotate(startAngle); - ctx.textAlign = 'center'; - ctx.textBaseline = 'middle'; - this.ticks.forEach((tick, index) => { - if (index === 0 && !opts.reverse) { - return; - } - const optsAtIndex = tickOpts.setContext(this.getContext(index)); - const tickFont = toFont(optsAtIndex.font); - offset = this.getDistanceFromCenterForValue(this.ticks[index].value); - if (optsAtIndex.showLabelBackdrop) { - ctx.font = tickFont.string; - width = ctx.measureText(tick.label).width; - ctx.fillStyle = optsAtIndex.backdropColor; - const padding = toPadding(optsAtIndex.backdropPadding); - ctx.fillRect( - -width / 2 - padding.left, - -offset - tickFont.size / 2 - padding.top, - width + padding.width, - tickFont.size + padding.height - ); - } - renderText(ctx, tick.label, 0, -offset, tickFont, { - color: optsAtIndex.color, - }); - }); - ctx.restore(); - } - drawTitle() {} -} -RadialLinearScale.id = 'radialLinear'; -RadialLinearScale.defaults = { - display: true, - animate: true, - position: 'chartArea', - angleLines: { - display: true, - lineWidth: 1, - borderDash: [], - borderDashOffset: 0.0 - }, - grid: { - circular: false - }, - startAngle: 0, - ticks: { - showLabelBackdrop: true, - callback: Ticks.formatters.numeric - }, - pointLabels: { - backdropColor: undefined, - backdropPadding: 2, - display: true, - font: { - size: 10 - }, - callback(label) { - return label; - }, - padding: 5, - centerPointLabels: false - } -}; -RadialLinearScale.defaultRoutes = { - 'angleLines.color': 'borderColor', - 'pointLabels.color': 'color', - 'ticks.color': 'color' -}; -RadialLinearScale.descriptors = { - angleLines: { - _fallback: 'grid' - } -}; - -const INTERVALS = { - millisecond: {common: true, size: 1, steps: 1000}, - second: {common: true, size: 1000, steps: 60}, - minute: {common: true, size: 60000, steps: 60}, - hour: {common: true, size: 3600000, steps: 24}, - day: {common: true, size: 86400000, steps: 30}, - week: {common: false, size: 604800000, steps: 4}, - month: {common: true, size: 2.628e9, steps: 12}, - quarter: {common: false, size: 7.884e9, steps: 4}, - year: {common: true, size: 3.154e10} -}; -const UNITS = (Object.keys(INTERVALS)); -function sorter(a, b) { - return a - b; -} -function parse(scale, input) { - if (isNullOrUndef(input)) { - return null; - } - const adapter = scale._adapter; - const {parser, round, isoWeekday} = scale._parseOpts; - let value = input; - if (typeof parser === 'function') { - value = parser(value); - } - if (!isNumberFinite(value)) { - value = typeof parser === 'string' - ? adapter.parse(value, parser) - : adapter.parse(value); - } - if (value === null) { - return null; - } - if (round) { - value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true) - ? adapter.startOf(value, 'isoWeek', isoWeekday) - : adapter.startOf(value, round); - } - return +value; -} -function determineUnitForAutoTicks(minUnit, min, max, capacity) { - const ilen = UNITS.length; - for (let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) { - const interval = INTERVALS[UNITS[i]]; - const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER; - if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) { - return UNITS[i]; - } - } - return UNITS[ilen - 1]; -} -function determineUnitForFormatting(scale, numTicks, minUnit, min, max) { - for (let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) { - const unit = UNITS[i]; - if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) { - return unit; - } - } - return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0]; -} -function determineMajorUnit(unit) { - for (let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) { - if (INTERVALS[UNITS[i]].common) { - return UNITS[i]; - } - } -} -function addTick(ticks, time, timestamps) { - if (!timestamps) { - ticks[time] = true; - } else if (timestamps.length) { - const {lo, hi} = _lookup(timestamps, time); - const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi]; - ticks[timestamp] = true; - } -} -function setMajorTicks(scale, ticks, map, majorUnit) { - const adapter = scale._adapter; - const first = +adapter.startOf(ticks[0].value, majorUnit); - const last = ticks[ticks.length - 1].value; - let major, index; - for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) { - index = map[major]; - if (index >= 0) { - ticks[index].major = true; - } - } - return ticks; -} -function ticksFromTimestamps(scale, values, majorUnit) { - const ticks = []; - const map = {}; - const ilen = values.length; - let i, value; - for (i = 0; i < ilen; ++i) { - value = values[i]; - map[value] = i; - ticks.push({ - value, - major: false - }); - } - return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit); -} -class TimeScale extends Scale { - constructor(props) { - super(props); - this._cache = { - data: [], - labels: [], - all: [] - }; - this._unit = 'day'; - this._majorUnit = undefined; - this._offsets = {}; - this._normalized = false; - this._parseOpts = undefined; - } - init(scaleOpts, opts) { - const time = scaleOpts.time || (scaleOpts.time = {}); - const adapter = this._adapter = new _adapters._date(scaleOpts.adapters.date); - mergeIf(time.displayFormats, adapter.formats()); - this._parseOpts = { - parser: time.parser, - round: time.round, - isoWeekday: time.isoWeekday - }; - super.init(scaleOpts); - this._normalized = opts.normalized; - } - parse(raw, index) { - if (raw === undefined) { - return null; - } - return parse(this, raw); - } - beforeLayout() { - super.beforeLayout(); - this._cache = { - data: [], - labels: [], - all: [] - }; - } - determineDataLimits() { - const options = this.options; - const adapter = this._adapter; - const unit = options.time.unit || 'day'; - let {min, max, minDefined, maxDefined} = this.getUserBounds(); - function _applyBounds(bounds) { - if (!minDefined && !isNaN(bounds.min)) { - min = Math.min(min, bounds.min); - } - if (!maxDefined && !isNaN(bounds.max)) { - max = Math.max(max, bounds.max); - } - } - if (!minDefined || !maxDefined) { - _applyBounds(this._getLabelBounds()); - if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') { - _applyBounds(this.getMinMax(false)); - } - } - min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit); - max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1; - this.min = Math.min(min, max - 1); - this.max = Math.max(min + 1, max); - } - _getLabelBounds() { - const arr = this.getLabelTimestamps(); - let min = Number.POSITIVE_INFINITY; - let max = Number.NEGATIVE_INFINITY; - if (arr.length) { - min = arr[0]; - max = arr[arr.length - 1]; - } - return {min, max}; - } - buildTicks() { - const options = this.options; - const timeOpts = options.time; - const tickOpts = options.ticks; - const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate(); - if (options.bounds === 'ticks' && timestamps.length) { - this.min = this._userMin || timestamps[0]; - this.max = this._userMax || timestamps[timestamps.length - 1]; - } - const min = this.min; - const max = this.max; - const ticks = _filterBetween(timestamps, min, max); - this._unit = timeOpts.unit || (tickOpts.autoSkip - ? determineUnitForAutoTicks(timeOpts.minUnit, this.min, this.max, this._getLabelCapacity(min)) - : determineUnitForFormatting(this, ticks.length, timeOpts.minUnit, this.min, this.max)); - this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined - : determineMajorUnit(this._unit); - this.initOffsets(timestamps); - if (options.reverse) { - ticks.reverse(); - } - return ticksFromTimestamps(this, ticks, this._majorUnit); - } - initOffsets(timestamps) { - let start = 0; - let end = 0; - let first, last; - if (this.options.offset && timestamps.length) { - first = this.getDecimalForValue(timestamps[0]); - if (timestamps.length === 1) { - start = 1 - first; - } else { - start = (this.getDecimalForValue(timestamps[1]) - first) / 2; - } - last = this.getDecimalForValue(timestamps[timestamps.length - 1]); - if (timestamps.length === 1) { - end = last; - } else { - end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2; - } - } - const limit = timestamps.length < 3 ? 0.5 : 0.25; - start = _limitValue(start, 0, limit); - end = _limitValue(end, 0, limit); - this._offsets = {start, end, factor: 1 / (start + 1 + end)}; - } - _generate() { - const adapter = this._adapter; - const min = this.min; - const max = this.max; - const options = this.options; - const timeOpts = options.time; - const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min)); - const stepSize = valueOrDefault(timeOpts.stepSize, 1); - const weekday = minor === 'week' ? timeOpts.isoWeekday : false; - const hasWeekday = isNumber(weekday) || weekday === true; - const ticks = {}; - let first = min; - let time, count; - if (hasWeekday) { - first = +adapter.startOf(first, 'isoWeek', weekday); - } - first = +adapter.startOf(first, hasWeekday ? 'day' : minor); - if (adapter.diff(max, min, minor) > 100000 * stepSize) { - throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor); - } - const timestamps = options.ticks.source === 'data' && this.getDataTimestamps(); - for (time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++) { - addTick(ticks, time, timestamps); - } - if (time === max || options.bounds === 'ticks' || count === 1) { - addTick(ticks, time, timestamps); - } - return Object.keys(ticks).sort((a, b) => a - b).map(x => +x); - } - getLabelForValue(value) { - const adapter = this._adapter; - const timeOpts = this.options.time; - if (timeOpts.tooltipFormat) { - return adapter.format(value, timeOpts.tooltipFormat); - } - return adapter.format(value, timeOpts.displayFormats.datetime); - } - _tickFormatFunction(time, index, ticks, format) { - const options = this.options; - const formats = options.time.displayFormats; - const unit = this._unit; - const majorUnit = this._majorUnit; - const minorFormat = unit && formats[unit]; - const majorFormat = majorUnit && formats[majorUnit]; - const tick = ticks[index]; - const major = majorUnit && majorFormat && tick && tick.major; - const label = this._adapter.format(time, format || (major ? majorFormat : minorFormat)); - const formatter = options.ticks.callback; - return formatter ? callback(formatter, [label, index, ticks], this) : label; - } - generateTickLabels(ticks) { - let i, ilen, tick; - for (i = 0, ilen = ticks.length; i < ilen; ++i) { - tick = ticks[i]; - tick.label = this._tickFormatFunction(tick.value, i, ticks); - } - } - getDecimalForValue(value) { - return value === null ? NaN : (value - this.min) / (this.max - this.min); - } - getPixelForValue(value) { - const offsets = this._offsets; - const pos = this.getDecimalForValue(value); - return this.getPixelForDecimal((offsets.start + pos) * offsets.factor); - } - getValueForPixel(pixel) { - const offsets = this._offsets; - const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end; - return this.min + pos * (this.max - this.min); - } - _getLabelSize(label) { - const ticksOpts = this.options.ticks; - const tickLabelWidth = this.ctx.measureText(label).width; - const angle = toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation); - const cosRotation = Math.cos(angle); - const sinRotation = Math.sin(angle); - const tickFontSize = this._resolveTickFontOptions(0).size; - return { - w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation), - h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation) - }; - } - _getLabelCapacity(exampleTime) { - const timeOpts = this.options.time; - const displayFormats = timeOpts.displayFormats; - const format = displayFormats[timeOpts.unit] || displayFormats.millisecond; - const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [exampleTime], this._majorUnit), format); - const size = this._getLabelSize(exampleLabel); - const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1; - return capacity > 0 ? capacity : 1; - } - getDataTimestamps() { - let timestamps = this._cache.data || []; - let i, ilen; - if (timestamps.length) { - return timestamps; - } - const metas = this.getMatchingVisibleMetas(); - if (this._normalized && metas.length) { - return (this._cache.data = metas[0].controller.getAllParsedValues(this)); - } - for (i = 0, ilen = metas.length; i < ilen; ++i) { - timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this)); - } - return (this._cache.data = this.normalize(timestamps)); - } - getLabelTimestamps() { - const timestamps = this._cache.labels || []; - let i, ilen; - if (timestamps.length) { - return timestamps; - } - const labels = this.getLabels(); - for (i = 0, ilen = labels.length; i < ilen; ++i) { - timestamps.push(parse(this, labels[i])); - } - return (this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps)); - } - normalize(values) { - return _arrayUnique(values.sort(sorter)); - } -} -TimeScale.id = 'time'; -TimeScale.defaults = { - bounds: 'data', - adapters: {}, - time: { - parser: false, - unit: false, - round: false, - isoWeekday: false, - minUnit: 'millisecond', - displayFormats: {} - }, - ticks: { - source: 'auto', - major: { - enabled: false - } - } -}; - -function interpolate(table, val, reverse) { - let lo = 0; - let hi = table.length - 1; - let prevSource, nextSource, prevTarget, nextTarget; - if (reverse) { - if (val >= table[lo].pos && val <= table[hi].pos) { - ({lo, hi} = _lookupByKey(table, 'pos', val)); - } - ({pos: prevSource, time: prevTarget} = table[lo]); - ({pos: nextSource, time: nextTarget} = table[hi]); - } else { - if (val >= table[lo].time && val <= table[hi].time) { - ({lo, hi} = _lookupByKey(table, 'time', val)); - } - ({time: prevSource, pos: prevTarget} = table[lo]); - ({time: nextSource, pos: nextTarget} = table[hi]); - } - const span = nextSource - prevSource; - return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget; -} -class TimeSeriesScale extends TimeScale { - constructor(props) { - super(props); - this._table = []; - this._minPos = undefined; - this._tableRange = undefined; - } - initOffsets() { - const timestamps = this._getTimestampsForTable(); - const table = this._table = this.buildLookupTable(timestamps); - this._minPos = interpolate(table, this.min); - this._tableRange = interpolate(table, this.max) - this._minPos; - super.initOffsets(timestamps); - } - buildLookupTable(timestamps) { - const {min, max} = this; - const items = []; - const table = []; - let i, ilen, prev, curr, next; - for (i = 0, ilen = timestamps.length; i < ilen; ++i) { - curr = timestamps[i]; - if (curr >= min && curr <= max) { - items.push(curr); - } - } - if (items.length < 2) { - return [ - {time: min, pos: 0}, - {time: max, pos: 1} - ]; - } - for (i = 0, ilen = items.length; i < ilen; ++i) { - next = items[i + 1]; - prev = items[i - 1]; - curr = items[i]; - if (Math.round((next + prev) / 2) !== curr) { - table.push({time: curr, pos: i / (ilen - 1)}); - } - } - return table; - } - _getTimestampsForTable() { - let timestamps = this._cache.all || []; - if (timestamps.length) { - return timestamps; - } - const data = this.getDataTimestamps(); - const label = this.getLabelTimestamps(); - if (data.length && label.length) { - timestamps = this.normalize(data.concat(label)); - } else { - timestamps = data.length ? data : label; - } - timestamps = this._cache.all = timestamps; - return timestamps; - } - getDecimalForValue(value) { - return (interpolate(this._table, value) - this._minPos) / this._tableRange; - } - getValueForPixel(pixel) { - const offsets = this._offsets; - const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end; - return interpolate(this._table, decimal * this._tableRange + this._minPos, true); - } -} -TimeSeriesScale.id = 'timeseries'; -TimeSeriesScale.defaults = TimeScale.defaults; - -var scales = /*#__PURE__*/Object.freeze({ -__proto__: null, -CategoryScale: CategoryScale, -LinearScale: LinearScale, -LogarithmicScale: LogarithmicScale, -RadialLinearScale: RadialLinearScale, -TimeScale: TimeScale, -TimeSeriesScale: TimeSeriesScale -}); - -Chart.register(controllers, scales, elements, plugins); -Chart.helpers = {...helpers}; -Chart._adapters = _adapters; -Chart.Animation = Animation; -Chart.Animations = Animations; -Chart.animator = animator; -Chart.controllers = registry.controllers.items; -Chart.DatasetController = DatasetController; -Chart.Element = Element; -Chart.elements = elements; -Chart.Interaction = Interaction; -Chart.layouts = layouts; -Chart.platforms = platforms; -Chart.Scale = Scale; -Chart.Ticks = Ticks; -Object.assign(Chart, controllers, scales, elements, plugins, platforms); -Chart.Chart = Chart; -if (typeof window !== 'undefined') { - window.Chart = Chart; -} - -return Chart; - -})); diff --git a/primary/public/lib/chart.min.js b/primary/public/lib/chart.min.js deleted file mode 100644 index 2b3e9984..00000000 --- a/primary/public/lib/chart.min.js +++ /dev/null @@ -1,13 +0,0 @@ -/*! - * Chart.js v3.7.1 - * https://www.chartjs.org - * (c) 2022 Chart.js Contributors - * Released under the MIT License - */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){"use strict";const t="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function e(e,i,s){const n=s||(t=>Array.prototype.slice.call(t));let o=!1,a=[];return function(...s){a=n(s),o||(o=!0,t.call(window,(()=>{o=!1,e.apply(i,a)})))}}function i(t,e){let i;return function(...s){return e?(clearTimeout(i),i=setTimeout(t,e,s)):t.apply(this,s),e}}const s=t=>"start"===t?"left":"end"===t?"right":"center",n=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2,o=(t,e,i,s)=>t===(s?"left":"right")?i:"center"===t?(e+i)/2:e;var a=new class{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,s){const n=e.listeners[s],o=e.duration;n.forEach((s=>s({chart:t,initial:e.initial,numSteps:o,currentStep:Math.min(i-e.start,o)})))}_refresh(){this._request||(this._running=!0,this._request=t.call(window,(()=>{this._update(),this._request=null,this._running&&this._refresh()})))}_update(t=Date.now()){let e=0;this._charts.forEach(((i,s)=>{if(!i.running||!i.items.length)return;const n=i.items;let o,a=n.length-1,r=!1;for(;a>=0;--a)o=n[a],o._active?(o._total>i.duration&&(i.duration=o._total),o.tick(t),r=!0):(n[a]=n[n.length-1],n.pop());r&&(s.draw(),this._notify(s,i,t,"progress")),n.length||(i.running=!1,this._notify(s,i,t,"complete"),i.initial=!1),e+=n.length})),this._lastDate=t,0===e&&(this._running=!1)}_getAnims(t){const e=this._charts;let i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){const e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce(((t,e)=>Math.max(t,e._duration)),0),this._refresh())}running(t){if(!this._running)return!1;const e=this._charts.get(t);return!!(e&&e.running&&e.items.length)}stop(t){const e=this._charts.get(t);if(!e||!e.items.length)return;const i=e.items;let s=i.length-1;for(;s>=0;--s)i[s].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}}; -/*! - * @kurkle/color v0.1.9 - * https://github.com/kurkle/color#readme - * (c) 2020 Jukka Kurkela - * Released under the MIT License - */const r={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},l="0123456789ABCDEF",h=t=>l[15&t],c=t=>l[(240&t)>>4]+l[15&t],d=t=>(240&t)>>4==(15&t);function u(t){var e=function(t){return d(t.r)&&d(t.g)&&d(t.b)&&d(t.a)}(t)?h:c;return t?"#"+e(t.r)+e(t.g)+e(t.b)+(t.a<255?e(t.a):""):t}function f(t){return t+.5|0}const g=(t,e,i)=>Math.max(Math.min(t,i),e);function p(t){return g(f(2.55*t),0,255)}function m(t){return g(f(255*t),0,255)}function x(t){return g(f(t/2.55)/100,0,1)}function b(t){return g(f(100*t),0,100)}const _=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const y=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function v(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function w(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function M(t,e,i){const s=v(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function k(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=n===e?(i-s)/h+(i>16&255,o>>8&255,255&o]}return t}(),T.transparent=[0,0,0,0]);const e=T[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}function R(t,e,i){if(t){let s=k(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=P(s),t.r=s[0],t.g=s[1],t.b=s[2]}}function E(t,e){return t?Object.assign(e||{},t):t}function I(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=m(t[3]))):(e=E(t,{r:0,g:0,b:0,a:1})).a=m(e.a),e}function z(t){return"r"===t.charAt(0)?function(t){const e=_.exec(t);let i,s,n,o=255;if(e){if(e[7]!==i){const t=+e[7];o=255&(e[8]?p(t):255*t)}return i=+e[1],s=+e[3],n=+e[5],i=255&(e[2]?p(i):i),s=255&(e[4]?p(s):s),n=255&(e[6]?p(n):n),{r:i,g:s,b:n,a:o}}}(t):C(t)}class F{constructor(t){if(t instanceof F)return t;const e=typeof t;let i;var s,n,o;"object"===e?i=I(t):"string"===e&&(o=(s=t).length,"#"===s[0]&&(4===o||5===o?n={r:255&17*r[s[1]],g:255&17*r[s[2]],b:255&17*r[s[3]],a:5===o?17*r[s[4]]:255}:7!==o&&9!==o||(n={r:r[s[1]]<<4|r[s[2]],g:r[s[3]]<<4|r[s[4]],b:r[s[5]]<<4|r[s[6]],a:9===o?r[s[7]]<<4|r[s[8]]:255})),i=n||L(t)||z(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=E(this._rgb);return t&&(t.a=x(t.a)),t}set rgb(t){this._rgb=I(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${x(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):this._rgb;var t}hexString(){return this._valid?u(this._rgb):this._rgb}hslString(){return this._valid?function(t){if(!t)return;const e=k(t),i=e[0],s=b(e[1]),n=b(e[2]);return t.a<255?`hsla(${i}, ${s}%, ${n}%, ${x(t.a)})`:`hsl(${i}, ${s}%, ${n}%)`}(this._rgb):this._rgb}mix(t,e){const i=this;if(t){const s=i.rgb,n=t.rgb;let o;const a=e===o?.5:e,r=2*a-1,l=s.a-n.a,h=((r*l==-1?r:(r+l)/(1+r*l))+1)/2;o=1-h,s.r=255&h*s.r+o*n.r+.5,s.g=255&h*s.g+o*n.g+.5,s.b=255&h*s.b+o*n.b+.5,s.a=a*s.a+(1-a)*n.a,i.rgb=s}return i}clone(){return new F(this.rgb)}alpha(t){return this._rgb.a=m(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=f(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return R(this._rgb,2,t),this}darken(t){return R(this._rgb,2,-t),this}saturate(t){return R(this._rgb,1,t),this}desaturate(t){return R(this._rgb,1,-t),this}rotate(t){return function(t,e){var i=k(t);i[0]=D(i[0]+e),i=P(i),t.r=i[0],t.g=i[1],t.b=i[2]}(this._rgb,t),this}}function B(t){return new F(t)}const V=t=>t instanceof CanvasGradient||t instanceof CanvasPattern;function W(t){return V(t)?t:B(t)}function N(t){return V(t)?t:B(t).saturate(.5).darken(.1).hexString()}function H(){}const j=function(){let t=0;return function(){return t++}}();function $(t){return null==t}function Y(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.substr(0,7)&&"Array]"===e.substr(-6)}function U(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}const X=t=>("number"==typeof t||t instanceof Number)&&isFinite(+t);function q(t,e){return X(t)?t:e}function K(t,e){return void 0===t?e:t}const G=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:t/e,Z=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function J(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function Q(t,e,i,s){let n,o,a;if(Y(t))if(o=t.length,s)for(n=o-1;n>=0;n--)e.call(i,t[n],n);else for(n=0;ni;)t=t[e.substr(i,s-i)],i=s+1,s=rt(e,i);return t}function ht(t){return t.charAt(0).toUpperCase()+t.slice(1)}const ct=t=>void 0!==t,dt=t=>"function"==typeof t,ut=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function ft(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const gt=Object.create(null),pt=Object.create(null);function mt(t,e){if(!e)return t;const i=e.split(".");for(let e=0,s=i.length;et.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>N(e.backgroundColor),this.hoverBorderColor=(t,e)=>N(e.borderColor),this.hoverColor=(t,e)=>N(e.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t)}set(t,e){return xt(this,t,e)}get(t){return mt(this,t)}describe(t,e){return xt(pt,t,e)}override(t,e){return xt(gt,t,e)}route(t,e,i,s){const n=mt(this,t),o=mt(this,i),a="_"+e;Object.defineProperties(n,{[a]:{value:n[e],writable:!0},[e]:{enumerable:!0,get(){const t=this[a],e=o[s];return U(t)?Object.assign({},e,t):K(t,e)},set(t){this[a]=t}}})}}({_scriptable:t=>!t.startsWith("on"),_indexable:t=>"events"!==t,hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}});const _t=Math.PI,yt=2*_t,vt=yt+_t,wt=Number.POSITIVE_INFINITY,Mt=_t/180,kt=_t/2,St=_t/4,Pt=2*_t/3,Dt=Math.log10,Ct=Math.sign;function Ot(t){const e=Math.round(t);t=Lt(t,e,t/1e3)?e:t;const i=Math.pow(10,Math.floor(Dt(t))),s=t/i;return(s<=1?1:s<=2?2:s<=5?5:10)*i}function At(t){const e=[],i=Math.sqrt(t);let s;for(s=1;st-e)).pop(),e}function Tt(t){return!isNaN(parseFloat(t))&&isFinite(t)}function Lt(t,e,i){return Math.abs(t-e)=t}function Et(t,e,i){let s,n,o;for(s=0,n=t.length;sl&&h=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function Ut(t){return!t||$(t.size)||$(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function Xt(t,e,i,s,n){let o=e[n];return o||(o=e[n]=t.measureText(n).width,i.push(n)),o>s&&(s=o),s}function qt(t,e,i,s){let n=(s=s||{}).data=s.data||{},o=s.garbageCollect=s.garbageCollect||[];s.font!==e&&(n=s.data={},o=s.garbageCollect=[],s.font=e),t.save(),t.font=e;let a=0;const r=i.length;let l,h,c,d,u;for(l=0;li.length){for(l=0;l0&&t.stroke()}}function Jt(t,e,i){return i=i||.5,!e||t&&t.x>e.left-i&&t.xe.top-i&&t.y0&&""!==o.strokeColor;let l,h;for(t.save(),t.font=n.string,function(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]);$(e.rotation)||t.rotate(e.rotation);e.color&&(t.fillStyle=e.color);e.textAlign&&(t.textAlign=e.textAlign);e.textBaseline&&(t.textBaseline=e.textBaseline)}(t,o),l=0;lt[i]1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const re=(t,e,i)=>ae(t,i,(s=>t[s][e]ae(t,i,(s=>t[s][e]>=i));function he(t,e,i){let s=0,n=t.length;for(;ss&&t[n-1]>i;)n--;return s>0||n{const i="_onData"+ht(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...e){const n=s.apply(this,e);return t._chartjs.listeners.forEach((t=>{"function"==typeof t[i]&&t[i](...e)})),n}})})))}function ue(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(ce.forEach((e=>{delete t[e]})),delete t._chartjs)}function fe(t){const e=new Set;let i,s;for(i=0,s=t.length;iwindow.getComputedStyle(t,null);function be(t,e){return xe(t).getPropertyValue(e)}const _e=["top","right","bottom","left"];function ye(t,e,i){const s={};i=i?"-"+i:"";for(let n=0;n<4;n++){const o=_e[n];s[o]=parseFloat(t[e+"-"+o+i])||0}return s.width=s.left+s.right,s.height=s.top+s.bottom,s}function ve(t,e){const{canvas:i,currentDevicePixelRatio:s}=e,n=xe(i),o="border-box"===n.boxSizing,a=ye(n,"padding"),r=ye(n,"border","width"),{x:l,y:h,box:c}=function(t,e){const i=t.native||t,s=i.touches,n=s&&s.length?s[0]:i,{offsetX:o,offsetY:a}=n;let r,l,h=!1;if(((t,e,i)=>(t>0||e>0)&&(!i||!i.shadowRoot))(o,a,i.target))r=o,l=a;else{const t=e.getBoundingClientRect();r=n.clientX-t.left,l=n.clientY-t.top,h=!0}return{x:r,y:l,box:h}}(t,i),d=a.left+(c&&r.left),u=a.top+(c&&r.top);let{width:f,height:g}=e;return o&&(f-=a.width+r.width,g-=a.height+r.height),{x:Math.round((l-d)/f*i.width/s),y:Math.round((h-u)/g*i.height/s)}}const we=t=>Math.round(10*t)/10;function Me(t,e,i,s){const n=xe(t),o=ye(n,"margin"),a=me(n.maxWidth,t,"clientWidth")||wt,r=me(n.maxHeight,t,"clientHeight")||wt,l=function(t,e,i){let s,n;if(void 0===e||void 0===i){const o=pe(t);if(o){const t=o.getBoundingClientRect(),a=xe(o),r=ye(a,"border","width"),l=ye(a,"padding");e=t.width-l.width-r.width,i=t.height-l.height-r.height,s=me(a.maxWidth,o,"clientWidth"),n=me(a.maxHeight,o,"clientHeight")}else e=t.clientWidth,i=t.clientHeight}return{width:e,height:i,maxWidth:s||wt,maxHeight:n||wt}}(t,e,i);let{width:h,height:c}=l;if("content-box"===n.boxSizing){const t=ye(n,"border","width"),e=ye(n,"padding");h-=e.width+t.width,c-=e.height+t.height}return h=Math.max(0,h-o.width),c=Math.max(0,s?Math.floor(h/s):c-o.height),h=we(Math.min(h,a,l.maxWidth)),c=we(Math.min(c,r,l.maxHeight)),h&&!c&&(c=we(h/2)),{width:h,height:c}}function ke(t,e,i){const s=e||1,n=Math.floor(t.height*s),o=Math.floor(t.width*s);t.height=n/s,t.width=o/s;const a=t.canvas;return a.style&&(i||!a.style.height&&!a.style.width)&&(a.style.height=`${t.height}px`,a.style.width=`${t.width}px`),(t.currentDevicePixelRatio!==s||a.height!==n||a.width!==o)&&(t.currentDevicePixelRatio=s,a.height=n,a.width=o,t.ctx.setTransform(s,0,0,s,0,0),!0)}const Se=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};window.addEventListener("test",null,e),window.removeEventListener("test",null,e)}catch(t){}return t}();function Pe(t,e){const i=be(t,e),s=i&&i.match(/^(\d+)(\.\d+)?px$/);return s?+s[1]:void 0}function De(t,e){return"native"in t?{x:t.x,y:t.y}:ve(t,e)}function Ce(t,e,i,s){const{controller:n,data:o,_sorted:a}=t,r=n._cachedMeta.iScale;if(r&&e===r.axis&&"r"!==e&&a&&o.length){const t=r._reversePixels?le:re;if(!s)return t(o,e,i);if(n._sharedOptions){const s=o[0],n="function"==typeof s.getRange&&s.getRange(e);if(n){const s=t(o,e,i-n),a=t(o,e,i+n);return{lo:s.lo,hi:a.hi}}}}return{lo:0,hi:o.length-1}}function Oe(t,e,i,s,n){const o=t.getSortedVisibleDatasetMetas(),a=i[e];for(let t=0,i=o.length;t{t[r](n[a],s)&&o.push({element:t,datasetIndex:e,index:i}),t.inRange(n.x,n.y,s)&&(l=!0)})),i.intersect&&!l?[]:o}var Ee={modes:{index(t,e,i,s){const n=De(e,t),o=i.axis||"x",a=i.intersect?Ae(t,n,o,s):Le(t,n,o,!1,s),r=[];return a.length?(t.getSortedVisibleDatasetMetas().forEach((t=>{const e=a[0].index,i=t.data[e];i&&!i.skip&&r.push({element:i,datasetIndex:t.index,index:e})})),r):[]},dataset(t,e,i,s){const n=De(e,t),o=i.axis||"xy";let a=i.intersect?Ae(t,n,o,s):Le(t,n,o,!1,s);if(a.length>0){const e=a[0].datasetIndex,i=t.getDatasetMeta(e).data;a=[];for(let t=0;tAe(t,De(e,t),i.axis||"xy",s),nearest:(t,e,i,s)=>Le(t,De(e,t),i.axis||"xy",i.intersect,s),x:(t,e,i,s)=>Re(t,e,{axis:"x",intersect:i.intersect},s),y:(t,e,i,s)=>Re(t,e,{axis:"y",intersect:i.intersect},s)}};const Ie=new RegExp(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/),ze=new RegExp(/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/);function Fe(t,e){const i=(""+t).match(Ie);if(!i||"normal"===i[1])return 1.2*e;switch(t=+i[2],i[3]){case"px":return t;case"%":t/=100}return e*t}function Be(t,e){const i={},s=U(e),n=s?Object.keys(e):e,o=U(t)?s?i=>K(t[i],t[e[i]]):e=>t[e]:()=>t;for(const t of n)i[t]=+o(t)||0;return i}function Ve(t){return Be(t,{top:"y",right:"x",bottom:"y",left:"x"})}function We(t){return Be(t,["topLeft","topRight","bottomLeft","bottomRight"])}function Ne(t){const e=Ve(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function He(t,e){t=t||{},e=e||bt.font;let i=K(t.size,e.size);"string"==typeof i&&(i=parseInt(i,10));let s=K(t.style,e.style);s&&!(""+s).match(ze)&&(console.warn('Invalid font style specified: "'+s+'"'),s="");const n={family:K(t.family,e.family),lineHeight:Fe(K(t.lineHeight,e.lineHeight),i),size:i,style:s,weight:K(t.weight,e.weight),string:""};return n.string=Ut(n),n}function je(t,e,i,s){let n,o,a,r=!0;for(n=0,o=t.length;ni&&0===t?0:t+e;return{min:a(s,-Math.abs(o)),max:a(n,o)}}function Ye(t,e){return Object.assign(Object.create(t),e)}const Ue=["left","top","right","bottom"];function Xe(t,e){return t.filter((t=>t.pos===e))}function qe(t,e){return t.filter((t=>-1===Ue.indexOf(t.pos)&&t.box.axis===e))}function Ke(t,e){return t.sort(((t,i)=>{const s=e?i:t,n=e?t:i;return s.weight===n.weight?s.index-n.index:s.weight-n.weight}))}function Ge(t,e){const i=function(t){const e={};for(const i of t){const{stack:t,pos:s,stackWeight:n}=i;if(!t||!Ue.includes(s))continue;const o=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});o.count++,o.weight+=n}return e}(t),{vBoxMaxWidth:s,hBoxMaxHeight:n}=e;let o,a,r;for(o=0,a=t.length;o{s[t]=Math.max(e[t],i[t])})),s}return s(t?["left","right"]:["top","bottom"])}function ei(t,e,i,s){const n=[];let o,a,r,l,h,c;for(o=0,a=t.length,h=0;ot.box.fullSize)),!0),s=Ke(Xe(e,"left"),!0),n=Ke(Xe(e,"right")),o=Ke(Xe(e,"top"),!0),a=Ke(Xe(e,"bottom")),r=qe(e,"x"),l=qe(e,"y");return{fullSize:i,leftAndTop:s.concat(o),rightAndBottom:n.concat(l).concat(a).concat(r),chartArea:Xe(e,"chartArea"),vertical:s.concat(n).concat(l),horizontal:o.concat(a).concat(r)}}(t.boxes),l=r.vertical,h=r.horizontal;Q(t.boxes,(t=>{"function"==typeof t.beforeLayout&&t.beforeLayout()}));const c=l.reduce(((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1),0)||1,d=Object.freeze({outerWidth:e,outerHeight:i,padding:n,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/c,hBoxMaxHeight:a/2}),u=Object.assign({},n);Je(u,Ne(s));const f=Object.assign({maxPadding:u,w:o,h:a,x:n.left,y:n.top},n),g=Ge(l.concat(h),d);ei(r.fullSize,f,d,g),ei(l,f,d,g),ei(h,f,d,g)&&ei(l,f,d,g),function(t){const e=t.maxPadding;function i(i){const s=Math.max(e[i]-t[i],0);return t[i]+=s,s}t.y+=i("top"),t.x+=i("left"),i("right"),i("bottom")}(f),si(r.leftAndTop,f,d,g),f.x+=f.w,f.y+=f.h,si(r.rightAndBottom,f,d,g),t.chartArea={left:f.left,top:f.top,right:f.left+f.w,bottom:f.top+f.h,height:f.h,width:f.w},Q(r.chartArea,(e=>{const i=e.box;Object.assign(i,t.chartArea),i.update(f.w,f.h,{left:0,top:0,right:0,bottom:0})}))}};function oi(t,e=[""],i=t,s,n=(()=>t[0])){ct(s)||(s=mi("_fallback",t));const o={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:i,_fallback:s,_getTarget:n,override:n=>oi([n,...t],e,i,s)};return new Proxy(o,{deleteProperty:(e,i)=>(delete e[i],delete e._keys,delete t[0][i],!0),get:(i,s)=>ci(i,s,(()=>function(t,e,i,s){let n;for(const o of e)if(n=mi(li(o,t),i),ct(n))return hi(t,n)?gi(i,s,t,n):n}(s,e,t,i))),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(t[0]),has:(t,e)=>xi(t).includes(e),ownKeys:t=>xi(t),set(t,e,i){const s=t._storage||(t._storage=n());return t[e]=s[e]=i,delete t._keys,!0}})}function ai(t,e,i,s){const n={_cacheable:!1,_proxy:t,_context:e,_subProxy:i,_stack:new Set,_descriptors:ri(t,s),setContext:e=>ai(t,e,i,s),override:n=>ai(t.override(n),e,i,s)};return new Proxy(n,{deleteProperty:(e,i)=>(delete e[i],delete t[i],!0),get:(t,e,i)=>ci(t,e,(()=>function(t,e,i){const{_proxy:s,_context:n,_subProxy:o,_descriptors:a}=t;let r=s[e];dt(r)&&a.isScriptable(e)&&(r=function(t,e,i,s){const{_proxy:n,_context:o,_subProxy:a,_stack:r}=i;if(r.has(t))throw new Error("Recursion detected: "+Array.from(r).join("->")+"->"+t);r.add(t),e=e(o,a||s),r.delete(t),hi(t,e)&&(e=gi(n._scopes,n,t,e));return e}(e,r,t,i));Y(r)&&r.length&&(r=function(t,e,i,s){const{_proxy:n,_context:o,_subProxy:a,_descriptors:r}=i;if(ct(o.index)&&s(t))e=e[o.index%e.length];else if(U(e[0])){const i=e,s=n._scopes.filter((t=>t!==i));e=[];for(const l of i){const i=gi(s,n,t,l);e.push(ai(i,o,a&&a[t],r))}}return e}(e,r,t,a.isIndexable));hi(e,r)&&(r=ai(r,n,o&&o[e],a));return r}(t,e,i))),getOwnPropertyDescriptor:(e,i)=>e._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i),getPrototypeOf:()=>Reflect.getPrototypeOf(t),has:(e,i)=>Reflect.has(t,i),ownKeys:()=>Reflect.ownKeys(t),set:(e,i,s)=>(t[i]=s,delete e[i],!0)})}function ri(t,e={scriptable:!0,indexable:!0}){const{_scriptable:i=e.scriptable,_indexable:s=e.indexable,_allKeys:n=e.allKeys}=t;return{allKeys:n,scriptable:i,indexable:s,isScriptable:dt(i)?i:()=>i,isIndexable:dt(s)?s:()=>s}}const li=(t,e)=>t?t+ht(e):e,hi=(t,e)=>U(e)&&"adapters"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function ci(t,e,i){if(Object.prototype.hasOwnProperty.call(t,e))return t[e];const s=i();return t[e]=s,s}function di(t,e,i){return dt(t)?t(e,i):t}const ui=(t,e)=>!0===t?e:"string"==typeof t?lt(e,t):void 0;function fi(t,e,i,s,n){for(const o of e){const e=ui(i,o);if(e){t.add(e);const o=di(e._fallback,i,n);if(ct(o)&&o!==i&&o!==s)return o}else if(!1===e&&ct(s)&&i!==s)return null}return!1}function gi(t,e,i,s){const n=e._rootScopes,o=di(e._fallback,i,s),a=[...t,...n],r=new Set;r.add(s);let l=pi(r,a,i,o||i,s);return null!==l&&((!ct(o)||o===i||(l=pi(r,a,o,l,s),null!==l))&&oi(Array.from(r),[""],n,o,(()=>function(t,e,i){const s=t._getTarget();e in s||(s[e]={});const n=s[e];if(Y(n)&&U(i))return i;return n}(e,i,s))))}function pi(t,e,i,s,n){for(;i;)i=fi(t,e,i,s,n);return i}function mi(t,e){for(const i of e){if(!i)continue;const e=i[t];if(ct(e))return e}}function xi(t){let e=t._keys;return e||(e=t._keys=function(t){const e=new Set;for(const i of t)for(const t of Object.keys(i).filter((t=>!t.startsWith("_"))))e.add(t);return Array.from(e)}(t._scopes)),e}const bi=Number.EPSILON||1e-14,_i=(t,e)=>e"x"===t?"y":"x";function vi(t,e,i,s){const n=t.skip?e:t,o=e,a=i.skip?e:i,r=Vt(o,n),l=Vt(a,o);let h=r/(r+l),c=l/(r+l);h=isNaN(h)?0:h,c=isNaN(c)?0:c;const d=s*h,u=s*c;return{previous:{x:o.x-d*(a.x-n.x),y:o.y-d*(a.y-n.y)},next:{x:o.x+u*(a.x-n.x),y:o.y+u*(a.y-n.y)}}}function wi(t,e="x"){const i=yi(e),s=t.length,n=Array(s).fill(0),o=Array(s);let a,r,l,h=_i(t,0);for(a=0;a!t.skip))),"monotone"===e.cubicInterpolationMode)wi(t,n);else{let i=s?t[t.length-1]:t[0];for(o=0,a=t.length;o0===t||1===t,Pi=(t,e,i)=>-Math.pow(2,10*(t-=1))*Math.sin((t-e)*yt/i),Di=(t,e,i)=>Math.pow(2,-10*t)*Math.sin((t-e)*yt/i)+1,Ci={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*kt),easeOutSine:t=>Math.sin(t*kt),easeInOutSine:t=>-.5*(Math.cos(_t*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>Si(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>Si(t)?t:Pi(t,.075,.3),easeOutElastic:t=>Si(t)?t:Di(t,.075,.3),easeInOutElastic(t){const e=.1125;return Si(t)?t:t<.5?.5*Pi(2*t,e,.45):.5+.5*Di(2*t-1,e,.45)},easeInBack(t){const e=1.70158;return t*t*((e+1)*t-e)},easeOutBack(t){const e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-Ci.easeOutBounce(1-t),easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},easeInOutBounce:t=>t<.5?.5*Ci.easeInBounce(2*t):.5*Ci.easeOutBounce(2*t-1)+.5};function Oi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:t.y+i*(e.y-t.y)}}function Ai(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:"middle"===s?i<.5?t.y:e.y:"after"===s?i<1?t.y:e.y:i>0?e.y:t.y}}function Ti(t,e,i,s){const n={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},a=Oi(t,n,i),r=Oi(n,o,i),l=Oi(o,e,i),h=Oi(a,r,i),c=Oi(r,l,i);return Oi(h,c,i)}const Li=new Map;function Ri(t,e,i){return function(t,e){e=e||{};const i=t+JSON.stringify(e);let s=Li.get(i);return s||(s=new Intl.NumberFormat(t,e),Li.set(i,s)),s}(e,i).format(t)}function Ei(t,e,i){return t?function(t,e){return{x:i=>t+t+e-i,setWidth(t){e=t},textAlign:t=>"center"===t?t:"right"===t?"left":"right",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}}(e,i):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t}}function Ii(t,e){let i,s;"ltr"!==e&&"rtl"!==e||(i=t.canvas.style,s=[i.getPropertyValue("direction"),i.getPropertyPriority("direction")],i.setProperty("direction",e,"important"),t.prevTextDirection=s)}function zi(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Fi(t){return"angle"===t?{between:Ht,compare:Wt,normalize:Nt}:{between:Yt,compare:(t,e)=>t-e,normalize:t=>t}}function Bi({start:t,end:e,count:i,loop:s,style:n}){return{start:t%i,end:e%i,loop:s&&(e-t+1)%i==0,style:n}}function Vi(t,e,i){if(!i)return[t];const{property:s,start:n,end:o}=i,a=e.length,{compare:r,between:l,normalize:h}=Fi(s),{start:c,end:d,loop:u,style:f}=function(t,e,i){const{property:s,start:n,end:o}=i,{between:a,normalize:r}=Fi(s),l=e.length;let h,c,{start:d,end:u,loop:f}=t;if(f){for(d+=l,u+=l,h=0,c=l;hb||l(n,x,p)&&0!==r(n,x),v=()=>!b||0===r(o,p)||l(o,x,p);for(let t=c,i=c;t<=d;++t)m=e[t%a],m.skip||(p=h(m[s]),p!==x&&(b=l(p,n,o),null===_&&y()&&(_=0===r(p,n)?t:i),null!==_&&v()&&(g.push(Bi({start:_,end:t,loop:u,count:a,style:f})),_=null),i=t,x=p));return null!==_&&g.push(Bi({start:_,end:d,loop:u,count:a,style:f})),g}function Wi(t,e){const i=[],s=t.segments;for(let n=0;nn&&t[o%e].skip;)o--;return o%=e,{start:n,end:o}}(i,n,o,s);if(!0===s)return Hi(t,[{start:a,end:r,loop:o}],i,e);return Hi(t,function(t,e,i,s){const n=t.length,o=[];let a,r=e,l=t[e];for(a=e+1;a<=i;++a){const i=t[a%n];i.skip||i.stop?l.skip||(s=!1,o.push({start:e%n,end:(a-1)%n,loop:s}),e=r=i.stop?a:null):(r=a,l.skip&&(e=a)),l=i}return null!==r&&o.push({start:e%n,end:r%n,loop:s}),o}(i,a,rnull===t||""===t;const Gi=!!Se&&{passive:!0};function Zi(t,e,i){t.canvas.removeEventListener(e,i,Gi)}function Ji(t,e){for(const i of t)if(i===e||i.contains(e))return!0}function Qi(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||Ji(i.addedNodes,s),e=e&&!Ji(i.removedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}function ts(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||Ji(i.removedNodes,s),e=e&&!Ji(i.addedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}const es=new Map;let is=0;function ss(){const t=window.devicePixelRatio;t!==is&&(is=t,es.forEach(((e,i)=>{i.currentDevicePixelRatio!==t&&e()})))}function ns(t,i,s){const n=t.canvas,o=n&&pe(n);if(!o)return;const a=e(((t,e)=>{const i=o.clientWidth;s(t,e),i{const e=t[0],i=e.contentRect.width,s=e.contentRect.height;0===i&&0===s||a(i,s)}));return r.observe(o),function(t,e){es.size||window.addEventListener("resize",ss),es.set(t,e)}(t,a),r}function os(t,e,i){i&&i.disconnect(),"resize"===e&&function(t){es.delete(t),es.size||window.removeEventListener("resize",ss)}(t)}function as(t,i,s){const n=t.canvas,o=e((e=>{null!==t.ctx&&s(function(t,e){const i=qi[t.type]||t.type,{x:s,y:n}=ve(t,e);return{type:i,chart:e,native:t,x:void 0!==s?s:null,y:void 0!==n?n:null}}(e,t))}),t,(t=>{const e=t[0];return[e,e.offsetX,e.offsetY]}));return function(t,e,i){t.addEventListener(e,i,Gi)}(n,i,o),o}class rs extends Ui{acquireContext(t,e){const i=t&&t.getContext&&t.getContext("2d");return i&&i.canvas===t?(function(t,e){const i=t.style,s=t.getAttribute("height"),n=t.getAttribute("width");if(t.$chartjs={initial:{height:s,width:n,style:{display:i.display,height:i.height,width:i.width}}},i.display=i.display||"block",i.boxSizing=i.boxSizing||"border-box",Ki(n)){const e=Pe(t,"width");void 0!==e&&(t.width=e)}if(Ki(s))if(""===t.style.height)t.height=t.width/(e||2);else{const e=Pe(t,"height");void 0!==e&&(t.height=e)}}(t,e),i):null}releaseContext(t){const e=t.canvas;if(!e.$chartjs)return!1;const i=e.$chartjs.initial;["height","width"].forEach((t=>{const s=i[t];$(s)?e.removeAttribute(t):e.setAttribute(t,s)}));const s=i.style||{};return Object.keys(s).forEach((t=>{e.style[t]=s[t]})),e.width=e.width,delete e.$chartjs,!0}addEventListener(t,e,i){this.removeEventListener(t,e);const s=t.$proxies||(t.$proxies={}),n={attach:Qi,detach:ts,resize:ns}[e]||as;s[e]=n(t,e,i)}removeEventListener(t,e){const i=t.$proxies||(t.$proxies={}),s=i[e];if(!s)return;({attach:os,detach:os,resize:os}[e]||Zi)(t,e,s),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,s){return Me(t,e,i,s)}isAttached(t){const e=pe(t);return!(!e||!e.isConnected)}}function ls(t){return!ge()||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?Xi:rs}var hs=Object.freeze({__proto__:null,_detectPlatform:ls,BasePlatform:Ui,BasicPlatform:Xi,DomPlatform:rs});const cs="transparent",ds={boolean:(t,e,i)=>i>.5?e:t,color(t,e,i){const s=W(t||cs),n=s.valid&&W(e||cs);return n&&n.valid?n.mix(s,i).hexString():e},number:(t,e,i)=>t+(e-t)*i};class us{constructor(t,e,i,s){const n=e[i];s=je([t.to,s,n,t.from]);const o=je([t.from,n,s]);this._active=!0,this._fn=t.fn||ds[t.type||typeof o],this._easing=Ci[t.easing]||Ci.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=o,this._to=s,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);const s=this._target[this._prop],n=i-this._start,o=this._duration-n;this._start=i,this._duration=Math.floor(Math.max(o,t.duration)),this._total+=n,this._loop=!!t.loop,this._to=je([t.to,e,s,t.from]),this._from=je([t.from,s,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const e=t-this._start,i=this._duration,s=this._prop,n=this._from,o=this._loop,a=this._to;let r;if(this._active=n!==a&&(o||e1?2-r:r,r=this._easing(Math.min(1,Math.max(0,r))),this._target[s]=this._fn(n,a,r))}wait(){const t=this._promises||(this._promises=[]);return new Promise(((e,i)=>{t.push({res:e,rej:i})}))}_notify(t){const e=t?"res":"rej",i=this._promises||[];for(let t=0;t"onProgress"!==t&&"onComplete"!==t&&"fn"!==t}),bt.set("animations",{colors:{type:"color",properties:["color","borderColor","backgroundColor"]},numbers:{type:"number",properties:["x","y","borderWidth","radius","tension"]}}),bt.describe("animations",{_fallback:"animation"}),bt.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>0|t}}}});class gs{constructor(t,e){this._chart=t,this._properties=new Map,this.configure(e)}configure(t){if(!U(t))return;const e=this._properties;Object.getOwnPropertyNames(t).forEach((i=>{const s=t[i];if(!U(s))return;const n={};for(const t of fs)n[t]=s[t];(Y(s.properties)&&s.properties||[i]).forEach((t=>{t!==i&&e.has(t)||e.set(t,n)}))}))}_animateOptions(t,e){const i=e.options,s=function(t,e){if(!e)return;let i=t.options;if(!i)return void(t.options=e);i.$shared&&(t.options=i=Object.assign({},i,{$shared:!1,$animations:{}}));return i}(t,i);if(!s)return[];const n=this._createAnimations(s,i);return i.$shared&&function(t,e){const i=[],s=Object.keys(e);for(let e=0;e{t.options=i}),(()=>{})),n}_createAnimations(t,e){const i=this._properties,s=[],n=t.$animations||(t.$animations={}),o=Object.keys(e),a=Date.now();let r;for(r=o.length-1;r>=0;--r){const l=o[r];if("$"===l.charAt(0))continue;if("options"===l){s.push(...this._animateOptions(t,e));continue}const h=e[l];let c=n[l];const d=i.get(l);if(c){if(d&&c.active()){c.update(d,h,a);continue}c.cancel()}d&&d.duration?(n[l]=c=new us(d,t,l,h),s.push(c)):t[l]=h}return s}update(t,e){if(0===this._properties.size)return void Object.assign(t,e);const i=this._createAnimations(t,e);return i.length?(a.add(this._chart,i),!0):void 0}}function ps(t,e){const i=t&&t.options||{},s=i.reverse,n=void 0===i.min?e:0,o=void 0===i.max?e:0;return{start:s?o:n,end:s?n:o}}function ms(t,e){const i=[],s=t._getSortedDatasetMetas(e);let n,o;for(n=0,o=s.length;n0||!i&&e<0)return n.index}return null}function vs(t,e){const{chart:i,_cachedMeta:s}=t,n=i._stacks||(i._stacks={}),{iScale:o,vScale:a,index:r}=s,l=o.axis,h=a.axis,c=function(t,e,i){return`${t.id}.${e.id}.${i.stack||i.type}`}(o,a,s),d=e.length;let u;for(let t=0;ti[t].axis===e)).shift()}function Ms(t,e){const i=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const t of e){const e=t._stacks;if(!e||void 0===e[s]||void 0===e[s][i])return;delete e[s][i]}}}const ks=t=>"reset"===t||"none"===t,Ss=(t,e)=>e?t:Object.assign({},t);class Ps{constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.$context=void 0,this._syncList=[],this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=bs(t.vScale,t),this.addElements()}updateIndex(t){this.index!==t&&Ms(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,i=this.getDataset(),s=(t,e,i,s)=>"x"===t?e:"r"===t?s:i,n=e.xAxisID=K(i.xAxisID,ws(t,"x")),o=e.yAxisID=K(i.yAxisID,ws(t,"y")),a=e.rAxisID=K(i.rAxisID,ws(t,"r")),r=e.indexAxis,l=e.iAxisID=s(r,n,o,a),h=e.vAxisID=s(r,o,n,a);e.xScale=this.getScaleForId(n),e.yScale=this.getScaleForId(o),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(l),e.vScale=this.getScaleForId(h)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){const t=this._cachedMeta;this._data&&ue(this._data,this),t._stacked&&Ms(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(U(e))this._data=function(t){const e=Object.keys(t),i=new Array(e.length);let s,n,o;for(s=0,n=e.length;s0&&i._parsed[t-1];if(!1===this._parsing)i._parsed=s,i._sorted=!0,h=s;else{h=Y(s[t])?this.parseArrayData(i,s,t,e):U(s[t])?this.parseObjectData(i,s,t,e):this.parsePrimitiveData(i,s,t,e);const n=()=>null===l[a]||d&&l[a]t&&!e.hidden&&e._stacked&&{keys:ms(i,!0),values:null})(e,i,this.chart),l={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:h,max:c}=function(t){const{min:e,max:i,minDefined:s,maxDefined:n}=t.getUserBounds();return{min:s?e:Number.NEGATIVE_INFINITY,max:n?i:Number.POSITIVE_INFINITY}}(a);let d,u;function f(){u=s[d];const e=u[a.axis];return!X(u[t.axis])||h>e||c=0;--d)if(!f()){this.updateRangeFromParsed(l,t,u,r);break}return l}getAllParsedValues(t){const e=this._cachedMeta._parsed,i=[];let s,n,o;for(s=0,n=e.length;s=0&&tthis.getContext(i,s)),c);return f.$shared&&(f.$shared=r,n[o]=Object.freeze(Ss(f,r))),f}_resolveAnimations(t,e,i){const s=this.chart,n=this._cachedDataOpts,o=`animation-${e}`,a=n[o];if(a)return a;let r;if(!1!==s.options.animation){const s=this.chart.config,n=s.datasetAnimationScopeKeys(this._type,e),o=s.getOptionScopes(this.getDataset(),n);r=s.createResolver(o,this.getContext(t,i,e))}const l=new gs(s,r&&r.animations);return r&&r._cacheable&&(n[o]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||ks(t)||this.chart._animationsDisabled}updateElement(t,e,i,s){ks(s)?Object.assign(t,i):this._resolveAnimations(e,s).update(t,i)}updateSharedOptions(t,e,i){t&&!ks(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,s){t.active=s;const n=this.getStyle(e,s);this._resolveAnimations(e,i,s).update(t,{options:!s&&this.getSharedOptions(n)||n})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const e=this._data,i=this._cachedMeta.data;for(const[t,e,i]of this._syncList)this[t](e,i);this._syncList=[];const s=i.length,n=e.length,o=Math.min(n,s);o&&this.parse(0,o),n>s?this._insertElements(s,n-s,t):n{for(t.length+=e,a=t.length-1;a>=o;a--)t[a]=t[a-e]};for(r(n),a=t;a{s[t]=i[t]&&i[t].active()?i[t]._to:this[t]})),s}}Ds.defaults={},Ds.defaultRoutes=void 0;const Cs={values:t=>Y(t)?t:""+t,numeric(t,e,i){if(0===t)return"0";const s=this.chart.options.locale;let n,o=t;if(i.length>1){const e=Math.max(Math.abs(i[0].value),Math.abs(i[i.length-1].value));(e<1e-4||e>1e15)&&(n="scientific"),o=function(t,e){let i=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;Math.abs(i)>=1&&t!==Math.floor(t)&&(i=t-Math.floor(t));return i}(t,i)}const a=Dt(Math.abs(o)),r=Math.max(Math.min(-1*Math.floor(a),20),0),l={notation:n,minimumFractionDigits:r,maximumFractionDigits:r};return Object.assign(l,this.options.ticks.format),Ri(t,s,l)},logarithmic(t,e,i){if(0===t)return"0";const s=t/Math.pow(10,Math.floor(Dt(t)));return 1===s||2===s||5===s?Cs.numeric.call(this,t,e,i):""}};var Os={formatters:Cs};function As(t,e){const i=t.options.ticks,s=i.maxTicksLimit||function(t){const e=t.options.offset,i=t._tickSize(),s=t._length/i+(e?0:1),n=t._maxLength/i;return Math.floor(Math.min(s,n))}(t),n=i.major.enabled?function(t){const e=[];let i,s;for(i=0,s=t.length;is)return function(t,e,i,s){let n,o=0,a=i[0];for(s=Math.ceil(s),n=0;nn)return e}return Math.max(n,1)}(n,e,s);if(o>0){let t,i;const s=o>1?Math.round((r-a)/(o-1)):null;for(Ts(e,l,h,$(s)?0:a-s,a),t=0,i=o-1;te.lineWidth,tickColor:(t,e)=>e.color,offset:!1,borderDash:[],borderDashOffset:0,borderWidth:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:Os.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),bt.route("scale.ticks","color","","color"),bt.route("scale.grid","color","","borderColor"),bt.route("scale.grid","borderColor","","borderColor"),bt.route("scale.title","color","","color"),bt.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&"callback"!==t&&"parser"!==t,_indexable:t=>"borderDash"!==t&&"tickBorderDash"!==t}),bt.describe("scales",{_fallback:"scale"}),bt.describe("scale.ticks",{_scriptable:t=>"backdropPadding"!==t&&"callback"!==t,_indexable:t=>"backdropPadding"!==t});const Ls=(t,e,i)=>"top"===e||"left"===e?t[e]+i:t[e]-i;function Rs(t,e){const i=[],s=t.length/e,n=t.length;let o=0;for(;oa+r)))return h}function Is(t){return t.drawTicks?t.tickLength:0}function zs(t,e){if(!t.display)return 0;const i=He(t.font,e),s=Ne(t.padding);return(Y(t.text)?t.text.length:1)*i.lineHeight+s.height}function Fs(t,e,i){let n=s(t);return(i&&"right"!==e||!i&&"right"===e)&&(n=(t=>"left"===t?"right":"right"===t?"left":t)(n)),n}class Bs extends Ds{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:s}=this;return t=q(t,Number.POSITIVE_INFINITY),e=q(e,Number.NEGATIVE_INFINITY),i=q(i,Number.POSITIVE_INFINITY),s=q(s,Number.NEGATIVE_INFINITY),{min:q(t,i),max:q(e,s),minDefined:X(t),maxDefined:X(e)}}getMinMax(t){let e,{min:i,max:s,minDefined:n,maxDefined:o}=this.getUserBounds();if(n&&o)return{min:i,max:s};const a=this.getMatchingVisibleMetas();for(let r=0,l=a.length;rs?s:i,s=n&&i>s?i:s,{min:q(i,q(s,i)),max:q(s,q(i,s))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){J(this.options.beforeUpdate,[this])}update(t,e,i){const{beginAtZero:s,grace:n,ticks:o}=this.options,a=o.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=$e(this,n,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const r=a=n||i<=1||!this.isHorizontal())return void(this.labelRotation=s);const h=this._getLabelSizes(),c=h.widest.width,d=h.highest.height,u=jt(this.chart.width-c,0,this.maxWidth);o=t.offset?this.maxWidth/i:u/(i-1),c+6>o&&(o=u/(i-(t.offset?.5:1)),a=this.maxHeight-Is(t.grid)-e.padding-zs(t.title,this.chart.options.font),r=Math.sqrt(c*c+d*d),l=zt(Math.min(Math.asin(jt((h.highest.height+6)/o,-1,1)),Math.asin(jt(a/r,-1,1))-Math.asin(jt(d/r,-1,1)))),l=Math.max(s,Math.min(n,l))),this.labelRotation=l}afterCalculateLabelRotation(){J(this.options.afterCalculateLabelRotation,[this])}beforeFit(){J(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:e,options:{ticks:i,title:s,grid:n}}=this,o=this._isVisible(),a=this.isHorizontal();if(o){const o=zs(s,e.options.font);if(a?(t.width=this.maxWidth,t.height=Is(n)+o):(t.height=this.maxHeight,t.width=Is(n)+o),i.display&&this.ticks.length){const{first:e,last:s,widest:n,highest:o}=this._getLabelSizes(),r=2*i.padding,l=It(this.labelRotation),h=Math.cos(l),c=Math.sin(l);if(a){const e=i.mirror?0:c*n.width+h*o.height;t.height=Math.min(this.maxHeight,t.height+e+r)}else{const e=i.mirror?0:h*n.width+c*o.height;t.width=Math.min(this.maxWidth,t.width+e+r)}this._calculatePadding(e,s,c,h)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,s){const{ticks:{align:n,padding:o},position:a}=this.options,r=0!==this.labelRotation,l="top"!==a&&"x"===this.axis;if(this.isHorizontal()){const a=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1);let c=0,d=0;r?l?(c=s*t.width,d=i*e.height):(c=i*t.height,d=s*e.width):"start"===n?d=e.width:"end"===n?c=t.width:(c=t.width/2,d=e.width/2),this.paddingLeft=Math.max((c-a+o)*this.width/(this.width-a),0),this.paddingRight=Math.max((d-h+o)*this.width/(this.width-h),0)}else{let i=e.height/2,s=t.height/2;"start"===n?(i=0,s=t.height):"end"===n&&(i=e.height,s=0),this.paddingTop=i+o,this.paddingBottom=s+o}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){J(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:e}=this.options;return"top"===e||"bottom"===e||"x"===t}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){let e,i;for(this.beforeTickToLabelConversion(),this.generateTickLabels(t),e=0,i=t.length;e{const i=t.gc,s=i.length/2;let n;if(s>e){for(n=0;n({width:n[t]||0,height:o[t]||0});return{first:v(0),last:v(e-1),widest:v(_),highest:v(y),widths:n,heights:o}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const e=this._startPixel+t*this._length;return $t(this._alignToPixels?Kt(this.chart,e,0):e)}getDecimalForPixel(t){const e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){const e=this.ticks||[];if(t>=0&&ta*s?a/i:r/s:r*s0}_computeGridLineItems(t){const e=this.axis,i=this.chart,s=this.options,{grid:n,position:o}=s,a=n.offset,r=this.isHorizontal(),l=this.ticks.length+(a?1:0),h=Is(n),c=[],d=n.setContext(this.getContext()),u=d.drawBorder?d.borderWidth:0,f=u/2,g=function(t){return Kt(i,t,u)};let p,m,x,b,_,y,v,w,M,k,S,P;if("top"===o)p=g(this.bottom),y=this.bottom-h,w=p-f,k=g(t.top)+f,P=t.bottom;else if("bottom"===o)p=g(this.top),k=t.top,P=g(t.bottom)-f,y=p+f,w=this.top+h;else if("left"===o)p=g(this.right),_=this.right-h,v=p-f,M=g(t.left)+f,S=t.right;else if("right"===o)p=g(this.left),M=t.left,S=g(t.right)-f,_=p+f,v=this.left+h;else if("x"===e){if("center"===o)p=g((t.top+t.bottom)/2+.5);else if(U(o)){const t=Object.keys(o)[0],e=o[t];p=g(this.chart.scales[t].getPixelForValue(e))}k=t.top,P=t.bottom,y=p+f,w=y+h}else if("y"===e){if("center"===o)p=g((t.left+t.right)/2);else if(U(o)){const t=Object.keys(o)[0],e=o[t];p=g(this.chart.scales[t].getPixelForValue(e))}_=p-f,v=_-h,M=t.left,S=t.right}const D=K(s.ticks.maxTicksLimit,l),C=Math.max(1,Math.ceil(l/D));for(m=0;me.value===t));if(i>=0){return e.setContext(this.getContext(i)).lineWidth}return 0}drawGrid(t){const e=this.options.grid,i=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let n,o;const a=(t,e,s)=>{s.width&&s.color&&(i.save(),i.lineWidth=s.width,i.strokeStyle=s.color,i.setLineDash(s.borderDash||[]),i.lineDashOffset=s.borderDashOffset,i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(e.x,e.y),i.stroke(),i.restore())};if(e.display)for(n=0,o=s.length;n{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:i+1,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",s=[];let n,o;for(n=0,o=e.length;n{const s=i.split("."),n=s.pop(),o=[t].concat(s).join("."),a=e[i].split("."),r=a.pop(),l=a.join(".");bt.route(o,n,l,r)}))}(e,t.defaultRoutes);t.descriptors&&bt.describe(e,t.descriptors)}(t,o,i),this.override&&bt.override(t.id,t.overrides)),o}get(t){return this.items[t]}unregister(t){const e=this.items,i=t.id,s=this.scope;i in e&&delete e[i],s&&i in bt[s]&&(delete bt[s][i],this.override&&delete gt[i])}}var Ws=new class{constructor(){this.controllers=new Vs(Ps,"datasets",!0),this.elements=new Vs(Ds,"elements"),this.plugins=new Vs(Object,"plugins"),this.scales=new Vs(Bs,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(t,e,i){[...e].forEach((e=>{const s=i||this._getRegistryForType(e);i||s.isForType(e)||s===this.plugins&&e.id?this._exec(t,s,e):Q(e,(e=>{const s=i||this._getRegistryForType(e);this._exec(t,s,e)}))}))}_exec(t,e,i){const s=ht(t);J(i["before"+s],[],i),e[t](i),J(i["after"+s],[],i)}_getRegistryForType(t){for(let e=0;et.filter((t=>!e.some((e=>t.plugin.id===e.plugin.id))));this._notify(s(e,i),t,"stop"),this._notify(s(i,e),t,"start")}}function Hs(t,e){return e||!1!==t?!0===t?{}:t:null}function js(t,e,i,s){const n=t.pluginScopeKeys(e),o=t.getOptionScopes(i,n);return t.createResolver(o,s,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function $s(t,e){const i=bt.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||i.indexAxis||"x"}function Ys(t,e){return"x"===t||"y"===t?t:e.axis||("top"===(i=e.position)||"bottom"===i?"x":"left"===i||"right"===i?"y":void 0)||t.charAt(0).toLowerCase();var i}function Us(t){const e=t.options||(t.options={});e.plugins=K(e.plugins,{}),e.scales=function(t,e){const i=gt[t.type]||{scales:{}},s=e.scales||{},n=$s(t.type,e),o=Object.create(null),a=Object.create(null);return Object.keys(s).forEach((t=>{const e=s[t];if(!U(e))return console.error(`Invalid scale configuration for scale: ${t}`);if(e._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${t}`);const r=Ys(t,e),l=function(t,e){return t===e?"_index_":"_value_"}(r,n),h=i.scales||{};o[r]=o[r]||t,a[t]=ot(Object.create(null),[{axis:r},e,h[r],h[l]])})),t.data.datasets.forEach((i=>{const n=i.type||t.type,r=i.indexAxis||$s(n,e),l=(gt[n]||{}).scales||{};Object.keys(l).forEach((t=>{const e=function(t,e){let i=t;return"_index_"===t?i=e:"_value_"===t&&(i="x"===e?"y":"x"),i}(t,r),n=i[e+"AxisID"]||o[e]||e;a[n]=a[n]||Object.create(null),ot(a[n],[{axis:e},s[n],l[t]])}))})),Object.keys(a).forEach((t=>{const e=a[t];ot(e,[bt.scales[e.type],bt.scale])})),a}(t,e)}function Xs(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const qs=new Map,Ks=new Set;function Gs(t,e){let i=qs.get(t);return i||(i=e(),qs.set(t,i),Ks.add(i)),i}const Zs=(t,e,i)=>{const s=lt(e,i);void 0!==s&&t.add(s)};class Js{constructor(t){this._config=function(t){return(t=t||{}).data=Xs(t.data),Us(t),t}(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=Xs(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),Us(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return Gs(t,(()=>[[`datasets.${t}`,""]]))}datasetAnimationScopeKeys(t,e){return Gs(`${t}.transition.${e}`,(()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]]))}datasetElementScopeKeys(t,e){return Gs(`${t}-${e}`,(()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]]))}pluginScopeKeys(t){const e=t.id;return Gs(`${this.type}-plugin-${e}`,(()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]]))}_cachedScopes(t,e){const i=this._scopeCache;let s=i.get(t);return s&&!e||(s=new Map,i.set(t,s)),s}getOptionScopes(t,e,i){const{options:s,type:n}=this,o=this._cachedScopes(t,i),a=o.get(e);if(a)return a;const r=new Set;e.forEach((e=>{t&&(r.add(t),e.forEach((e=>Zs(r,t,e)))),e.forEach((t=>Zs(r,s,t))),e.forEach((t=>Zs(r,gt[n]||{},t))),e.forEach((t=>Zs(r,bt,t))),e.forEach((t=>Zs(r,pt,t)))}));const l=Array.from(r);return 0===l.length&&l.push(Object.create(null)),Ks.has(e)&&o.set(e,l),l}chartOptionScopes(){const{options:t,type:e}=this;return[t,gt[e]||{},bt.datasets[e]||{},{type:e},bt,pt]}resolveNamedOptions(t,e,i,s=[""]){const n={$shared:!0},{resolver:o,subPrefixes:a}=Qs(this._resolverCache,t,s);let r=o;if(function(t,e){const{isScriptable:i,isIndexable:s}=ri(t);for(const n of e){const e=i(n),o=s(n),a=(o||e)&&t[n];if(e&&(dt(a)||tn(a))||o&&Y(a))return!0}return!1}(o,e)){n.$shared=!1;r=ai(o,i=dt(i)?i():i,this.createResolver(t,i,a))}for(const t of e)n[t]=r[t];return n}createResolver(t,e,i=[""],s){const{resolver:n}=Qs(this._resolverCache,t,i);return U(e)?ai(n,e,void 0,s):n}}function Qs(t,e,i){let s=t.get(e);s||(s=new Map,t.set(e,s));const n=i.join();let o=s.get(n);if(!o){o={resolver:oi(e,i),subPrefixes:i.filter((t=>!t.toLowerCase().includes("hover")))},s.set(n,o)}return o}const tn=t=>U(t)&&Object.getOwnPropertyNames(t).reduce(((e,i)=>e||dt(t[i])),!1);const en=["top","bottom","left","right","chartArea"];function sn(t,e){return"top"===t||"bottom"===t||-1===en.indexOf(t)&&"x"===e}function nn(t,e){return function(i,s){return i[t]===s[t]?i[e]-s[e]:i[t]-s[t]}}function on(t){const e=t.chart,i=e.options.animation;e.notifyPlugins("afterRender"),J(i&&i.onComplete,[t],e)}function an(t){const e=t.chart,i=e.options.animation;J(i&&i.onProgress,[t],e)}function rn(t){return ge()&&"string"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const ln={},hn=t=>{const e=rn(t);return Object.values(ln).filter((t=>t.canvas===e)).pop()};function cn(t,e,i){const s=Object.keys(t);for(const n of s){const s=+n;if(s>=e){const o=t[n];delete t[n],(i>0||s>e)&&(t[s+i]=o)}}}class dn{constructor(t,e){const s=this.config=new Js(e),n=rn(t),o=hn(n);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas can be reused.");const r=s.createResolver(s.chartOptionScopes(),this.getContext());this.platform=new(s.platform||ls(n)),this.platform.updateConfig(s);const l=this.platform.acquireContext(n,r.aspectRatio),h=l&&l.canvas,c=h&&h.height,d=h&&h.width;this.id=j(),this.ctx=l,this.canvas=h,this.width=d,this.height=c,this._options=r,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new Ns,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=i((t=>this.update(t)),r.resizeDelay||0),this._dataChanges=[],ln[this.id]=this,l&&h?(a.listen(this,"complete",on),a.listen(this,"progress",an),this._initialize(),this.attached&&this.update()):console.error("Failed to create chart: can't acquire context from the given item")}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:s,_aspectRatio:n}=this;return $(t)?e&&n?n:s?i/s:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():ke(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Gt(this.canvas,this.ctx),this}stop(){return a.stop(this),this}resize(t,e){a.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){const i=this.options,s=this.canvas,n=i.maintainAspectRatio&&this.aspectRatio,o=this.platform.getMaximumSize(s,t,e,n),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),r=this.width?"resize":"attach";this.width=o.width,this.height=o.height,this._aspectRatio=this.aspectRatio,ke(this,a,!0)&&(this.notifyPlugins("resize",{size:o}),J(i.onResize,[this,o],this),this.attached&&this._doResize(r)&&this.render())}ensureScalesHaveIDs(){Q(this.options.scales||{},((t,e)=>{t.id=e}))}buildOrUpdateScales(){const t=this.options,e=t.scales,i=this.scales,s=Object.keys(i).reduce(((t,e)=>(t[e]=!1,t)),{});let n=[];e&&(n=n.concat(Object.keys(e).map((t=>{const i=e[t],s=Ys(t,i),n="r"===s,o="x"===s;return{options:i,dposition:n?"chartArea":o?"bottom":"left",dtype:n?"radialLinear":o?"category":"linear"}})))),Q(n,(e=>{const n=e.options,o=n.id,a=Ys(o,n),r=K(n.type,e.dtype);void 0!==n.position&&sn(n.position,a)===sn(e.dposition)||(n.position=e.dposition),s[o]=!0;let l=null;if(o in i&&i[o].type===r)l=i[o];else{l=new(Ws.getScale(r))({id:o,type:r,ctx:this.ctx,chart:this}),i[l.id]=l}l.init(n,t)})),Q(s,((t,e)=>{t||delete i[e]})),Q(i,(t=>{ni.configure(this,t,t.options),ni.addBox(this,t)}))}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort(((t,e)=>t.index-e.index)),i>e){for(let t=e;te.length&&delete this._stacks,t.forEach(((t,i)=>{0===e.filter((e=>e===t._dataset)).length&&this._destroyDatasetMeta(i)}))}buildOrUpdateControllers(){const t=[],e=this.data.datasets;let i,s;for(this._removeUnreferencedMetasets(),i=0,s=e.length;i{this.getDatasetMeta(e).controller.reset()}),this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const e=this.config;e.update();const i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1===this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0}))return;const n=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let o=0;for(let t=0,e=this.data.datasets.length;t{t.reset()})),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(nn("z","_idx"));const{_active:a,_lastEvent:r}=this;r?this._eventHandler(r,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){Q(this.scales,(t=>{ni.removeBox(this,t)})),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);ut(e,i)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(const{method:i,start:s,count:n}of e){cn(t,s,"_removeElements"===i?-n:n)}}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const e=this.data.datasets.length,i=e=>new Set(t.filter((t=>t[0]===e)).map(((t,e)=>e+","+t.splice(1).join(",")))),s=i(0);for(let t=1;tt.split(","))).map((t=>({method:t[1],start:+t[2],count:+t[3]})))}_updateLayout(t){if(!1===this.notifyPlugins("beforeLayout",{cancelable:!0}))return;ni.update(this,this.width,this.height,t);const e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],Q(this.boxes,(t=>{i&&"chartArea"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))}),this),this._layers.forEach(((t,e)=>{t._idx=e})),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(!1!==this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})){for(let t=0,e=this.data.datasets.length;t=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){const e=this.ctx,i=t._clip,s=!i.disabled,n=this.chartArea,o={meta:t,index:t.index,cancelable:!0};!1!==this.notifyPlugins("beforeDatasetDraw",o)&&(s&&Qt(e,{left:!1===i.left?0:n.left-i.left,right:!1===i.right?this.width:n.right+i.right,top:!1===i.top?0:n.top-i.top,bottom:!1===i.bottom?this.height:n.bottom+i.bottom}),t.controller.draw(),s&&te(e),o.cancelable=!1,this.notifyPlugins("afterDatasetDraw",o))}getElementsAtEventForMode(t,e,i,s){const n=Ee.modes[e];return"function"==typeof n?n(this,t,i,s):[]}getDatasetMeta(t){const e=this.data.datasets[t],i=this._metasets;let s=i.filter((t=>t&&t._dataset===e)).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(s)),s}getContext(){return this.$context||(this.$context=Ye(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const e=this.data.datasets[t];if(!e)return!1;const i=this.getDatasetMeta(t);return"boolean"==typeof i.hidden?!i.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){const s=i?"show":"hide",n=this.getDatasetMeta(t),o=n.controller._resolveAnimations(void 0,s);ct(e)?(n.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),o.update(n,{visible:i}),this.update((e=>e.datasetIndex===t?s:void 0)))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),a.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,i,s),t[i]=s},s=(t,e,i)=>{t.offsetX=e,t.offsetY=i,this._eventHandler(t)};Q(this.options.events,(t=>i(t,s)))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(i,s)=>{t[i]&&(e.removeEventListener(this,i,s),delete t[i])},n=(t,e)=>{this.canvas&&this.resize(t,e)};let o;const a=()=>{s("attach",a),this.attached=!0,this.resize(),i("resize",n),i("detach",o)};o=()=>{this.attached=!1,s("resize",n),this._stop(),this._resize(0,0),i("attach",a)},e.isAttached(this.canvas)?a():o()}unbindEvents(){Q(this._listeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._listeners={},Q(this._responsiveListeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){const s=i?"set":"remove";let n,o,a,r;for("dataset"===e&&(n=this.getDatasetMeta(t[0].datasetIndex),n.controller["_"+s+"DatasetHoverStyle"]()),a=0,r=t.length;a{const i=this.getDatasetMeta(t);if(!i)throw new Error("No dataset found at index "+t);return{datasetIndex:t,element:i.data[e],index:e}}));!tt(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}_updateHoverStyles(t,e,i){const s=this.options.hover,n=(t,e)=>t.filter((t=>!e.some((e=>t.datasetIndex===e.datasetIndex&&t.index===e.index)))),o=n(e,t),a=i?t:n(t,e);o.length&&this.updateHoverStyle(o,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(t,e){const i={event:t,replay:e,cancelable:!0,inChartArea:Jt(t,this.chartArea,this._minPadding)},s=e=>(e.options.events||this.options.events).includes(t.native.type);if(!1===this.notifyPlugins("beforeEvent",i,s))return;const n=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins("afterEvent",i,s),(n||i.changed)&&this.render(),this}_handleEvent(t,e,i){const{_active:s=[],options:n}=this,o=e,a=this._getActiveElements(t,s,i,o),r=ft(t),l=function(t,e,i,s){return i&&"mouseout"!==t.type?s?e:t:null}(t,this._lastEvent,i,r);i&&(this._lastEvent=null,J(n.onHover,[t,a,this],this),r&&J(n.onClick,[t,a,this],this));const h=!tt(a,s);return(h||e)&&(this._active=a,this._updateHoverStyles(a,s,e)),this._lastEvent=l,h}_getActiveElements(t,e,i,s){if("mouseout"===t.type)return[];if(!i)return e;const n=this.options.hover;return this.getElementsAtEventForMode(t,n.mode,n,s)}}const un=()=>Q(dn.instances,(t=>t._plugins.invalidate())),fn=!0;function gn(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}Object.defineProperties(dn,{defaults:{enumerable:fn,value:bt},instances:{enumerable:fn,value:ln},overrides:{enumerable:fn,value:gt},registry:{enumerable:fn,value:Ws},version:{enumerable:fn,value:"3.7.1"},getChart:{enumerable:fn,value:hn},register:{enumerable:fn,value:(...t)=>{Ws.add(...t),un()}},unregister:{enumerable:fn,value:(...t)=>{Ws.remove(...t),un()}}});class pn{constructor(t){this.options=t||{}}formats(){return gn()}parse(t,e){return gn()}format(t,e){return gn()}add(t,e,i){return gn()}diff(t,e,i){return gn()}startOf(t,e,i){return gn()}endOf(t,e){return gn()}}pn.override=function(t){Object.assign(pn.prototype,t)};var mn={_date:pn};function xn(t){const e=t.iScale,i=function(t,e){if(!t._cache.$bar){const i=t.getMatchingVisibleMetas(e);let s=[];for(let e=0,n=i.length;et-e)))}return t._cache.$bar}(e,t.type);let s,n,o,a,r=e._length;const l=()=>{32767!==o&&-32768!==o&&(ct(a)&&(r=Math.min(r,Math.abs(o-a)||r)),a=o)};for(s=0,n=i.length;sMath.abs(r)&&(l=r,h=a),e[i.axis]=h,e._custom={barStart:l,barEnd:h,start:n,end:o,min:a,max:r}}(t,e,i,s):e[i.axis]=i.parse(t,s),e}function _n(t,e,i,s){const n=t.iScale,o=t.vScale,a=n.getLabels(),r=n===o,l=[];let h,c,d,u;for(h=i,c=i+s;ht.x,i="left",s="right"):(e=t.base=i?1:-1)}(c,e,o)*n,d===o&&(p-=c/2),h=p+c),p===e.getPixelForValue(o)){const t=Ct(c)*e.getLineWidthForValue(o)/2;p+=t,c-=t}return{size:c,base:p,head:h,center:h+c/2}}_calculateBarIndexPixels(t,e){const i=e.scale,s=this.options,n=s.skipNull,o=K(s.maxBarThickness,1/0);let a,r;if(e.grouped){const i=n?this._getStackCount(t):e.stackCount,l="flex"===s.barThickness?function(t,e,i,s){const n=e.pixels,o=n[t];let a=t>0?n[t-1]:null,r=t=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){const e=this._cachedMeta,{xScale:i,yScale:s}=e,n=this.getParsed(t),o=i.getLabelForValue(n.x),a=s.getLabelForValue(n.y),r=n._custom;return{label:e.label,value:"("+o+", "+a+(r?", "+r:"")+")"}}update(t){const e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,s){const n="reset"===s,{iScale:o,vScale:a}=this._cachedMeta,r=this.resolveDataElementOptions(e,s),l=this.getSharedOptions(r),h=this.includeOptions(s,l),c=o.axis,d=a.axis;for(let r=e;r""}}}};class Dn extends Ps{constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,e){const i=this.getDataset().data,s=this._cachedMeta;if(!1===this._parsing)s._parsed=i;else{let n,o,a=t=>+i[t];if(U(i[t])){const{key:t="value"}=this._parsing;a=e=>+lt(i[e],t)}for(n=t,o=t+e;nHt(t,r,l,!0)?1:Math.max(e,e*i,s,s*i),g=(t,e,s)=>Ht(t,r,l,!0)?-1:Math.min(e,e*i,s,s*i),p=f(0,h,d),m=f(kt,c,u),x=g(_t,h,d),b=g(_t+kt,c,u);s=(p-x)/2,n=(m-b)/2,o=-(p+x)/2,a=-(m+b)/2}return{ratioX:s,ratioY:n,offsetX:o,offsetY:a}}(c,h,r),p=(i.width-o)/d,m=(i.height-o)/u,x=Math.max(Math.min(p,m)/2,0),b=Z(this.options.radius,x),_=(b-Math.max(b*r,0))/this._getVisibleDatasetWeightTotal();this.offsetX=f*b,this.offsetY=g*b,s.total=this.calculateTotal(),this.outerRadius=b-_*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-_*l,0),this.updateElements(n,0,n.length,t)}_circumference(t,e){const i=this.options,s=this._cachedMeta,n=this._getCircumference();return e&&i.animation.animateRotate||!this.chart.getDataVisibility(t)||null===s._parsed[t]||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*n/yt)}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.chartArea,r=o.options.animation,l=(a.left+a.right)/2,h=(a.top+a.bottom)/2,c=n&&r.animateScale,d=c?0:this.innerRadius,u=c?0:this.outerRadius,f=this.resolveDataElementOptions(e,s),g=this.getSharedOptions(f),p=this.includeOptions(s,g);let m,x=this._getRotation();for(m=0;m0&&!isNaN(t)?yt*(Math.abs(t)/e):0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=Ri(e._parsed[t],i.options.locale);return{label:s[t]||"",value:n}}getMaxBorderWidth(t){let e=0;const i=this.chart;let s,n,o,a,r;if(!t)for(s=0,n=i.data.datasets.length;s"spacing"!==t,_indexable:t=>"spacing"!==t},Dn.overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i}}=t.legend.options;return e.labels.map(((e,s)=>{const n=t.getDatasetMeta(0).controller.getStyle(s);return{text:e,fillStyle:n.backgroundColor,strokeStyle:n.borderColor,lineWidth:n.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(s),index:s}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}},tooltip:{callbacks:{title:()=>"",label(t){let e=t.label;const i=": "+t.formattedValue;return Y(e)?(e=e.slice(),e[0]+=i):e+=i,e}}}}};class Cn extends Ps{initialize(){this.enableOptionSharing=!0,super.initialize()}update(t){const e=this._cachedMeta,{dataset:i,data:s=[],_dataset:n}=e,o=this.chart._animationsDisabled;let{start:a,count:r}=function(t,e,i){const s=e.length;let n=0,o=s;if(t._sorted){const{iScale:a,_parsed:r}=t,l=a.axis,{min:h,max:c,minDefined:d,maxDefined:u}=a.getUserBounds();d&&(n=jt(Math.min(re(r,a.axis,h).lo,i?s:re(e,l,a.getPixelForValue(h)).lo),0,s-1)),o=u?jt(Math.max(re(r,a.axis,c).hi+1,i?0:re(e,l,a.getPixelForValue(c)).hi+1),n,s)-n:s-n}return{start:n,count:o}}(e,s,o);this._drawStart=a,this._drawCount=r,function(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.min,ymax:i.max};if(!s)return t._scaleRanges=n,!0;const o=s.xmin!==e.min||s.xmax!==e.max||s.ymin!==i.min||s.ymax!==i.max;return Object.assign(s,n),o}(e)&&(a=0,r=s.length),i._chart=this.chart,i._datasetIndex=this.index,i._decimated=!!n._decimated,i.points=s;const l=this.resolveDatasetElementOptions(t);this.options.showLine||(l.borderWidth=0),l.segment=this.options.segment,this.updateElement(i,void 0,{animated:!o,options:l},t),this.updateElements(s,a,r,t)}updateElements(t,e,i,s){const n="reset"===s,{iScale:o,vScale:a,_stacked:r,_dataset:l}=this._cachedMeta,h=this.resolveDataElementOptions(e,s),c=this.getSharedOptions(h),d=this.includeOptions(s,c),u=o.axis,f=a.axis,{spanGaps:g,segment:p}=this.options,m=Tt(g)?g:Number.POSITIVE_INFINITY,x=this.chart._animationsDisabled||n||"none"===s;let b=e>0&&this.getParsed(e-1);for(let h=e;h0&&i[u]-b[u]>m,p&&(g.parsed=i,g.raw=l.data[h]),d&&(g.options=c||this.resolveDataElementOptions(h,e.active?"active":s)),x||this.updateElement(e,h,g,s),b=i}this.updateSharedOptions(c,s,h)}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,s=t.data||[];if(!s.length)return i;const n=s[0].size(this.resolveDataElementOptions(0)),o=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(i,n,o)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}}Cn.id="line",Cn.defaults={datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1},Cn.overrides={scales:{_index_:{type:"category"},_value_:{type:"linear"}}};class On extends Ps{constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=Ri(e._parsed[t].r,i.options.locale);return{label:s[t]||"",value:n}}update(t){const e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}_updateRadius(){const t=this.chart,e=t.chartArea,i=t.options,s=Math.min(e.right-e.left,e.bottom-e.top),n=Math.max(s/2,0),o=(n-Math.max(i.cutoutPercentage?n/100*i.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=n-o*this.index,this.innerRadius=this.outerRadius-o}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=this.getDataset(),r=o.options.animation,l=this._cachedMeta.rScale,h=l.xCenter,c=l.yCenter,d=l.getIndexAngle(0)-.5*_t;let u,f=d;const g=360/this.countVisibleElements();for(u=0;u{!isNaN(t.data[s])&&this.chart.getDataVisibility(s)&&i++})),i}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?It(this.resolveDataElementOptions(t,e).angle||i):0}}On.id="polarArea",On.defaults={dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0},On.overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i}}=t.legend.options;return e.labels.map(((e,s)=>{const n=t.getDatasetMeta(0).controller.getStyle(s);return{text:e,fillStyle:n.backgroundColor,strokeStyle:n.borderColor,lineWidth:n.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(s),index:s}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}},tooltip:{callbacks:{title:()=>"",label:t=>t.chart.data.labels[t.dataIndex]+": "+t.formattedValue}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};class An extends Dn{}An.id="pie",An.defaults={cutout:0,rotation:0,circumference:360,radius:"100%"};class Tn extends Ps{getLabelAndValue(t){const e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}update(t){const e=this._cachedMeta,i=e.dataset,s=e.data||[],n=e.iScale.getLabels();if(i.points=s,"resize"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);const o={_loop:!0,_fullLoop:n.length===s.length,options:e};this.updateElement(i,void 0,o,t)}this.updateElements(s,0,s.length,t)}updateElements(t,e,i,s){const n=this.getDataset(),o=this._cachedMeta.rScale,a="reset"===s;for(let r=e;r"",label:t=>"("+t.label+", "+t.formattedValue+")"}}},scales:{x:{type:"linear"},y:{type:"linear"}}};var Rn=Object.freeze({__proto__:null,BarController:Sn,BubbleController:Pn,DoughnutController:Dn,LineController:Cn,PolarAreaController:On,PieController:An,RadarController:Tn,ScatterController:Ln});function En(t,e,i){const{startAngle:s,pixelMargin:n,x:o,y:a,outerRadius:r,innerRadius:l}=e;let h=n/r;t.beginPath(),t.arc(o,a,r,s-h,i+h),l>n?(h=n/l,t.arc(o,a,l,i+h,s-h,!0)):t.arc(o,a,n,i+kt,s-kt),t.closePath(),t.clip()}function In(t,e,i,s){const n=Be(t.options.borderRadius,["outerStart","outerEnd","innerStart","innerEnd"]);const o=(i-e)/2,a=Math.min(o,s*e/2),r=t=>{const e=(i-Math.min(o,t))*s/2;return jt(t,0,Math.min(o,e))};return{outerStart:r(n.outerStart),outerEnd:r(n.outerEnd),innerStart:jt(n.innerStart,0,a),innerEnd:jt(n.innerEnd,0,a)}}function zn(t,e,i,s){return{x:i+t*Math.cos(e),y:s+t*Math.sin(e)}}function Fn(t,e,i,s,n){const{x:o,y:a,startAngle:r,pixelMargin:l,innerRadius:h}=e,c=Math.max(e.outerRadius+s+i-l,0),d=h>0?h+s+i+l:0;let u=0;const f=n-r;if(s){const t=((h>0?h-s:0)+(c>0?c-s:0))/2;u=(f-(0!==t?f*t/(t+s):f))/2}const g=(f-Math.max(.001,f*c-i/_t)/c)/2,p=r+g+u,m=n-g-u,{outerStart:x,outerEnd:b,innerStart:_,innerEnd:y}=In(e,d,c,m-p),v=c-x,w=c-b,M=p+x/v,k=m-b/w,S=d+_,P=d+y,D=p+_/S,C=m-y/P;if(t.beginPath(),t.arc(o,a,c,M,k),b>0){const e=zn(w,k,o,a);t.arc(e.x,e.y,b,k,m+kt)}const O=zn(P,m,o,a);if(t.lineTo(O.x,O.y),y>0){const e=zn(P,C,o,a);t.arc(e.x,e.y,y,m+kt,C+Math.PI)}if(t.arc(o,a,d,m-y/d,p+_/d,!0),_>0){const e=zn(S,D,o,a);t.arc(e.x,e.y,_,D+Math.PI,p-kt)}const A=zn(v,p,o,a);if(t.lineTo(A.x,A.y),x>0){const e=zn(v,M,o,a);t.arc(e.x,e.y,x,p-kt,M)}t.closePath()}function Bn(t,e,i,s,n){const{options:o}=e,{borderWidth:a,borderJoinStyle:r}=o,l="inner"===o.borderAlign;a&&(l?(t.lineWidth=2*a,t.lineJoin=r||"round"):(t.lineWidth=a,t.lineJoin=r||"bevel"),e.fullCircles&&function(t,e,i){const{x:s,y:n,startAngle:o,pixelMargin:a,fullCircles:r}=e,l=Math.max(e.outerRadius-a,0),h=e.innerRadius+a;let c;for(i&&En(t,e,o+yt),t.beginPath(),t.arc(s,n,h,o+yt,o,!0),c=0;c=yt||Ht(n,a,r),f=Yt(o,l+d,h+d);return u&&f}getCenterPoint(t){const{x:e,y:i,startAngle:s,endAngle:n,innerRadius:o,outerRadius:a}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius","circumference"],t),{offset:r,spacing:l}=this.options,h=(s+n)/2,c=(o+a+l+r)/2;return{x:e+Math.cos(h)*c,y:i+Math.sin(h)*c}}tooltipPosition(t){return this.getCenterPoint(t)}draw(t){const{options:e,circumference:i}=this,s=(e.offset||0)/2,n=(e.spacing||0)/2;if(this.pixelMargin="inner"===e.borderAlign?.33:0,this.fullCircles=i>yt?Math.floor(i/yt):0,0===i||this.innerRadius<0||this.outerRadius<0)return;t.save();let o=0;if(s){o=s/2;const e=(this.startAngle+this.endAngle)/2;t.translate(Math.cos(e)*o,Math.sin(e)*o),this.circumference>=_t&&(o=s)}t.fillStyle=e.backgroundColor,t.strokeStyle=e.borderColor;const a=function(t,e,i,s){const{fullCircles:n,startAngle:o,circumference:a}=e;let r=e.endAngle;if(n){Fn(t,e,i,s,o+yt);for(let e=0;er&&o>r;return{count:s,start:l,loop:e.loop,ilen:h(a+(h?r-t:t))%o,_=()=>{f!==g&&(t.lineTo(m,g),t.lineTo(m,f),t.lineTo(m,p))};for(l&&(d=n[b(0)],t.moveTo(d.x,d.y)),c=0;c<=r;++c){if(d=n[b(c)],d.skip)continue;const e=d.x,i=d.y,s=0|e;s===u?(ig&&(g=i),m=(x*m+e)/++x):(_(),t.lineTo(e,i),u=s,x=0,f=g=i),p=i}_()}function Yn(t){const e=t.options,i=e.borderDash&&e.borderDash.length;return!(t._decimated||t._loop||e.tension||"monotone"===e.cubicInterpolationMode||e.stepped||i)?$n:jn}Vn.id="arc",Vn.defaults={borderAlign:"center",borderColor:"#fff",borderJoinStyle:void 0,borderRadius:0,borderWidth:2,offset:0,spacing:0,angle:void 0},Vn.defaultRoutes={backgroundColor:"backgroundColor"};const Un="function"==typeof Path2D;function Xn(t,e,i,s){Un&&!e.options.segment?function(t,e,i,s){let n=e._path;n||(n=e._path=new Path2D,e.path(n,i,s)&&n.closePath()),Wn(t,e.options),t.stroke(n)}(t,e,i,s):function(t,e,i,s){const{segments:n,options:o}=e,a=Yn(e);for(const r of n)Wn(t,o,r.style),t.beginPath(),a(t,e,r,{start:i,end:i+s-1})&&t.closePath(),t.stroke()}(t,e,i,s)}class qn extends Ds{constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){const i=this.options;if((i.tension||"monotone"===i.cubicInterpolationMode)&&!i.stepped&&!this._pointsUpdated){const s=i.spanGaps?this._loop:this._fullLoop;ki(this._points,i,t,s,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=Ni(this,this.options.segment))}first(){const t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){const t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){const i=this.options,s=t[e],n=this.points,o=Wi(this,{property:e,start:s,end:s});if(!o.length)return;const a=[],r=function(t){return t.stepped?Ai:t.tension||"monotone"===t.cubicInterpolationMode?Ti:Oi}(i);let l,h;for(l=0,h=o.length;l"borderDash"!==t&&"fill"!==t};class Gn extends Ds{constructor(t){super(),this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.options,{x:n,y:o}=this.getProps(["x","y"],i);return Math.pow(t-n,2)+Math.pow(e-o,2){oo(t)}))}var ro={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(t,e,i)=>{if(!i.enabled)return void ao(t);const s=t.width;t.data.datasets.forEach(((e,n)=>{const{_data:o,indexAxis:a}=e,r=t.getDatasetMeta(n),l=o||e.data;if("y"===je([a,t.options.indexAxis]))return;if("line"!==r.type)return;const h=t.scales[r.xAxisID];if("linear"!==h.type&&"time"!==h.type)return;if(t.options.parsing)return;let{start:c,count:d}=function(t,e){const i=e.length;let s,n=0;const{iScale:o}=t,{min:a,max:r,minDefined:l,maxDefined:h}=o.getUserBounds();return l&&(n=jt(re(e,o.axis,a).lo,0,i-1)),s=h?jt(re(e,o.axis,r).hi+1,n,i)-n:i-n,{start:n,count:s}}(r,l);if(d<=(i.threshold||4*s))return void oo(e);let u;switch($(o)&&(e._data=l,delete e.data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),i.algorithm){case"lttb":u=function(t,e,i,s,n){const o=n.samples||s;if(o>=i)return t.slice(e,e+i);const a=[],r=(i-2)/(o-2);let l=0;const h=e+i-1;let c,d,u,f,g,p=e;for(a[l++]=t[p],c=0;cu&&(u=f,d=t[s],g=s);a[l++]=d,p=g}return a[l++]=t[h],a}(l,c,d,s,i);break;case"min-max":u=function(t,e,i,s){let n,o,a,r,l,h,c,d,u,f,g=0,p=0;const m=[],x=e+i-1,b=t[e].x,_=t[x].x-b;for(n=e;nf&&(f=r,c=n),g=(p*g+o.x)/++p;else{const i=n-1;if(!$(h)&&!$(c)){const e=Math.min(h,c),s=Math.max(h,c);e!==d&&e!==i&&m.push({...t[e],x:g}),s!==d&&s!==i&&m.push({...t[s],x:g})}n>0&&i!==d&&m.push(t[i]),m.push(o),l=e,p=0,u=f=r,h=c=d=n}}return m}(l,c,d,s);break;default:throw new Error(`Unsupported decimation algorithm '${i.algorithm}'`)}e._decimated=u}))},destroy(t){ao(t)}};function lo(t,e,i){const s=function(t){const e=t.options,i=e.fill;let s=K(i&&i.target,i);return void 0===s&&(s=!!e.backgroundColor),!1!==s&&null!==s&&(!0===s?"origin":s)}(t);if(U(s))return!isNaN(s.value)&&s;let n=parseFloat(s);return X(n)&&Math.floor(n)===n?("-"!==s[0]&&"+"!==s[0]||(n=e+n),!(n===e||n<0||n>=i)&&n):["origin","start","end","stack","shape"].indexOf(s)>=0&&s}class ho{constructor(t){this.x=t.x,this.y=t.y,this.radius=t.radius}pathSegment(t,e,i){const{x:s,y:n,radius:o}=this;return e=e||{start:0,end:yt},t.arc(s,n,o,e.end,e.start,!0),!i.bounds}interpolate(t){const{x:e,y:i,radius:s}=this,n=t.angle;return{x:e+Math.cos(n)*s,y:i+Math.sin(n)*s,angle:n}}}function co(t){return(t.scale||{}).getPointPositionForValue?function(t){const{scale:e,fill:i}=t,s=e.options,n=e.getLabels().length,o=[],a=s.reverse?e.max:e.min,r=s.reverse?e.min:e.max;let l,h,c;if(c="start"===i?a:"end"===i?r:U(i)?i.value:e.getBaseValue(),s.grid.circular)return h=e.getPointPositionForValue(0,a),new ho({x:h.x,y:h.y,radius:e.getDistanceFromCenterForValue(c)});for(l=0;lt;e--){const t=i[e];if(!isNaN(t.x)&&!isNaN(t.y))break}return e}function fo(t,e,i){const s=[];for(let n=0;n{e=uo(t,e,n);const a=n[t],r=n[e];null!==s?(o.push({x:a.x,y:s}),o.push({x:r.x,y:s})):null!==i&&(o.push({x:i,y:a.y}),o.push({x:i,y:r.y}))})),o}(t,e),i.length?new qn({points:i,options:{tension:0},_loop:s,_fullLoop:s}):null}function xo(t,e,i){let s=t[e].fill;const n=[e];let o;if(!i)return s;for(;!1!==s&&-1===n.indexOf(s);){if(!X(s))return s;if(o=t[s],!o)return!1;if(o.visible)return s;n.push(s),s=o.fill}return!1}function bo(t,e,i){const{segments:s,points:n}=e;let o=!0,a=!1;t.beginPath();for(const r of s){const{start:s,end:l}=r,h=n[s],c=n[uo(s,l,n)];o?(t.moveTo(h.x,h.y),o=!1):(t.lineTo(h.x,i),t.lineTo(h.x,h.y)),a=!!e.pathSegment(t,r,{move:a}),a?t.closePath():t.lineTo(c.x,i)}t.lineTo(e.first().x,i),t.closePath(),t.clip()}function _o(t,e,i,s){if(s)return;let n=e[t],o=i[t];return"angle"===t&&(n=Nt(n),o=Nt(o)),{property:t,start:n,end:o}}function yo(t,e,i,s){return t&&e?s(t[i],e[i]):t?t[i]:e?e[i]:0}function vo(t,e,i){const{top:s,bottom:n}=e.chart.chartArea,{property:o,start:a,end:r}=i||{};"x"===o&&(t.beginPath(),t.rect(a,s,r-a,n-s),t.clip())}function wo(t,e,i,s){const n=e.interpolate(i,s);n&&t.lineTo(n.x,n.y)}function Mo(t,e){const{line:i,target:s,property:n,color:o,scale:a}=e,r=function(t,e,i){const s=t.segments,n=t.points,o=e.points,a=[];for(const t of s){let{start:s,end:r}=t;r=uo(s,r,n);const l=_o(i,n[s],n[r],t.loop);if(!e.segments){a.push({source:t,target:l,start:n[s],end:n[r]});continue}const h=Wi(e,l);for(const e of h){const s=_o(i,o[e.start],o[e.end],e.loop),r=Vi(t,n,s);for(const t of r)a.push({source:t,target:e,start:{[i]:yo(l,s,"start",Math.max)},end:{[i]:yo(l,s,"end",Math.min)}})}}return a}(i,s,n);for(const{source:e,target:l,start:h,end:c}of r){const{style:{backgroundColor:r=o}={}}=e,d=!0!==s;t.save(),t.fillStyle=r,vo(t,a,d&&_o(n,h,c)),t.beginPath();const u=!!i.pathSegment(t,e);let f;if(d){u?t.closePath():wo(t,s,c,n);const e=!!s.pathSegment(t,l,{move:u,reverse:!0});f=u&&e,f||wo(t,s,h,n)}t.closePath(),t.fill(f?"evenodd":"nonzero"),t.restore()}}function ko(t,e,i){const s=po(e),{line:n,scale:o,axis:a}=e,r=n.options,l=r.fill,h=r.backgroundColor,{above:c=h,below:d=h}=l||{};s&&n.points.length&&(Qt(t,i),function(t,e){const{line:i,target:s,above:n,below:o,area:a,scale:r}=e,l=i._loop?"angle":e.axis;t.save(),"x"===l&&o!==n&&(bo(t,s,a.top),Mo(t,{line:i,target:s,color:n,scale:r,property:l}),t.restore(),t.save(),bo(t,s,a.bottom)),Mo(t,{line:i,target:s,color:o,scale:r,property:l}),t.restore()}(t,{line:n,target:s,above:c,below:d,area:i,scale:o,axis:a}),te(t))}var So={id:"filler",afterDatasetsUpdate(t,e,i){const s=(t.data.datasets||[]).length,n=[];let o,a,r,l;for(a=0;a=0;--e){const i=n[e].$filler;i&&(i.line.updateControlPoints(o,i.axis),s&&ko(t.ctx,i,o))}},beforeDatasetsDraw(t,e,i){if("beforeDatasetsDraw"!==i.drawTime)return;const s=t.getSortedVisibleDatasetMetas();for(let e=s.length-1;e>=0;--e){const i=s[e].$filler;i&&ko(t.ctx,i,t.chartArea)}},beforeDatasetDraw(t,e,i){const s=e.meta.$filler;s&&!1!==s.fill&&"beforeDatasetDraw"===i.drawTime&&ko(t.ctx,s,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const Po=(t,e)=>{let{boxHeight:i=e,boxWidth:s=e}=t;return t.usePointStyle&&(i=Math.min(i,e),s=Math.min(s,e)),{boxWidth:s,boxHeight:i,itemHeight:Math.max(e,i)}};class Do extends Ds{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let e=J(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter((e=>t.filter(e,this.chart.data)))),t.sort&&(e=e.sort(((e,i)=>t.sort(e,i,this.chart.data)))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){const{options:t,ctx:e}=this;if(!t.display)return void(this.width=this.height=0);const i=t.labels,s=He(i.font),n=s.size,o=this._computeTitleHeight(),{boxWidth:a,itemHeight:r}=Po(i,n);let l,h;e.font=s.string,this.isHorizontal()?(l=this.maxWidth,h=this._fitRows(o,n,a,r)+10):(h=this.maxHeight,l=this._fitCols(o,n,a,r)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(h,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,s){const{ctx:n,maxWidth:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.lineWidths=[0],h=s+a;let c=t;n.textAlign="left",n.textBaseline="middle";let d=-1,u=-h;return this.legendItems.forEach(((t,f)=>{const g=i+e/2+n.measureText(t.text).width;(0===f||l[l.length-1]+g+2*a>o)&&(c+=h,l[l.length-(f>0?0:1)]=0,u+=h,d++),r[f]={left:0,top:u,row:d,width:g,height:s},l[l.length-1]+=g+a})),c}_fitCols(t,e,i,s){const{ctx:n,maxHeight:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.columnSizes=[],h=o-t;let c=a,d=0,u=0,f=0,g=0;return this.legendItems.forEach(((t,o)=>{const p=i+e/2+n.measureText(t.text).width;o>0&&u+s+2*a>h&&(c+=d+a,l.push({width:d,height:u}),f+=d+a,g++,d=u=0),r[o]={left:f,top:u,col:g,width:p,height:s},d=Math.max(d,p),u+=s+a})),c+=d,l.push({width:d,height:u}),c}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:s},rtl:o}}=this,a=Ei(o,this.left,this.width);if(this.isHorizontal()){let o=0,r=n(i,this.left+s,this.right-this.lineWidths[o]);for(const l of e)o!==l.row&&(o=l.row,r=n(i,this.left+s,this.right-this.lineWidths[o])),l.top+=this.top+t+s,l.left=a.leftForLtr(a.x(r),l.width),r+=l.width+s}else{let o=0,r=n(i,this.top+t+s,this.bottom-this.columnSizes[o].height);for(const l of e)l.col!==o&&(o=l.col,r=n(i,this.top+t+s,this.bottom-this.columnSizes[o].height)),l.top=r,l.left+=this.left+s,l.left=a.leftForLtr(a.x(l.left),l.width),r+=l.height+s}}isHorizontal(){return"top"===this.options.position||"bottom"===this.options.position}draw(){if(this.options.display){const t=this.ctx;Qt(t,this),this._draw(),te(t)}}_draw(){const{options:t,columnSizes:e,lineWidths:i,ctx:s}=this,{align:a,labels:r}=t,l=bt.color,h=Ei(t.rtl,this.left,this.width),c=He(r.font),{color:d,padding:u}=r,f=c.size,g=f/2;let p;this.drawTitle(),s.textAlign=h.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=c.string;const{boxWidth:m,boxHeight:x,itemHeight:b}=Po(r,f),_=this.isHorizontal(),y=this._computeTitleHeight();p=_?{x:n(a,this.left+u,this.right-i[0]),y:this.top+u+y,line:0}:{x:this.left+u,y:n(a,this.top+y+u,this.bottom-e[0].height),line:0},Ii(this.ctx,t.textDirection);const v=b+u;this.legendItems.forEach(((w,M)=>{s.strokeStyle=w.fontColor||d,s.fillStyle=w.fontColor||d;const k=s.measureText(w.text).width,S=h.textAlign(w.textAlign||(w.textAlign=r.textAlign)),P=m+g+k;let D=p.x,C=p.y;h.setWidth(this.width),_?M>0&&D+P+u>this.right&&(C=p.y+=v,p.line++,D=p.x=n(a,this.left+u,this.right-i[p.line])):M>0&&C+v>this.bottom&&(D=p.x=D+e[p.line].width+u,p.line++,C=p.y=n(a,this.top+y+u,this.bottom-e[p.line].height));!function(t,e,i){if(isNaN(m)||m<=0||isNaN(x)||x<0)return;s.save();const n=K(i.lineWidth,1);if(s.fillStyle=K(i.fillStyle,l),s.lineCap=K(i.lineCap,"butt"),s.lineDashOffset=K(i.lineDashOffset,0),s.lineJoin=K(i.lineJoin,"miter"),s.lineWidth=n,s.strokeStyle=K(i.strokeStyle,l),s.setLineDash(K(i.lineDash,[])),r.usePointStyle){const o={radius:m*Math.SQRT2/2,pointStyle:i.pointStyle,rotation:i.rotation,borderWidth:n},a=h.xPlus(t,m/2);Zt(s,o,a,e+g)}else{const o=e+Math.max((f-x)/2,0),a=h.leftForLtr(t,m),r=We(i.borderRadius);s.beginPath(),Object.values(r).some((t=>0!==t))?oe(s,{x:a,y:o,w:m,h:x,radius:r}):s.rect(a,o,m,x),s.fill(),0!==n&&s.stroke()}s.restore()}(h.x(D),C,w),D=o(S,D+m+g,_?D+P:this.right,t.rtl),function(t,e,i){se(s,i.text,t,e+b/2,c,{strikethrough:i.hidden,textAlign:h.textAlign(i.textAlign)})}(h.x(D),C,w),_?p.x+=P+u:p.y+=v})),zi(this.ctx,t.textDirection)}drawTitle(){const t=this.options,e=t.title,i=He(e.font),o=Ne(e.padding);if(!e.display)return;const a=Ei(t.rtl,this.left,this.width),r=this.ctx,l=e.position,h=i.size/2,c=o.top+h;let d,u=this.left,f=this.width;if(this.isHorizontal())f=Math.max(...this.lineWidths),d=this.top+c,u=n(t.align,u,this.right-f);else{const e=this.columnSizes.reduce(((t,e)=>Math.max(t,e.height)),0);d=c+n(t.align,this.top,this.bottom-e-t.labels.padding-this._computeTitleHeight())}const g=n(l,u,u+f);r.textAlign=a.textAlign(s(l)),r.textBaseline="middle",r.strokeStyle=e.color,r.fillStyle=e.color,r.font=i.string,se(r,e.text,g,d,i)}_computeTitleHeight(){const t=this.options.title,e=He(t.font),i=Ne(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,s,n;if(Yt(t,this.left,this.right)&&Yt(e,this.top,this.bottom))for(n=this.legendHitBoxes,i=0;it.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:i,pointStyle:s,textAlign:n,color:o}}=t.legend.options;return t._getSortedDatasetMetas().map((t=>{const a=t.controller.getStyle(i?0:void 0),r=Ne(a.borderWidth);return{text:e[t.index].label,fillStyle:a.backgroundColor,fontColor:o,hidden:!t.visible,lineCap:a.borderCapStyle,lineDash:a.borderDash,lineDashOffset:a.borderDashOffset,lineJoin:a.borderJoinStyle,lineWidth:(r.width+r.height)/4,strokeStyle:a.borderColor,pointStyle:s||a.pointStyle,rotation:a.rotation,textAlign:n||a.textAlign,borderRadius:0,datasetIndex:t.index}}),this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class Oo extends Ds{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){const i=this.options;if(this.left=0,this.top=0,!i.display)return void(this.width=this.height=this.right=this.bottom=0);this.width=this.right=t,this.height=this.bottom=e;const s=Y(i.text)?i.text.length:1;this._padding=Ne(i.padding);const n=s*He(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=n:this.width=n}isHorizontal(){const t=this.options.position;return"top"===t||"bottom"===t}_drawArgs(t){const{top:e,left:i,bottom:s,right:o,options:a}=this,r=a.align;let l,h,c,d=0;return this.isHorizontal()?(h=n(r,i,o),c=e+t,l=o-i):("left"===a.position?(h=i+t,c=n(r,s,e),d=-.5*_t):(h=o-t,c=n(r,e,s),d=.5*_t),l=s-e),{titleX:h,titleY:c,maxWidth:l,rotation:d}}draw(){const t=this.ctx,e=this.options;if(!e.display)return;const i=He(e.font),n=i.lineHeight/2+this._padding.top,{titleX:o,titleY:a,maxWidth:r,rotation:l}=this._drawArgs(n);se(t,e.text,0,0,i,{color:e.color,maxWidth:r,rotation:l,textAlign:s(e.align),textBaseline:"middle",translation:[o,a]})}}var Ao={id:"title",_element:Oo,start(t,e,i){!function(t,e){const i=new Oo({ctx:t.ctx,options:e,chart:t});ni.configure(t,i,e),ni.addBox(t,i),t.titleBlock=i}(t,i)},stop(t){const e=t.titleBlock;ni.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,i){const s=t.titleBlock;ni.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const To=new WeakMap;var Lo={id:"subtitle",start(t,e,i){const s=new Oo({ctx:t.ctx,options:i,chart:t});ni.configure(t,s,i),ni.addBox(t,s),To.set(t,s)},stop(t){ni.removeBox(t,To.get(t)),To.delete(t)},beforeUpdate(t,e,i){const s=To.get(t);ni.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Ro={average(t){if(!t.length)return!1;let e,i,s=0,n=0,o=0;for(e=0,i=t.length;e-1?t.split("\n"):t}function zo(t,e){const{element:i,datasetIndex:s,index:n}=e,o=t.getDatasetMeta(s).controller,{label:a,value:r}=o.getLabelAndValue(n);return{chart:t,label:a,parsed:o.getParsed(n),raw:t.data.datasets[s].data[n],formattedValue:r,dataset:o.getDataset(),dataIndex:n,datasetIndex:s,element:i}}function Fo(t,e){const i=t.chart.ctx,{body:s,footer:n,title:o}=t,{boxWidth:a,boxHeight:r}=e,l=He(e.bodyFont),h=He(e.titleFont),c=He(e.footerFont),d=o.length,u=n.length,f=s.length,g=Ne(e.padding);let p=g.height,m=0,x=s.reduce(((t,e)=>t+e.before.length+e.lines.length+e.after.length),0);if(x+=t.beforeBody.length+t.afterBody.length,d&&(p+=d*h.lineHeight+(d-1)*e.titleSpacing+e.titleMarginBottom),x){p+=f*(e.displayColors?Math.max(r,l.lineHeight):l.lineHeight)+(x-f)*l.lineHeight+(x-1)*e.bodySpacing}u&&(p+=e.footerMarginTop+u*c.lineHeight+(u-1)*e.footerSpacing);let b=0;const _=function(t){m=Math.max(m,i.measureText(t).width+b)};return i.save(),i.font=h.string,Q(t.title,_),i.font=l.string,Q(t.beforeBody.concat(t.afterBody),_),b=e.displayColors?a+2+e.boxPadding:0,Q(s,(t=>{Q(t.before,_),Q(t.lines,_),Q(t.after,_)})),b=0,i.font=c.string,Q(t.footer,_),i.restore(),m+=g.width,{width:m,height:p}}function Bo(t,e,i,s){const{x:n,width:o}=i,{width:a,chartArea:{left:r,right:l}}=t;let h="center";return"center"===s?h=n<=(r+l)/2?"left":"right":n<=o/2?h="left":n>=a-o/2&&(h="right"),function(t,e,i,s){const{x:n,width:o}=s,a=i.caretSize+i.caretPadding;return"left"===t&&n+o+a>e.width||"right"===t&&n-o-a<0||void 0}(h,t,e,i)&&(h="center"),h}function Vo(t,e,i){const s=i.yAlign||e.yAlign||function(t,e){const{y:i,height:s}=e;return it.height-s/2?"bottom":"center"}(t,i);return{xAlign:i.xAlign||e.xAlign||Bo(t,e,i,s),yAlign:s}}function Wo(t,e,i,s){const{caretSize:n,caretPadding:o,cornerRadius:a}=t,{xAlign:r,yAlign:l}=i,h=n+o,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=We(a);let g=function(t,e){let{x:i,width:s}=t;return"right"===e?i-=s:"center"===e&&(i-=s/2),i}(e,r);const p=function(t,e,i){let{y:s,height:n}=t;return"top"===e?s+=i:s-="bottom"===e?n+i:n/2,s}(e,l,h);return"center"===l?"left"===r?g+=h:"right"===r&&(g-=h):"left"===r?g-=Math.max(c,u)+n:"right"===r&&(g+=Math.max(d,f)+n),{x:jt(g,0,s.width-e.width),y:jt(p,0,s.height-e.height)}}function No(t,e,i){const s=Ne(i.padding);return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-s.right:t.x+s.left}function Ho(t){return Eo([],Io(t))}function jo(t,e){const i=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return i?t.override(i):t}class $o extends Ds{constructor(t){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=t.chart||t._chart,this._chart=this.chart,this.options=t.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(t){this.options=t,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const t=this._cachedAnimations;if(t)return t;const e=this.chart,i=this.options.setContext(this.getContext()),s=i.enabled&&e.options.animation&&i.animations,n=new gs(this.chart,s);return s._cacheable&&(this._cachedAnimations=Object.freeze(n)),n}getContext(){return this.$context||(this.$context=(t=this.chart.getContext(),e=this,i=this._tooltipItems,Ye(t,{tooltip:e,tooltipItems:i,type:"tooltip"})));var t,e,i}getTitle(t,e){const{callbacks:i}=e,s=i.beforeTitle.apply(this,[t]),n=i.title.apply(this,[t]),o=i.afterTitle.apply(this,[t]);let a=[];return a=Eo(a,Io(s)),a=Eo(a,Io(n)),a=Eo(a,Io(o)),a}getBeforeBody(t,e){return Ho(e.callbacks.beforeBody.apply(this,[t]))}getBody(t,e){const{callbacks:i}=e,s=[];return Q(t,(t=>{const e={before:[],lines:[],after:[]},n=jo(i,t);Eo(e.before,Io(n.beforeLabel.call(this,t))),Eo(e.lines,n.label.call(this,t)),Eo(e.after,Io(n.afterLabel.call(this,t))),s.push(e)})),s}getAfterBody(t,e){return Ho(e.callbacks.afterBody.apply(this,[t]))}getFooter(t,e){const{callbacks:i}=e,s=i.beforeFooter.apply(this,[t]),n=i.footer.apply(this,[t]),o=i.afterFooter.apply(this,[t]);let a=[];return a=Eo(a,Io(s)),a=Eo(a,Io(n)),a=Eo(a,Io(o)),a}_createItems(t){const e=this._active,i=this.chart.data,s=[],n=[],o=[];let a,r,l=[];for(a=0,r=e.length;at.filter(e,s,n,i)))),t.itemSort&&(l=l.sort(((e,s)=>t.itemSort(e,s,i)))),Q(l,(e=>{const i=jo(t.callbacks,e);s.push(i.labelColor.call(this,e)),n.push(i.labelPointStyle.call(this,e)),o.push(i.labelTextColor.call(this,e))})),this.labelColors=s,this.labelPointStyles=n,this.labelTextColors=o,this.dataPoints=l,l}update(t,e){const i=this.options.setContext(this.getContext()),s=this._active;let n,o=[];if(s.length){const t=Ro[i.position].call(this,s,this._eventPosition);o=this._createItems(i),this.title=this.getTitle(o,i),this.beforeBody=this.getBeforeBody(o,i),this.body=this.getBody(o,i),this.afterBody=this.getAfterBody(o,i),this.footer=this.getFooter(o,i);const e=this._size=Fo(this,i),a=Object.assign({},t,e),r=Vo(this.chart,i,a),l=Wo(i,a,r,this.chart);this.xAlign=r.xAlign,this.yAlign=r.yAlign,n={opacity:1,x:l.x,y:l.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(n={opacity:0});this._tooltipItems=o,this.$context=void 0,n&&this._resolveAnimations().update(this,n),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,s){const n=this.getCaretPosition(t,i,s);e.lineTo(n.x1,n.y1),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3)}getCaretPosition(t,e,i){const{xAlign:s,yAlign:n}=this,{caretSize:o,cornerRadius:a}=i,{topLeft:r,topRight:l,bottomLeft:h,bottomRight:c}=We(a),{x:d,y:u}=t,{width:f,height:g}=e;let p,m,x,b,_,y;return"center"===n?(_=u+g/2,"left"===s?(p=d,m=p-o,b=_+o,y=_-o):(p=d+f,m=p+o,b=_-o,y=_+o),x=p):(m="left"===s?d+Math.max(r,h)+o:"right"===s?d+f-Math.max(l,c)-o:this.caretX,"top"===n?(b=u,_=b-o,p=m-o,x=m+o):(b=u+g,_=b+o,p=m+o,x=m-o),y=b),{x1:p,x2:m,x3:x,y1:b,y2:_,y3:y}}drawTitle(t,e,i){const s=this.title,n=s.length;let o,a,r;if(n){const l=Ei(i.rtl,this.x,this.width);for(t.x=No(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",o=He(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=o.string,r=0;r0!==t))?(t.beginPath(),t.fillStyle=n.multiKeyBackground,oe(t,{x:e,y:g,w:l,h:r,radius:a}),t.fill(),t.stroke(),t.fillStyle=o.backgroundColor,t.beginPath(),oe(t,{x:i,y:g+1,w:l-2,h:r-2,radius:a}),t.fill()):(t.fillStyle=n.multiKeyBackground,t.fillRect(e,g,l,r),t.strokeRect(e,g,l,r),t.fillStyle=o.backgroundColor,t.fillRect(i,g+1,l-2,r-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){const{body:s}=this,{bodySpacing:n,bodyAlign:o,displayColors:a,boxHeight:r,boxWidth:l,boxPadding:h}=i,c=He(i.bodyFont);let d=c.lineHeight,u=0;const f=Ei(i.rtl,this.x,this.width),g=function(i){e.fillText(i,f.x(t.x+u),t.y+d/2),t.y+=d+n},p=f.textAlign(o);let m,x,b,_,y,v,w;for(e.textAlign=o,e.textBaseline="middle",e.font=c.string,t.x=No(this,p,i),e.fillStyle=i.bodyColor,Q(this.beforeBody,g),u=a&&"right"!==p?"center"===o?l/2+h:l+2+h:0,_=0,v=s.length;_0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,i=this.$animations,s=i&&i.x,n=i&&i.y;if(s||n){const i=Ro[t.position].call(this,this._active,this._eventPosition);if(!i)return;const o=this._size=Fo(this,t),a=Object.assign({},i,this._size),r=Vo(e,t,a),l=Wo(t,a,r,e);s._to===l.x&&n._to===l.y||(this.xAlign=r.xAlign,this.yAlign=r.yAlign,this.width=o.width,this.height=o.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,l))}}draw(t){const e=this.options.setContext(this.getContext());let i=this.opacity;if(!i)return;this._updateAnimationTarget(e);const s={width:this.width,height:this.height},n={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;const o=Ne(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(n,t,s,e),Ii(t,e.textDirection),n.y+=o.top,this.drawTitle(n,t,e),this.drawBody(n,t,e),this.drawFooter(n,t,e),zi(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){const i=this._active,s=t.map((({datasetIndex:t,index:e})=>{const i=this.chart.getDatasetMeta(t);if(!i)throw new Error("Cannot find a dataset at index "+t);return{datasetIndex:t,element:i.data[e],index:e}})),n=!tt(i,s),o=this._positionChanged(s,e);(n||o)&&(this._active=s,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,n=this._active||[],o=this._getActiveElements(t,n,e,i),a=this._positionChanged(o,t),r=e||!tt(o,n)||a;return r&&(this._active=o,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),r}_getActiveElements(t,e,i,s){const n=this.options;if("mouseout"===t.type)return[];if(!s)return e;const o=this.chart.getElementsAtEventForMode(t,n.mode,n,i);return n.reverse&&o.reverse(),o}_positionChanged(t,e){const{caretX:i,caretY:s,options:n}=this,o=Ro[n.position].call(this,t,e);return!1!==o&&(i!==o.x||s!==o.y)}}$o.positioners=Ro;var Yo={id:"tooltip",_element:$o,positioners:Ro,afterInit(t,e,i){i&&(t.tooltip=new $o({chart:t,options:i}))},beforeUpdate(t,e,i){t.tooltip&&t.tooltip.initialize(i)},reset(t,e,i){t.tooltip&&t.tooltip.initialize(i)},afterDraw(t){const e=t.tooltip,i={tooltip:e};!1!==t.notifyPlugins("beforeTooltipDraw",i)&&(e&&e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",i))},afterEvent(t,e){if(t.tooltip){const i=e.replay;t.tooltip.handleEvent(e.event,i,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:{beforeTitle:H,title(t){if(t.length>0){const e=t[0],i=e.chart.data.labels,s=i?i.length:0;if(this&&this.options&&"dataset"===this.options.mode)return e.dataset.label||"";if(e.label)return e.label;if(s>0&&e.dataIndex"filter"!==t&&"itemSort"!==t&&"external"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]},Uo=Object.freeze({__proto__:null,Decimation:ro,Filler:So,Legend:Co,SubTitle:Lo,Title:Ao,Tooltip:Yo});function Xo(t,e,i,s){const n=t.indexOf(e);if(-1===n)return((t,e,i,s)=>("string"==typeof e?(i=t.push(e)-1,s.unshift({index:i,label:e})):isNaN(e)&&(i=null),i))(t,e,i,s);return n!==t.lastIndexOf(e)?i:n}class qo extends Bs{constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const e=this._addedLabels;if(e.length){const t=this.getLabels();for(const{index:i,label:s}of e)t[i]===s&&t.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if($(t))return null;const i=this.getLabels();return((t,e)=>null===t?null:jt(Math.round(t),0,e))(e=isFinite(e)&&i[e]===t?e:Xo(i,t,K(e,t),this._addedLabels),i.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:i,max:s}=this.getMinMax(!0);"ticks"===this.options.bounds&&(t||(i=0),e||(s=this.getLabels().length-1)),this.min=i,this.max=s}buildTicks(){const t=this.min,e=this.max,i=this.options.offset,s=[];let n=this.getLabels();n=0===t&&e===n.length-1?n:n.slice(t,e+1),this._valueRange=Math.max(n.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let i=t;i<=e;i++)s.push({value:i});return s}getLabelForValue(t){const e=this.getLabels();return t>=0&&te.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}}function Ko(t,e,{horizontal:i,minRotation:s}){const n=It(s),o=(i?Math.sin(n):Math.cos(n))||.001,a=.75*e*(""+t).length;return Math.min(e/o,a)}qo.id="category",qo.defaults={ticks:{callback:qo.prototype.getLabelForValue}};class Go extends Bs{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(t,e){return $(t)||("number"==typeof t||t instanceof Number)&&!isFinite(+t)?null:+t}handleTickRangeOptions(){const{beginAtZero:t}=this.options,{minDefined:e,maxDefined:i}=this.getUserBounds();let{min:s,max:n}=this;const o=t=>s=e?s:t,a=t=>n=i?n:t;if(t){const t=Ct(s),e=Ct(n);t<0&&e<0?a(0):t>0&&e>0&&o(0)}if(s===n){let e=1;(n>=Number.MAX_SAFE_INTEGER||s<=Number.MIN_SAFE_INTEGER)&&(e=Math.abs(.05*n)),a(n+e),t||o(s-e)}this.min=s,this.max=n}getTickLimit(){const t=this.options.ticks;let e,{maxTicksLimit:i,stepSize:s}=t;return s?(e=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,e>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${e} ticks. Limiting to 1000.`),e=1e3)):(e=this.computeTickLimit(),i=i||11),i&&(e=Math.min(i,e)),e}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,e=t.ticks;let i=this.getTickLimit();i=Math.max(2,i);const s=function(t,e){const i=[],{bounds:s,step:n,min:o,max:a,precision:r,count:l,maxTicks:h,maxDigits:c,includeBounds:d}=t,u=n||1,f=h-1,{min:g,max:p}=e,m=!$(o),x=!$(a),b=!$(l),_=(p-g)/(c+1);let y,v,w,M,k=Ot((p-g)/f/u)*u;if(k<1e-14&&!m&&!x)return[{value:g},{value:p}];M=Math.ceil(p/k)-Math.floor(g/k),M>f&&(k=Ot(M*k/f/u)*u),$(r)||(y=Math.pow(10,r),k=Math.ceil(k*y)/y),"ticks"===s?(v=Math.floor(g/k)*k,w=Math.ceil(p/k)*k):(v=g,w=p),m&&x&&n&&Rt((a-o)/n,k/1e3)?(M=Math.round(Math.min((a-o)/k,h)),k=(a-o)/M,v=o,w=a):b?(v=m?o:v,w=x?a:w,M=l-1,k=(w-v)/M):(M=(w-v)/k,M=Lt(M,Math.round(M),k/1e3)?Math.round(M):Math.ceil(M));const S=Math.max(Ft(k),Ft(v));y=Math.pow(10,$(r)?S:r),v=Math.round(v*y)/y,w=Math.round(w*y)/y;let P=0;for(m&&(d&&v!==o?(i.push({value:o}),v0?i:null;this._zero=!0}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=X(t)?Math.max(0,t):null,this.max=X(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let i=this.min,s=this.max;const n=e=>i=t?i:e,o=t=>s=e?s:t,a=(t,e)=>Math.pow(10,Math.floor(Dt(t))+e);i===s&&(i<=0?(n(1),o(10)):(n(a(i,-1)),o(a(s,1)))),i<=0&&n(a(s,-1)),s<=0&&o(a(i,1)),this._zero&&this.min!==this._suggestedMin&&i===a(this.min,0)&&n(a(i,-1)),this.min=i,this.max=s}buildTicks(){const t=this.options,e=function(t,e){const i=Math.floor(Dt(e.max)),s=Math.ceil(e.max/Math.pow(10,i)),n=[];let o=q(t.min,Math.pow(10,Math.floor(Dt(e.min)))),a=Math.floor(Dt(o)),r=Math.floor(o/Math.pow(10,a)),l=a<0?Math.pow(10,Math.abs(a)):1;do{n.push({value:o,major:Jo(o)}),++r,10===r&&(r=1,++a,l=a>=0?1:l),o=Math.round(r*Math.pow(10,a)*l)/l}while(an?{start:e-i,end:e}:{start:e,end:e+i}}function ia(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},i=Object.assign({},e),s=[],n=[],o=t._pointLabels.length,a=t.options.pointLabels,r=a.centerPointLabels?_t/o:0;for(let d=0;de.r&&(r=(s.end-e.r)/o,t.r=Math.max(t.r,e.r+r)),n.starte.b&&(l=(n.end-e.b)/a,t.b=Math.max(t.b,e.b+l))}function na(t){return 0===t||180===t?"center":t<180?"left":"right"}function oa(t,e,i){return"right"===i?t-=e:"center"===i&&(t-=e/2),t}function aa(t,e,i){return 90===i||270===i?t-=e/2:(i>270||i<90)&&(t-=e),t}function ra(t,e,i,s){const{ctx:n}=t;if(i)n.arc(t.xCenter,t.yCenter,e,0,yt);else{let i=t.getPointPosition(0,e);n.moveTo(i.x,i.y);for(let o=1;o{const i=J(this.options.pointLabels.callback,[t,e],this);return i||0===i?i:""})).filter(((t,e)=>this.chart.getDataVisibility(e)))}fit(){const t=this.options;t.display&&t.pointLabels.display?ia(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,s){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,s))}getIndexAngle(t){return Nt(t*(yt/(this._pointLabels.length||1))+It(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if($(t))return NaN;const e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if($(t))return NaN;const e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){const e=this._pointLabels||[];if(t>=0&&t=0;n--){const e=s.setContext(t.getPointLabelContext(n)),o=He(e.font),{x:a,y:r,textAlign:l,left:h,top:c,right:d,bottom:u}=t._pointLabelItems[n],{backdropColor:f}=e;if(!$(f)){const t=Ne(e.backdropPadding);i.fillStyle=f,i.fillRect(h-t.left,c-t.top,d-h+t.width,u-c+t.height)}se(i,t._pointLabels[n],a,r+o.lineHeight/2,o,{color:e.color,textAlign:l,textBaseline:"middle"})}}(this,n),s.display&&this.ticks.forEach(((t,e)=>{if(0!==e){a=this.getDistanceFromCenterForValue(t.value);!function(t,e,i,s){const n=t.ctx,o=e.circular,{color:a,lineWidth:r}=e;!o&&!s||!a||!r||i<0||(n.save(),n.strokeStyle=a,n.lineWidth=r,n.setLineDash(e.borderDash),n.lineDashOffset=e.borderDashOffset,n.beginPath(),ra(t,i,o,s),n.closePath(),n.stroke(),n.restore())}(this,s.setContext(this.getContext(e-1)),a,n)}})),i.display){for(t.save(),o=n-1;o>=0;o--){const s=i.setContext(this.getPointLabelContext(o)),{color:n,lineWidth:l}=s;l&&n&&(t.lineWidth=l,t.strokeStyle=n,t.setLineDash(s.borderDash),t.lineDashOffset=s.borderDashOffset,a=this.getDistanceFromCenterForValue(e.ticks.reverse?this.min:this.max),r=this.getPointPosition(o,a),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(r.x,r.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;const s=this.getIndexAngle(0);let n,o;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(s),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach(((s,a)=>{if(0===a&&!e.reverse)return;const r=i.setContext(this.getContext(a)),l=He(r.font);if(n=this.getDistanceFromCenterForValue(this.ticks[a].value),r.showLabelBackdrop){t.font=l.string,o=t.measureText(s.label).width,t.fillStyle=r.backdropColor;const e=Ne(r.backdropPadding);t.fillRect(-o/2-e.left,-n-l.size/2-e.top,o+e.width,l.size+e.height)}se(t,s.label,0,-n,l,{color:r.color})})),t.restore()}drawTitle(){}}la.id="radialLinear",la.defaults={display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:Os.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback:t=>t,padding:5,centerPointLabels:!1}},la.defaultRoutes={"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"},la.descriptors={angleLines:{_fallback:"grid"}};const ha={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},ca=Object.keys(ha);function da(t,e){return t-e}function ua(t,e){if($(e))return null;const i=t._adapter,{parser:s,round:n,isoWeekday:o}=t._parseOpts;let a=e;return"function"==typeof s&&(a=s(a)),X(a)||(a="string"==typeof s?i.parse(a,s):i.parse(a)),null===a?null:(n&&(a="week"!==n||!Tt(o)&&!0!==o?i.startOf(a,n):i.startOf(a,"isoWeek",o)),+a)}function fa(t,e,i,s){const n=ca.length;for(let o=ca.indexOf(t);o=e?i[s]:i[n]]=!0}}else t[e]=!0}function pa(t,e,i){const s=[],n={},o=e.length;let a,r;for(a=0;a=0&&(e[l].major=!0);return e}(t,s,n,i):s}class ma extends Bs{constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e){const i=t.time||(t.time={}),s=this._adapter=new mn._date(t.adapters.date);ot(i.displayFormats,s.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return void 0===t?null:ua(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,e=this._adapter,i=t.time.unit||"day";let{min:s,max:n,minDefined:o,maxDefined:a}=this.getUserBounds();function r(t){o||isNaN(t.min)||(s=Math.min(s,t.min)),a||isNaN(t.max)||(n=Math.max(n,t.max))}o&&a||(r(this._getLabelBounds()),"ticks"===t.bounds&&"labels"===t.ticks.source||r(this.getMinMax(!1))),s=X(s)&&!isNaN(s)?s:+e.startOf(Date.now(),i),n=X(n)&&!isNaN(n)?n:+e.endOf(Date.now(),i)+1,this.min=Math.min(s,n-1),this.max=Math.max(s+1,n)}_getLabelBounds(){const t=this.getLabelTimestamps();let e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){const t=this.options,e=t.time,i=t.ticks,s="labels"===i.source?this.getLabelTimestamps():this._generate();"ticks"===t.bounds&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const n=this.min,o=he(s,n,this.max);return this._unit=e.unit||(i.autoSkip?fa(e.minUnit,this.min,this.max,this._getLabelCapacity(n)):function(t,e,i,s,n){for(let o=ca.length-1;o>=ca.indexOf(i);o--){const i=ca[o];if(ha[i].common&&t._adapter.diff(n,s,i)>=e-1)return i}return ca[i?ca.indexOf(i):0]}(this,o.length,e.minUnit,this.min,this.max)),this._majorUnit=i.major.enabled&&"year"!==this._unit?function(t){for(let e=ca.indexOf(t)+1,i=ca.length;e1e5*a)throw new Error(e+" and "+i+" are too far apart with stepSize of "+a+" "+o);const f="data"===s.ticks.source&&this.getDataTimestamps();for(c=u,d=0;ct-e)).map((t=>+t))}getLabelForValue(t){const e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}_tickFormatFunction(t,e,i,s){const n=this.options,o=n.time.displayFormats,a=this._unit,r=this._majorUnit,l=a&&o[a],h=r&&o[r],c=i[e],d=r&&h&&c&&c.major,u=this._adapter.format(t,s||(d?h:l)),f=n.ticks.callback;return f?J(f,[u,e,i],this):u}generateTickLabels(t){let e,i,s;for(e=0,i=t.length;e0?a:1}getDataTimestamps(){let t,e,i=this._cache.data||[];if(i.length)return i;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(t=0,e=s.length;t=t[r].pos&&e<=t[l].pos&&({lo:r,hi:l}=re(t,"pos",e)),({pos:s,time:o}=t[r]),({pos:n,time:a}=t[l])):(e>=t[r].time&&e<=t[l].time&&({lo:r,hi:l}=re(t,"time",e)),({time:s,pos:o}=t[r]),({time:n,pos:a}=t[l]));const h=n-s;return h?o+(a-o)*(e-s)/h:o}ma.id="time",ma.defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",major:{enabled:!1}}};class ba extends ma{constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=xa(e,this.min),this._tableRange=xa(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:i}=this,s=[],n=[];let o,a,r,l,h;for(o=0,a=t.length;o=e&&l<=i&&s.push(l);if(s.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(o=0,a=s.length;o{let t=0;return()=>t++})();function P(t){return null==t}function O(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function A(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function p(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function g(t,e){return p(t)?t:e}function T(t,e){return void 0===t?e:t}const V=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,B=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function k(t,e,i,s){let a,n,o;if(O(t))if(n=t.length,s)for(a=n-1;0<=a;a--)e.call(i,t[a],a);else for(a=0;at,x:t=>t.x,y:t=>t.y};function q(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s=s.endsWith("\\")?s.slice(0,-1)+".":(i.push(s),"");return i}function m(t,e){const i=X[e]||(X[e]=function(){const i=q(e);return t=>{for(const e of i){if(""===e)break;t=t&&t[e]}return t}}());return i(t)}function K(t){return t.charAt(0).toUpperCase()+t.slice(1)}const G=t=>void 0!==t,u=t=>"function"==typeof t,Z=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function J(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const S=Math.PI,_=2*S,Q=_+S,tt=Number.POSITIVE_INFINITY,et=S/180,D=S/2,it=S/4,st=2*S/3,r=Math.log10,y=Math.sign;function at(t,e,i){return Math.abs(t-e)t-e).pop(),e}function rt(t){return!isNaN(parseFloat(t))&&isFinite(t)}function lt(t,e){var i=Math.round(t);return i-e<=t&&t<=i+e}function ht(t,e,i){let s,a,n;for(s=0,a=t.length;s=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function bt(e,i,t){t=t||(t=>e[t]>1)?n=s:a=s;return{lo:n,hi:a}}const f=(i,s,a,t)=>bt(i,a,t?t=>{var e=i[t][s];return ei[t][s]bt(e,s,t=>e[t][i]>=s);function vt(t,e,i){let s=0,a=t.length;for(;ss&&t[a-1]>i;)a--;return 0{const i="_onData"+K(t),s=a[t];Object.defineProperty(a,t,{configurable:!0,enumerable:!1,value(...e){var t=s.apply(this,e);return a._chartjs.listeners.forEach(t=>{"function"==typeof t[i]&&t[i](...e)}),t}})}))}function Mt(e,t){var i=e._chartjs;if(i){const s=i.listeners,a=s.indexOf(t);-1!==a&&s.splice(a,1),0{delete e[t]}),delete e._chartjs)}}function wt(t){var e=new Set(t);return e.size===t.length?t:Array.from(e)}const kt="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function St(e,i){let s,a=!1;return function(...t){s=t,a||(a=!0,kt.call(window,()=>{a=!1,e.apply(i,s)}))}}function Pt(e,i){let s;return function(...t){return i?(clearTimeout(s),s=setTimeout(e,i,t)):e.apply(this,t),i}}const Dt=t=>"start"===t?"left":"end"===t?"right":"center",E=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2,Ct=(t,e,i,s)=>t===(s?"left":"right")?i:"center"===t?(e+i)/2:e;function Ot(t,e,i){var s=e.length;let a=0,n=s;if(t._sorted){const{iScale:o,_parsed:r}=t,l=o.axis,{min:h,max:c,minDefined:d,maxDefined:u}=o.getUserBounds();d&&(a=C(Math.min(f(r,l,h).lo,i?s:f(e,l,o.getPixelForValue(h)).lo),0,s-1)),n=u?C(Math.max(f(r,o.axis,c,!0).hi+1,i?0:f(e,l,o.getPixelForValue(c),!0).hi+1),a,s)-a:s-a}return{start:a,count:n}}function At(t){var{xScale:e,yScale:i,_scaleRanges:s}=t,a={xmin:e.min,xmax:e.max,ymin:i.min,ymax:i.max};if(!s)return t._scaleRanges=a,!0;t=s.xmin!==e.min||s.xmax!==e.max||s.ymin!==i.min||s.ymax!==i.max;return Object.assign(s,a),t}var l=new class{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(e,i,s,t){const a=i.listeners[t],n=i.duration;a.forEach(t=>t({chart:e,initial:i.initial,numSteps:n,currentStep:Math.min(s-i.start,n)}))}_refresh(){this._request||(this._running=!0,this._request=kt.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(o=Date.now()){let r=0;this._charts.forEach((s,a)=>{if(s.running&&s.items.length){const n=s.items;let t,e=n.length-1,i=!1;for(;0<=e;--e)(t=n[e])._active?(t._total>s.duration&&(s.duration=t._total),t.tick(o),i=!0):(n[e]=n[n.length-1],n.pop());i&&(a.draw(),this._notify(a,s,o,"progress")),n.length||(s.running=!1,this._notify(a,s,o,"complete"),s.initial=!1),r+=n.length}}),this._lastDate=o,0===r&&(this._running=!1)}_getAnims(t){const e=this._charts;let i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return 0Math.max(t,e._duration),0),this._refresh())}running(t){if(!this._running)return!1;t=this._charts.get(t);return!!(t&&t.running&&t.items.length)}stop(e){const i=this._charts.get(e);if(i&&i.items.length){const s=i.items;let t=s.length-1;for(;0<=t;--t)s[t].cancel();i.items=[],this._notify(e,i,Date.now(),"complete")}}remove(t){return this._charts.delete(t)}};function Tt(t){return t+.5|0}const Lt=(t,e,i)=>Math.max(Math.min(t,i),e);function Et(t){return Lt(Tt(2.55*t),0,255)}function Rt(t){return Lt(Tt(255*t),0,255)}function o(t){return Lt(Tt(t/2.55)/100,0,1)}function It(t){return Lt(Tt(100*t),0,100)}const n={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},zt=[..."0123456789ABCDEF"],Ft=t=>zt[15&t],Vt=t=>zt[(240&t)>>4]+zt[15&t],Bt=t=>(240&t)>>4==(15&t);const Wt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Nt(i,t,s){const a=t*Math.min(s,1-s),e=(t,e=(t+i/30)%12)=>s-a*Math.max(Math.min(e-3,9-e,1),-1);return[e(0),e(8),e(4)]}function Ht(i,s,a){i=(t,e=(t+i/60)%6)=>a-a*s*Math.max(Math.min(e,4-e,1),0);return[i(5),i(3),i(1)]}function jt(t,e,i){const s=Nt(t,1,.5);let a;for(1t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Qt=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function te(e,i,s){if(e){let t=Yt(e);t[i]=Math.max(0,Math.min(t[i]+t[i]*s,0===i?360:1)),t=Ut(t),e.r=t[0],e.g=t[1],e.b=t[2]}}function ee(t,e){return t&&Object.assign(e||{},t)}function ie(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?3<=t.length&&(e={r:t[0],g:t[1],b:t[2],a:255},3>16&255,n>>8&255,255&n]}return t}()).transparent=[0,0,0,0]),(i=Gt[i.toLowerCase()])&&{r:i[0],g:i[1],b:i[2],a:4===i.length?i[3]:255})||se(t)),this._rgb=a,this._valid=!!a}get valid(){return this._valid}get rgb(){var t=ee(this._rgb);return t&&(t.a=o(t.a)),t}set rgb(t){this._rgb=ie(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${o(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):void 0;var t}hexString(){return this._valid?(t=this._rgb,e=t,e=Bt(e.r)&&Bt(e.g)&&Bt(e.b)&&Bt(e.a)?Ft:Vt,t?"#"+e(t.r)+e(t.g)+e(t.b)+((t=t.a)<255?e(t):""):void 0):void 0;var t,e}hslString(){if(this._valid){var t,e,i,s=this._rgb;if(s)return i=Yt(s),t=i[0],e=It(i[1]),i=It(i[2]),s.a<255?`hsla(${t}, ${e}%, ${i}%, ${o(s.a)})`:`hsl(${t}, ${e}%, ${i}%)`}}mix(t,e){if(t){const s=this.rgb,a=t.rgb;var t=void 0===e?.5:e,e=2*t-1,i=s.a-a.a,e=(1+(e*i==-1?e:(e+i)/(1+e*i)))/2,i=1-e;s.r=255&e*s.r+i*a.r+.5,s.g=255&e*s.g+i*a.g+.5,s.b=255&e*s.b+i*a.b+.5,s.a=t*s.a+(1-t)*a.a,this.rgb=s}return this}interpolate(t,e){return t&&(this._rgb=(i=this._rgb,t=t._rgb,e=e,s=Qt(o(i.r)),a=Qt(o(i.g)),n=Qt(o(i.b)),{r:Rt(Jt(s+e*(Qt(o(t.r))-s))),g:Rt(Jt(a+e*(Qt(o(t.g))-a))),b:Rt(Jt(n+e*(Qt(o(t.b))-n))),a:i.a+e*(t.a-i.a)})),this;var i,s,a,n}clone(){return new ae(this.rgb)}alpha(t){return this._rgb.a=Rt(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=Tt(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return te(this._rgb,2,t),this}darken(t){return te(this._rgb,2,-t),this}saturate(t){return te(this._rgb,1,t),this}desaturate(t){return te(this._rgb,1,-t),this}rotate(t){return e=this._rgb,t=t,(i=Yt(e))[0]=Xt(i[0]+t),i=Ut(i),e.r=i[0],e.g=i[1],e.b=i[2],this;var e,i}}function ne(t){return!(!t||"object"!=typeof t)&&("[object CanvasPattern]"===(t=t.toString())||"[object CanvasGradient]"===t)}function oe(t){return ne(t)?t:new ae(t)}function re(t){return ne(t)?t:new ae(t).saturate(.5).darken(.1).hexString()}const le=["x","y","borderWidth","radius","tension"],he=["color","borderColor","backgroundColor"],ce=new Map;function de(t,e,a){return function(t,e){e=a||{};var i=t+JSON.stringify(e);let s=ce.get(i);return s||(s=new Intl.NumberFormat(t,e),ce.set(i,s)),s}(e).format(t)}const ue={values:t=>O(t)?t:""+t,numeric(t,e,i){if(0===t)return"0";var s=this.chart.options.locale;let a,n=t;if(1.8*i.length?ue.numeric.call(this,t,e,i):""}};var ge={formatters:ue};const fe=Object.create(null),pe=Object.create(null);function me(i,t){if(!t)return i;var s=t.split(".");for(let t=0,e=s.length;tt.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>re(e.backgroundColor),this.hoverBorderColor=(t,e)=>re(e.borderColor),this.hoverColor=(t,e)=>re(e.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return be(this,t,e)}get(t){return me(this,t)}describe(t,e){return be(pe,t,e)}override(t,e){return be(fe,t,e)}route(t,e,i,s){const a=me(this,t),n=me(this,i),o="_"+e;Object.defineProperties(a,{[o]:{value:a[e],writable:!0},[e]:{enumerable:!0,get(){var t=this[o],e=n[s];return A(t)?Object.assign({},e,t):T(t,e)},set(t){this[o]=t}}})}apply(t){t.forEach(t=>t(this))}}({_scriptable:t=>!t.startsWith("on"),_indexable:t=>"events"!==t,hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[function(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>"onProgress"!==t&&"onComplete"!==t&&"fn"!==t}),t.set("animations",{colors:{type:"color",properties:he},numbers:{type:"number",properties:le}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>0|t}}}})},function(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})},function(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:ge.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&"callback"!==t&&"parser"!==t,_indexable:t=>"borderDash"!==t&&"tickBorderDash"!==t&&"dash"!==t}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:t=>"backdropPadding"!==t&&"callback"!==t,_indexable:t=>"backdropPadding"!==t})}]);function xe(){return"undefined"!=typeof window&&"undefined"!=typeof document}function ve(t){let e=t.parentNode;return e=e&&"[object ShadowRoot]"===e.toString()?e.host:e}function _e(t,e,i){let s;return"string"==typeof t?(s=parseInt(t,10),-1!==t.indexOf("%")&&(s=s/100*e.parentNode[i])):s=t,s}const ye=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function Me(t,e){return ye(t).getPropertyValue(e)}const we=["top","right","bottom","left"];function ke(e,i,s){const a={};s=s?"-"+s:"";for(let t=0;t<4;t++){var n=we[t];a[n]=parseFloat(e[i+"-"+n+s])||0}return a.width=a.left+a.right,a.height=a.top+a.bottom,a}function Se(t,e){if("native"in t)return t;var{canvas:i,currentDevicePixelRatio:s}=e,a=ye(i),n="border-box"===a.boxSizing,o=ke(a,"padding"),a=ke(a,"border","width"),{x:t,y:r,box:l}=function(t,e){var i,s=t.touches,s=s&&s.length?s[0]:t,{offsetX:a,offsetY:n}=s;let o,r,l=!1;if(i=n,t=t.target,!(0Math.round(10*t)/10;function De(t,e,i,s){var a=ye(t),n=ke(a,"margin"),o=_e(a.maxWidth,t,"clientWidth")||tt,r=_e(a.maxHeight,t,"clientHeight")||tt,t=function(t,e,i){let s,a;if(void 0===e||void 0===i){const n=ve(t);if(n){const t=n.getBoundingClientRect(),o=ye(n),r=ke(o,"border","width"),l=ke(o,"padding");e=t.width-l.width-r.width,i=t.height-l.height-r.height,s=_e(o.maxWidth,n,"clientWidth"),a=_e(o.maxHeight,n,"clientHeight")}else e=t.clientWidth,i=t.clientHeight}return{width:e,height:i,maxWidth:s||tt,maxHeight:a||tt}}(t,e,i);let{width:l,height:h}=t;if("content-box"===a.boxSizing){const t=ke(a,"border","width"),e=ke(a,"padding");l-=e.width+t.width,h-=e.height+t.height}return l=Math.max(0,l-n.width),h=Math.max(0,s?l/s:h-n.height),l=Pe(Math.min(l,o,t.maxWidth)),h=Pe(Math.min(h,r,t.maxHeight)),l&&!h&&(h=Pe(l/2)),(void 0!==e||void 0!==i)&&s&&t.height&&h>t.height&&(h=t.height,l=Pe(Math.floor(h*s))),{width:l,height:h}}function Ce(t,e,i){var e=e||1,s=Math.floor(t.height*e),a=Math.floor(t.width*e);t.height=Math.floor(t.height),t.width=Math.floor(t.width);const n=t.canvas;return n.style&&(i||!n.style.height&&!n.style.width)&&(n.style.height=t.height+"px",n.style.width=t.width+"px"),(t.currentDevicePixelRatio!==e||n.height!==s||n.width!==a)&&(t.currentDevicePixelRatio=e,n.height=s,n.width=a,t.ctx.setTransform(e,0,0,e,0,0),!0)}var Oe=function(){let t=!1;try{var e={get passive(){return!(t=!0)}};xe()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch(t){}return t}();function Ae(t,e){const i=Me(t,e),s=i&&i.match(/^(\d+)(\.\d+)?px$/);return s?+s[1]:void 0}function Te(t){return!t||P(t.size)||P(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function Le(t,e,i,s,a){let n=e[a];return n||(n=e[a]=t.measureText(a).width,i.push(a)),s=n>s?n:s}function Ee(t,e,i,s){let a=(s=s||{}).data=s.data||{},n=s.garbageCollect=s.garbageCollect||[],o=(s.font!==e&&(a=s.data={},n=s.garbageCollect=[],s.font=e),t.save(),t.font=e,0);var r=i.length;let l,h,c,d,u;for(l=0;li.length){for(l=0;le.left-i&&t.xe.top-i&&t.yr[0]){const i=t||r;void 0===e&&(e=ti("_fallback",r));t={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:r,_rootScopes:i,_fallback:e,_getTarget:a,override:t=>Ye([t,...r],l,i,e)};return new Proxy(t,{deleteProperty:(t,e)=>(delete t[e],delete t._keys,delete r[0][e],!0),get:(n,o)=>Ke(n,o,()=>{var t,e=o,i=r,s=n;for(const a of l)if(t=ti(Xe(a,e),i),void 0!==t)return qe(e,t)?Je(i,s,e,t):t}),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(r[0]),has:(t,e)=>ei(t).includes(e),ownKeys:t=>ei(t),set(t,e,i){const s=t._storage||(t._storage=a());return t[e]=s[e]=i,delete t._keys,!0}})}function $e(s,e,i,a){var t={_cacheable:!1,_proxy:s,_context:e,_subProxy:i,_stack:new Set,_descriptors:Ue(s,a),setContext:t=>$e(s,t,i,a),override:t=>$e(s.override(t),e,i,a)};return new Proxy(t,{deleteProperty:(t,e)=>(delete t[e],delete s[e],!0),get:(r,h,c)=>Ke(r,h,()=>{{var l=r,e=h,i=c;const{_proxy:s,_context:a,_subProxy:n,_descriptors:o}=l;let t=s[e];return O(t=u(t)&&o.isScriptable(e)?function(t,e,i){const{_proxy:s,_context:a,_subProxy:n,_stack:o}=l;if(o.has(t))throw new Error("Recursion detected: "+Array.from(o).join("->")+"->"+t);o.add(t);let r=e(a,n||i);return o.delete(t),r=qe(t,r)?Je(s._scopes,s,t,r):r}(e,t,i):t)&&t.length&&(t=function(t,e,i,s){const{_proxy:a,_context:n,_subProxy:o,_descriptors:r}=i;if(void 0!==n.index&&s(t))return e[n.index%e.length];if(A(e[0])){const i=e,s=a._scopes.filter(t=>t!==i);e=[];for(const A of i){const i=Je(s,a,t,A);e.push($e(i,n,o&&o[t],r))}}return e}(e,t,l,o.isIndexable)),t=qe(e,t)?$e(t,a,n&&n[e],o):t}}),getOwnPropertyDescriptor:(t,e)=>t._descriptors.allKeys?Reflect.has(s,e)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(s,e),getPrototypeOf:()=>Reflect.getPrototypeOf(s),has:(t,e)=>Reflect.has(s,e),ownKeys:()=>Reflect.ownKeys(s),set:(t,e,i)=>(s[e]=i,delete t[e],!0)})}function Ue(t,e={scriptable:!0,indexable:!0}){const{_scriptable:i=e.scriptable,_indexable:s=e.indexable,_allKeys:a=e.allKeys}=t;return{allKeys:a,scriptable:i,indexable:s,isScriptable:u(i)?i:()=>i,isIndexable:u(s)?s:()=>s}}const Xe=(t,e)=>t?t+K(e):e,qe=(t,e)=>A(e)&&"adapters"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function Ke(t,e,i){if(Object.prototype.hasOwnProperty.call(t,e))return t[e];i=i();return t[e]=i}function Ge(t,e,i){return u(t)?t(e,i):t}function Ze(t,e,i,s,a){for(const r of e){n=i,o=r;const e=!0===n?o:"string"==typeof n?m(o,n):void 0;if(e){t.add(e);o=Ge(e._fallback,i,a);if(void 0!==o&&o!==i&&o!==s)return o}else if(!1===e&&void 0!==s&&i!==s)return null}var n,o;return!1}function Je(t,s,a,n){const e=s._rootScopes,i=Ge(s._fallback,a,n),o=[...t,...e],r=new Set;r.add(n);t=Qe(r,o,a,i||a,n);return null!==t&&(void 0===i||i===a||null!==Qe(r,o,i,t,n))&&Ye(Array.from(r),[""],e,i,()=>{{var t=a,e=n;const i=s._getTarget();return t in i||(i[t]={}),O(t=i[t])&&A(e)?e:t||{}}})}function Qe(t,e,i,s,a){for(;i;)i=Ze(t,e,i,s,a);return i}function ti(t,e){for(const i of e)if(i){const e=i[t];if(void 0!==e)return e}}function ei(t){let e=t._keys;return e=e||(t._keys=function(t){const e=new Set;for(const i of t)for(const t of Object.keys(i).filter(t=>!t.startsWith("_")))e.add(t);return Array.from(e)}(t._scopes))}function ii(t,e,i,s){const a=t["iScale"],{key:n="r"}=this._parsing,o=new Array(s);let r,l,h,c;for(r=0,l=s;re"x"===t?"y":"x";function oi(t,e,i,s){var t=t.skip?e:t,a=e,e=i.skip?e:i,i=gt(a,t),n=gt(e,a);let o=i/(i+n),r=n/(i+n);o=isNaN(o)?0:o,r=isNaN(r)?0:r;i=s*o,n=s*r;return{previous:{x:a.x-i*(e.x-t.x),y:a.y-i*(e.y-t.y)},next:{x:a.x+n*(e.x-t.x),y:a.y+n*(e.y-t.y)}}}function ri(t,n="x"){const e=ni(n),i=t.length,r=Array(i).fill(0),l=Array(i);let s,a,o,h=ai(t,0);for(s=0;s!t.skip)),"monotone"===e.cubicInterpolationMode)ri(o,t);else{let t=i?o[o.length-1]:o[0];for(s=0,a=o.length;s0===t||1===t,di=(t,e,i)=>-Math.pow(2,10*--t)*Math.sin((t-e)*_/i),ui=(t,e,i)=>Math.pow(2,-10*t)*Math.sin((t-e)*_/i)+1,gi={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>--t*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-(--t*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>--t*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*D),easeOutSine:t=>Math.sin(t*D),easeInOutSine:t=>-.5*(Math.cos(S*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>ci(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>1<=t?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1- --t*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>ci(t)?t:di(t,.075,.3),easeOutElastic:t=>ci(t)?t:ui(t,.075,.3),easeInOutElastic(t){return ci(t)?t:t<.5?.5*di(2*t,.1125,.45):.5+.5*ui(2*t-1,.1125,.45)},easeInBack(t){return t*t*(2.70158*t-1.70158)},easeOutBack(t){return--t*t*(2.70158*t+1.70158)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-gi.easeOutBounce(1-t),easeOutBounce(t){var e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},easeInOutBounce:t=>t<.5?.5*gi.easeInBounce(2*t):.5*gi.easeOutBounce(2*t-1)+.5};function fi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:t.y+i*(e.y-t.y)}}function pi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:("middle"===s?i<.5?t:e:"after"===s?i<1?t:e:0+t||0;function yi(e,i){const t={},s=A(i),a=s?Object.keys(i):i,n=A(e)?s?t=>T(e[t],e[i[t]]):t=>e[t]:()=>e;for(const e of a)t[e]=_i(n(e));return t}function Mi(t){return yi(t,{top:"y",right:"x",bottom:"y",left:"x"})}function wi(t){return yi(t,["topLeft","topRight","bottomLeft","bottomRight"])}function I(t){const e=Mi(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function z(t,e){e=e||R.font;let i=T((t=t||{}).size,e.size),s=("string"==typeof i&&(i=parseInt(i,10)),T(t.style,e.style));s&&!(""+s).match(xi)&&(console.warn('Invalid font style specified: "'+s+'"'),s=void 0);const a={family:T(t.family,e.family),lineHeight:vi(T(t.lineHeight,e.lineHeight),i),size:i,style:s,weight:T(t.weight,e.weight),string:""};return a.string=Te(a),a}function ki(t,e,i,s){let a,n,o,r=!0;for(a=0,n=t.length;ai&&0===t?0:t+e;return{min:a(t,-Math.abs(e)),max:a(s,e)}}function Pi(t,e){return Object.assign(Object.create(t),e)}function Di(t,e,i){return t?(s=e,a=i,{x:t=>s+s+a-t,setWidth(t){a=t},textAlign:t=>"center"===t?t:"right"===t?"left":"right",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t};var s,a}function Ci(t,e){let i,s;"ltr"!==e&&"rtl"!==e||(s=[(i=t.canvas.style).getPropertyValue("direction"),i.getPropertyPriority("direction")],i.setProperty("direction",e,"important"),t.prevTextDirection=s)}function Oi(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Ai(t){return"angle"===t?{between:pt,compare:ft,normalize:v}:{between:c,compare:(t,e)=>t-e,normalize:t=>t}}function Ti({start:t,end:e,count:i,loop:s,style:a}){return{start:t%i,end:e%i,loop:s&&(e-t+1)%i==0,style:a}}function Li(t,i,g){if(!g)return[t];const{property:s,start:a,end:n}=g,o=i.length,{compare:r,between:l,normalize:h}=Ai(s),{start:c,end:d,loop:u,style:f}=function(t,e){const{property:i,start:s,end:a}=g,{between:n,normalize:o}=Ai(i),r=e.length;let l,h,{start:c,end:d,loop:u}=t;if(u){for(c+=r,d+=r,l=0,h=r;ls&&t[a%e].skip;)a--;return a%=e,{start:s,end:a}}(i,s,a);return Ii(t,!0===n?[{start:o,end:r,loop:a}]:function(t,e,i,s){const a=t.length,n=[];let o,r=e,l=t[e];for(o=e+1;o<=i;++o){const i=t[o%a];i.skip||i.stop?l.skip||(s=!1,n.push({start:e%a,end:(o-1)%a,loop:s}),e=r=i.stop?o:null):(r=o,l.skip&&(e=o)),l=i}return null!==r&&n.push({start:e%a,end:r%a,loop:s}),n}(i,o,r{t[r](s[a],n)&&(o.push({element:t,datasetIndex:e,index:i}),l=l||t.inRange(s.x,s.y,n))}),e&&!l?[]:o}var Hi={evaluateInteractionItems:Vi,modes:{index(t,e,i,s){const a=Se(e,t),n=i.axis||"x",o=i.includeInvisible||!1,r=i.intersect?Bi(t,a,n,s,o):Wi(t,a,n,!1,s,o),l=[];return r.length?(t.getSortedVisibleDatasetMetas().forEach(t=>{var e=r[0].index,i=t.data[e];i&&!i.skip&&l.push({element:i,datasetIndex:t.index,index:e})}),l):[]},dataset(t,e,i,s){var e=Se(e,t),a=i.axis||"xy",n=i.includeInvisible||!1;let o=i.intersect?Bi(t,e,a,s,n):Wi(t,e,a,!1,s,n);if(0Bi(t,Se(e,t),i.axis||"xy",s,i.includeInvisible||!1),nearest(t,e,i,s){var e=Se(e,t),a=i.axis||"xy",n=i.includeInvisible||!1;return Wi(t,e,a,i.intersect,s,n)},x:(t,e,i,s)=>Ni(t,Se(e,t),"x",i.intersect,s),y:(t,e,i,s)=>Ni(t,Se(e,t),"y",i.intersect,s)}};const ji=["left","top","right","bottom"];function Yi(t,e){return t.filter(t=>t.pos===e)}function $i(t,e){return t.filter(t=>-1===ji.indexOf(t.pos)&&t.box.axis===e)}function Ui(t,s){return t.sort((t,e)=>{var i=s?e:t,t=s?t:e;return i.weight===t.weight?i.index-t.index:i.weight-t.weight})}function Xi(t,e,i,s){return Math.max(t[i],e[i])+Math.max(t[s],e[s])}function qi(t,e){t.top=Math.max(t.top,e.top),t.left=Math.max(t.left,e.left),t.bottom=Math.max(t.bottom,e.bottom),t.right=Math.max(t.right,e.right)}function Ki(t,e,i,s){const a=[];let n,o,r,l,h,c;for(n=0,o=t.length,h=0;n{s[t]=Math.max(e[t],i[t])}),s}}(r.horizontal,e));const{same:o,other:d}=function(t,e,i,s){const{pos:a,box:n}=i,o=t.maxPadding;if(!A(a)){i.size&&(t[a]-=i.size);const e=s[i.stack]||{size:0,count:1};e.size=Math.max(e.size,i.horizontal?n.height:n.width),i.size=e.size/e.count,t[a]+=i.size}n.getPadding&&qi(o,n.getPadding());var s=Math.max(0,e.outerWidth-Xi(o,t,"left","right")),e=Math.max(0,e.outerHeight-Xi(o,t,"top","bottom")),r=s!==t.w,l=e!==t.h;return t.w=s,t.h=e,i.horizontal?{same:r,other:l}:{same:l,other:r}}(e,i,r,s);h|=o&&a.length,c=c||d,l.fullSize||a.push(r)}return h&&Ki(a,e,i,s)||c}function Gi(t,e,i,s,a){t.top=i,t.left=e,t.right=e+s,t.bottom=i+a,t.width=s,t.height=a}function Zi(t,e,i,s){var a=i.padding;let{x:n,y:o}=e;for(const r of t){const t=r.box,l=s[r.stack]||{count:1,placed:0,weight:1},h=r.stackWeight/l.weight||1;if(r.horizontal){const s=e.w*h,n=l.size||t.height;G(l.start)&&(o=l.start),t.fullSize?Gi(t,a.left,o,i.outerWidth-a.right-a.left,n):Gi(t,e.left+l.placed,o,s,n),l.start=o,l.placed+=s,o=t.bottom}else{const s=e.h*h,o=l.size||t.width;G(l.start)&&(n=l.start),t.fullSize?Gi(t,n,a.top,o,i.outerHeight-a.bottom-a.top):Gi(t,n,e.top+l.placed,o,s),l.start=n,l.placed+=s,n=t.right}}e.x=n,e.y=o}var a={addBox(t,e){t.boxes||(t.boxes=[]),e.fullSize=e.fullSize||!1,e.position=e.position||"top",e.weight=e.weight||0,e._layers=e._layers||function(){return[{z:0,draw(t){e.draw(t)}}]},t.boxes.push(e)},removeBox(t,e){e=t.boxes?t.boxes.indexOf(e):-1;-1!==e&&t.boxes.splice(e,1)},configure(t,e,i){e.fullSize=i.fullSize,e.position=i.position,e.weight=i.weight},update(l,t,e,i){if(l){const o=I(l.options.layout.padding),r=Math.max(t-o.width,0),h=Math.max(e-o.height,0),c=function(){const t=function(t){const e=[];let i,s,a,n,o,r;for(i=0,s=(t||[]).length;it.box.fullSize),!0),i=Ui(Yi(t,"left"),!0),s=Ui(Yi(t,"right")),a=Ui(Yi(t,"top"),!0),n=Ui(Yi(t,"bottom")),o=$i(t,"x"),r=$i(t,"y");return{fullSize:e,leftAndTop:i.concat(a),rightAndBottom:s.concat(r).concat(n).concat(o),chartArea:Yi(t,"chartArea"),vertical:i.concat(s).concat(r),horizontal:a.concat(n).concat(o)}}(),d=c.vertical,u=c.horizontal;k(l.boxes,t=>{"function"==typeof t.beforeLayout&&t.beforeLayout()});var s=d.reduce((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1,0)||1,t=Object.freeze({outerWidth:t,outerHeight:e,padding:o,availableWidth:r,availableHeight:h,vBoxMaxWidth:r/2/s,hBoxMaxHeight:h/2}),e=Object.assign({},o);qi(e,I(i));const g=Object.assign({maxPadding:e,w:r,h:h,x:o.left,y:o.top},o),f=function(t,e){var i=function(t){const e={};for(const i of t){const{stack:t,pos:s,stackWeight:a}=i;if(t&&ji.includes(s)){const n=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});n.count++,n.weight+=a}}return e}(t),{vBoxMaxWidth:s,hBoxMaxHeight:a}=e;let n,o,r;for(n=0,o=t.length;n{const e=t.box;Object.assign(e,l.chartArea),e.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})})}}};class Ji{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,s){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,s?Math.floor(e/s):i)}}isAttached(t){return!0}updateConfig(t){}}class Qi extends Ji{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const ts="$chartjs",es={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},is=t=>null===t||""===t,ss=!!Oe&&{passive:!0};function as(t,e){for(const i of t)if(i===e||i.contains(e))return!0}function ns(t,e,i){const s=t.canvas,a=new MutationObserver(t=>{let e=!1;for(const i of t)e=e||as(i.addedNodes,s),e=e&&!as(i.removedNodes,s);e&&i()});return a.observe(document,{childList:!0,subtree:!0}),a}function os(t,e,i){const s=t.canvas,a=new MutationObserver(t=>{let e=!1;for(const i of t)e=e||as(i.removedNodes,s),e=e&&!as(i.addedNodes,s);e&&i()});return a.observe(document,{childList:!0,subtree:!0}),a}const rs=new Map;let ls=0;function hs(){const i=window.devicePixelRatio;i!==ls&&(ls=i,rs.forEach((t,e)=>{e.currentDevicePixelRatio!==i&&t()}))}function cs(t,e,s){const i=t.canvas,a=i&&ve(i);if(a){const o=St((t,e)=>{var i=a.clientWidth;s(t,e),i{var t=t[0],e=t.contentRect.width,t=t.contentRect.height;0===e&&0===t||o(e,t)});return r.observe(a),t=t,n=o,rs.size||window.addEventListener("resize",hs),rs.set(t,n),r;var n}}function ds(t,e,i){i&&i.disconnect(),"resize"===e&&(i=t,rs.delete(i),rs.size||window.removeEventListener("resize",hs))}function us(e,t,i){var s=e.canvas,a=St(t=>{null!==e.ctx&&i(function(t,e){var i=es[t.type]||t.type,{x:s,y:a}=Se(t,e);return{type:i,chart:e,native:t,x:void 0!==s?s:null,y:void 0!==a?a:null}}(t,e))},e);return s.addEventListener(t,a,ss),a}class gs extends Ji{acquireContext(t,e){var i=t&&t.getContext&&t.getContext("2d");{if(i&&i.canvas===t){{var s=e;const a=t.style,n=t.getAttribute("height"),o=t.getAttribute("width");if(t[ts]={initial:{height:n,width:o,style:{display:a.display,height:a.height,width:a.width}}},a.display=a.display||"block",a.boxSizing=a.boxSizing||"border-box",is(o)){const s=Ae(t,"width");void 0!==s&&(t.width=s)}if(is(n))if(""===t.style.height)t.height=t.width/(s||2);else{const s=Ae(t,"height");void 0!==s&&(t.height=s)}}return i}return null}}releaseContext(t){const i=t.canvas;if(!i[ts])return!1;const s=i[ts].initial,e=(["height","width"].forEach(t=>{var e=s[t];P(e)?i.removeAttribute(t):i.setAttribute(t,e)}),s.style||{});return Object.keys(e).forEach(t=>{i.style[t]=e[t]}),i.width=i.width,delete i[ts],!0}addEventListener(t,e,i){this.removeEventListener(t,e);const s=t.$proxies||(t.$proxies={}),a={attach:ns,detach:os,resize:cs}[e]||us;s[e]=a(t,e,i)}removeEventListener(t,e){const i=t.$proxies||(t.$proxies={}),s=i[e];s&&(({attach:ds,detach:ds,resize:ds}[e]||function(t,e,i){t.canvas.removeEventListener(e,i,ss)})(t,e,s),i[e]=void 0)}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,s){return De(t,e,i,s)}isAttached(t){t=ve(t);return!(!t||!t.isConnected)}}function fs(t){return!xe()||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?Qi:gs}Oe=Object.freeze({__proto__:null,BasePlatform:Ji,BasicPlatform:Qi,DomPlatform:gs,_detectPlatform:fs});const ps="transparent",ms={boolean:(t,e,i)=>.5t+(e-t)*i};class bs{constructor(t,e,i,s){var a=e[i],a=(s=ki([t.to,s,a,t.from]),ki([t.from,a,s]));this._active=!0,this._fn=t.fn||ms[t.type||typeof a],this._easing=gi[t.easing]||gi.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=a,this._to=s,this._promises=void 0}active(){return this._active}update(t,e,i){var s,a,n;this._active&&(this._notify(!1),s=this._target[this._prop],a=i-this._start,n=this._duration-a,this._start=i,this._duration=Math.floor(Math.max(n,t.duration)),this._total+=a,this._loop=!!t.loop,this._to=ki([t.to,e,s,t.from]),this._from=ki([t.from,s,e]))}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){var t=t-this._start,e=this._duration,i=this._prop,s=this._from,a=this._loop,n=this._to;let o;if(this._active=s!==n&&(a||t{i.push({res:t,rej:e})})}_notify(t){const e=t?"res":"rej",i=this._promises||[];for(let t=0;t{const t=s[e];if(A(t)){const i={};for(const s of a)i[s]=t[s];(O(t.properties)&&t.properties||[e]).forEach(t=>{t!==e&&n.has(t)||n.set(t,i)})}})}}_animateOptions(t,e){const i=e.options,s=function(e,i){if(i){let t=e.options;if(t)return t.$shared&&(e.options=t=Object.assign({},t,{$shared:!1,$animations:{}})),t;e.options=i}}(t,i);if(!s)return[];e=this._createAnimations(s,i);return i.$shared&&function(e,t){const i=[],s=Object.keys(t);for(let t=0;t{t.options=i},()=>{}),e}_createAnimations(e,i){const s=this._properties,a=[],n=e.$animations||(e.$animations={}),t=Object.keys(i),o=Date.now();let r;for(r=t.length-1;0<=r;--r){const c=t[r];if("$"!==c.charAt(0))if("options"===c)a.push(...this._animateOptions(e,i));else{var l=i[c];let t=n[c];var h=s.get(c);if(t){if(h&&t.active()){t.update(h,l,o);continue}t.cancel()}h&&h.duration?(n[c]=t=new bs(h,e,c,l),a.push(t)):e[c]=l}}return a}update(t,e){{if(0!==this._properties.size)return(t=this._createAnimations(t,e)).length?(l.add(this._chart,t),!0):void 0;Object.assign(t,e)}}}function vs(t,e){var t=t&&t.options||{},i=t.reverse,s=void 0===t.min?e:0,t=void 0===t.max?e:0;return{start:i?t:s,end:i?s:t}}function _s(t,e){const i=[],s=t._getSortedDatasetMetas(e);let a,n;for(a=0,n=s.length;ai[t].axis===e).shift()}function Ps(t,e){var i=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const t of e){const e=t._stacks;if(!e||void 0===e[s]||void 0===e[s][i])return;delete e[s][i],void 0!==e[s]._visualValues&&void 0!==e[s]._visualValues[i]&&delete e[s]._visualValues[i]}}}const Ds=t=>"reset"===t||"none"===t,Cs=(t,e)=>e?t:Object.assign({},t);class Os{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=Ms(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Ps(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,i=this.getDataset(),s=(t,e,i,s)=>"x"===t?e:"r"===t?s:i,a=e.xAxisID=T(i.xAxisID,Ss(t,"x")),n=e.yAxisID=T(i.yAxisID,Ss(t,"y")),o=e.rAxisID=T(i.rAxisID,Ss(t,"r")),r=e.indexAxis,l=e.iAxisID=s(r,a,n,o),h=e.vAxisID=s(r,n,a,o);e.xScale=this.getScaleForId(a),e.yScale=this.getScaleForId(n),e.rScale=this.getScaleForId(o),e.iScale=this.getScaleForId(l),e.vScale=this.getScaleForId(h)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){var e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){var t=this._cachedMeta;this._data&&Mt(this._data,this),t._stacked&&Ps(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(A(e))this._data=function(t){const e=Object.keys(t),i=new Array(e.length);let s,a,n;for(s=0,a=e.length;snull===l[o]||d&&l[o]t||cthis.getContext(i,s,e),c);return g.$shared&&(g.$shared=r,a[n]=Object.freeze(Cs(g,r))),g}_resolveAnimations(t,e,i){const s=this.chart,a=this._cachedDataOpts,n="animation-"+e,o=a[n];if(o)return o;let r;if(!1!==s.options.animation){const s=this.chart.config,a=s.datasetAnimationScopeKeys(this._type,e),n=s.getOptionScopes(this.getDataset(),a);r=s.createResolver(n,this.getContext(t,i,e))}t=new xs(s,r&&r.animations);return r&&r._cacheable&&(a[n]=Object.freeze(t)),t}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||Ds(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){var t=this.resolveDataElementOptions(t,e),i=this._sharedOptions,s=this.getSharedOptions(t),i=this.includeOptions(e,s)||s!==i;return this.updateSharedOptions(s,e,t),{sharedOptions:s,includeOptions:i}}updateElement(t,e,i,s){Ds(s)?Object.assign(t,i):this._resolveAnimations(e,s).update(t,i)}updateSharedOptions(t,e,i){t&&!Ds(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,s){t.active=s;var a=this.getStyle(e,s);this._resolveAnimations(e,i,s).update(t,{options:!s&&this.getSharedOptions(a)||a})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){var t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){var t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const e=this._data,i=this._cachedMeta.data;for(const[t,e,i]of this._syncList)this[t](e,i);this._syncList=[];var s=i.length,a=e.length,n=Math.min(a,s);n&&this.parse(0,n),s{for(t.length+=e,o=t.length-1;o>=n;o--)t[o]=t[o-e]};for(r(a),o=t;o{s[t]=i[t]&&i[t].active()?i[t]._to:this[t]}),s}}function As(t,e,i,s,a){var n=T(s,0),o=Math.min(T(a,t.length),t.length);let r,l,h,c=0;for(i=Math.ceil(i),a&&(i=(r=a-s)/Math.floor(r/i)),h=n;h<0;)c++,h=Math.round(n+c*i);for(l=Math.max(n,0);l"top"===e||"left"===e?t[e]+i:t[e]-i,Ls=(t,e)=>Math.min(e||t,t);function Es(t,e){const i=[],s=t.length/e,a=t.length;let n=0;for(;nn?n:a,n=o&&a>n?a:n,{min:g(a,g(n,a)),max:g(n,g(a,n))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){var t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){d(this.options.beforeUpdate,[this])}update(t,e,i){var{beginAtZero:s,grace:a,ticks:n}=this.options,o=n.sampleSize,t=(this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Si(this,a,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks(),os)return i}return Math.max(s,1)}(n,s,a);if(0{const e=t.gc,i=e.length/2;let s;if(y({width:n[t]||0,height:o[t]||0});return{first:w(0),last:w(e-1),widest:w(i),highest:w(M),widths:n,heights:o}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){var e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);t=this._startPixel+t*this._length;return mt(this._alignToPixels?Re(this.chart,t,0):t)}getDecimalForPixel(t){t=(t-this._startPixel)/this._length;return this._reversePixels?1-t:t}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){var{min:t,max:e}=this;return t<0&&e<0?e:0o+1e-6)))return l}(this,b,l))&&(v=Re(s,x,A),h?_=M=k=P=v:y=w=S=D=v,u.push({tx1:_,ty1:y,tx2:M,ty2:w,x1:k,y1:S,x2:P,y2:D,width:A,color:o,borderDash:T,borderDashOffset:c,tickWidth:d,tickColor:g,tickBorderDash:f,tickBorderDashOffset:p}))}return this._ticksLength=c,this._borderValue=m,u}_computeLabelItems(s){const a=this.axis,n=this.options,{position:o,ticks:e}=n,r=this.isHorizontal(),l=this.ticks,{align:h,crossAlign:c,padding:t,mirror:d}=e,i=Rs(n.grid),u=i+t,g=d?-t:u,f=-L(this.labelRotation),p=[];let m,b,x,v,_,y,M,w,k,S,P,D="middle";if("top"===o)_=this.bottom-g,y=this._getXAxisLabelAlignment();else if("bottom"===o)_=this.top+g,y=this._getXAxisLabelAlignment();else if("left"===o){const s=this._getYAxisLabelAlignment(i);y=s.textAlign,v=s.x}else if("right"===o){const s=this._getYAxisLabelAlignment(i);y=s.textAlign,v=s.x}else if("x"===a){if("center"===o)_=(s.top+s.bottom)/2+u;else if(A(o)){const s=Object.keys(o)[0],a=o[s];_=this.chart.scales[s].getPixelForValue(a)+u}y=this._getXAxisLabelAlignment()}else if("y"===a){if("center"===o)v=(s.left+s.right)/2-u;else if(A(o)){const s=Object.keys(o)[0],a=o[s];v=this.chart.scales[s].getPixelForValue(a)}y=this._getYAxisLabelAlignment(i).textAlign}"y"===a&&("start"===h?D="top":"end"===h&&(D="bottom"));var C=this._getLabelSizes();for(m=0,b=l.length;mt.value===e);return 0<=i?t.setContext(this.getContext(i)).lineWidth:0}drawGrid(t){const e=this.options.grid,s=this.ctx,i=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let a,n;var o=(t,e,i)=>{i.width&&i.color&&(s.save(),s.lineWidth=i.width,s.strokeStyle=i.color,s.setLineDash(i.borderDash||[]),s.lineDashOffset=i.borderDashOffset,s.beginPath(),s.moveTo(t.x,t.y),s.lineTo(e.x,e.y),s.stroke(),s.restore())};if(e.display)for(a=0,n=i.length;a{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:t,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",s=[];let a,n;for(a=0,n=e.length;a{const e=t.split("."),i=e.pop(),s=[r].concat(e).join("."),a=l[t].split("."),n=a.pop(),o=a.join(".");R.route(s,i,o,n)})),e.descriptors&&R.describe(s,e.descriptors),this.override&&R.override(t.id,t.overrides)),h;throw new Error("class does not have id: "+t)}get(t){return this.items[t]}unregister(t){const e=this.items,i=t.id,s=this.scope;i in e&&delete e[i],s&&i in R[s]&&(delete R[s][i],this.override&&delete fe[i])}}var b=new class{constructor(){this.controllers=new Fs(Os,"datasets",!0),this.elements=new Fs(e,"elements"),this.plugins=new Fs(Object,"plugins"),this.scales=new Fs(zs,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(i,t,s){[...t].forEach(t=>{const e=s||this._getRegistryForType(t);s||e.isForType(t)||e===this.plugins&&t.id?this._exec(i,e,t):k(t,t=>{var e=s||this._getRegistryForType(t);this._exec(i,e,t)})})}_exec(t,e,i){var s=K(t);d(i["before"+s],[],i),e[t](i),d(i["after"+s],[],i)}_getRegistryForType(e){for(let t=0;tt.filter(e=>!i.some(t=>e.plugin.id===t.plugin.id));this._notify(s(e,i),t,"stop"),this._notify(s(i,e),t,"start")}}function Bs(t,e){var i=R.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||i.indexAxis||"x"}function Ws(t){if("x"===t||"y"===t||"r"===t)return t}function Ns(t,...e){if(Ws(t))return t;for(const s of e){const e=s.axis||("top"===(i=s.position)||"bottom"===i?"x":"left"===i||"right"===i?"y":void 0)||1{var e=r[t];if(!A(e))return console.error("Invalid scale configuration for scale: "+t);if(e._proxy)return console.warn("Ignoring resolver passed as options for scale: "+t);const i=Ns(t,e,function(e,t){if(t.data&&t.data.datasets){t=t.data.datasets.filter(t=>t.xAxisID===e||t.yAxisID===e);if(t.length)return Hs(e,"x",t[0])||Hs(e,"y",t[0])}return{}}(t,o),R.scales[e.type]),s=i===l?"_index_":"_value_",a=n.scales||{};h[t]=$(Object.create(null),[{axis:i},e,a[i],a[s]])}),o.data.datasets.forEach(s=>{const t=s.type||o.type,a=s.indexAxis||Bs(t,e),n=(fe[t]||{}).scales||{};Object.keys(n).forEach(t=>{var e=function(t,e){let i=t;return"_index_"===t?i=e:"_value_"===t&&(i="x"===e?"y":"x"),i}(t,a),i=s[e+"AxisID"]||e;h[i]=h[i]||Object.create(null),$(h[i],[{axis:e},r[i],n[t]])})}),Object.keys(h).forEach(t=>{t=h[t];$(t,[R.scales[t.type],R.scale])}),h}(t,e)}function Ys(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const $s=new Map,Us=new Set;function Xs(t,e){let i=$s.get(t);return i||(i=e(),$s.set(t,i),Us.add(i)),i}const qs=(t,e,i)=>{e=m(e,i);void 0!==e&&t.add(e)};class Ks{constructor(t){this._config=((t=(t=t)||{}).data=Ys(t.data),js(t),t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=Ys(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){var t=this._config;this.clearCache(),js(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return Xs(t,()=>[["datasets."+t,""]])}datasetAnimationScopeKeys(t,e){return Xs(t+".transition."+e,()=>[[`datasets.${t}.transitions.`+e,"transitions."+e],["datasets."+t,""]])}datasetElementScopeKeys(t,e){return Xs(t+"-"+e,()=>[[`datasets.${t}.elements.`+e,"datasets."+t,"elements."+e,""]])}pluginScopeKeys(t){const e=t.id;return Xs(this.type+"-plugin-"+e,()=>[["plugins."+e,...t.additionalOptionScopes||[]]])}_cachedScopes(t,e){const i=this._scopeCache;let s=i.get(t);return s&&!e||(s=new Map,i.set(t,s)),s}getOptionScopes(e,t,i){const{options:s,type:a}=this,n=this._cachedScopes(e,i),o=n.get(t);if(o)return o;const r=new Set,l=(t.forEach(t=>{e&&(r.add(e),t.forEach(t=>qs(r,e,t))),t.forEach(t=>qs(r,s,t)),t.forEach(t=>qs(r,fe[a]||{},t)),t.forEach(t=>qs(r,R,t)),t.forEach(t=>qs(r,pe,t))}),Array.from(r));return 0===l.length&&l.push(Object.create(null)),Us.has(t)&&n.set(t,l),l}chartOptionScopes(){var{options:t,type:e}=this;return[t,fe[e]||{},R.datasets[e]||{},{type:e},R,pe]}resolveNamedOptions(t,e,i,s=[""]){const a={$shared:!0},{resolver:n,subPrefixes:o}=Gs(this._resolverCache,t,s);let r=n;!function(t,e){const{isScriptable:i,isIndexable:s}=Ue(t);for(const a of e){const e=i(a),n=s(a),o=(n||e)&&t[a];if(e&&(u(o)||Zs(o))||n&&O(o))return 1}}(n,e)||(a.$shared=!1,r=$e(n,i=u(i)?i():i,this.createResolver(t,i,o)));for(const t of e)a[t]=r[t];return a}createResolver(t,e,i=[""],s){t=Gs(this._resolverCache,t,i).resolver;return A(e)?$e(t,e,void 0,s):t}}function Gs(t,e,i){let s=t.get(e);s||(s=new Map,t.set(e,s));t=i.join();let a=s.get(t);return a||(a={resolver:Ye(e,i),subPrefixes:i.filter(t=>!t.toLowerCase().includes("hover"))},s.set(t,a)),a}const Zs=e=>A(e)&&Object.getOwnPropertyNames(e).some(t=>u(e[t])),Js=["top","bottom","left","right","chartArea"];function Qs(t,e){return"top"===t||"bottom"===t||-1===Js.indexOf(t)&&"x"===e}function ta(i,s){return function(t,e){return t[i]===e[i]?t[s]-e[s]:t[i]-e[i]}}function ea(t){const e=t.chart,i=e.options.animation;e.notifyPlugins("afterRender"),d(i&&i.onComplete,[t],e)}function ia(t){var e=t.chart,i=e.options.animation;d(i&&i.onProgress,[t],e)}function sa(t){return xe()&&"string"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t=t&&t.canvas?t.canvas:t}const aa={},na=t=>{const e=sa(t);return Object.values(aa).filter(t=>t.canvas===e).pop()};function oa(t,e,i){return(t.options.clip?t:e)[i]}class i{static defaults=R;static instances=aa;static overrides=fe;static registry=b;static version="4.4.1";static getChart=na;static register(...t){b.add(...t),ra()}static unregister(...t){b.remove(...t),ra()}constructor(t,e){const i=this.config=new Ks(e),s=sa(t),a=na(s);if(a)throw new Error("Canvas is already in use. Chart with ID '"+a.id+"' must be destroyed before the canvas with ID '"+a.canvas.id+"' can be reused.");var e=i.createResolver(i.chartOptionScopes(),this.getContext()),t=(this.platform=new(i.platform||fs(s)),this.platform.updateConfig(i),this.platform.acquireContext(s,e.aspectRatio)),n=t&&t.canvas,o=n&&n.height,r=n&&n.width;this.id=F(),this.ctx=t,this.canvas=n,this.width=r,this.height=o,this._options=e,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new Vs,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=Pt(t=>this.update(t),e.resizeDelay||0),this._dataChanges=[],aa[this.id]=this,t&&n?(l.listen(this,"complete",ea),l.listen(this,"progress",ia),this._initialize(),this.attached&&this.update()):console.error("Failed to create chart: can't acquire context from the given item")}get aspectRatio(){var{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:s,_aspectRatio:a}=this;return P(t)?e&&a?a:s?i/s:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return b}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():Ce(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Ie(this.canvas,this.ctx),this}stop(){return l.stop(this),this}resize(t,e){l.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){var i=this.options,s=this.canvas,a=i.maintainAspectRatio&&this.aspectRatio,s=this.platform.getMaximumSize(s,t,e,a),t=i.devicePixelRatio||this.platform.getDevicePixelRatio(),e=this.width?"resize":"attach";this.width=s.width,this.height=s.height,this._aspectRatio=this.aspectRatio,Ce(this,t,!0)&&(this.notifyPlugins("resize",{size:s}),d(i.onResize,[this,s],this),this.attached&&this._doResize(e)&&this.render())}ensureScalesHaveIDs(){k(this.options.scales||{},(t,e)=>{t.id=e})}buildOrUpdateScales(){const o=this.options,s=o.scales,r=this.scales,l=Object.keys(r).reduce((t,e)=>(t[e]=!1,t),{});let t=[];k(t=s?t.concat(Object.keys(s).map(t=>{var e=s[t],t=Ns(t,e),i="r"===t,t="x"===t;return{options:e,dposition:i?"chartArea":t?"bottom":"left",dtype:i?"radialLinear":t?"category":"linear"}})):t,t=>{const e=t.options,i=e.id,s=Ns(i,e),a=T(e.type,t.dtype);void 0!==e.position&&Qs(e.position,s)===Qs(t.dposition)||(e.position=t.dposition),l[i]=!0;let n=null;i in r&&r[i].type===a?n=r[i]:(n=new(b.getScale(a))({id:i,type:a,ctx:this.ctx,chart:this}),r[n.id]=n),n.init(e,o)}),k(l,(t,e)=>{t||delete r[e]}),k(r,t=>{a.configure(this,t,t.options),a.addBox(this,t)})}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort((t,e)=>t.index-e.index),ei.length&&delete this._stacks,t.forEach((e,t)=>{0===i.filter(t=>t===e._dataset).length&&this._destroyDatasetMeta(t)})}buildOrUpdateControllers(){const e=[],i=this.data.datasets;let s,a;for(this._removeUnreferencedMetasets(),s=0,a=i.length;s{this.getDatasetMeta(e).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const s=this.config,a=(s.update(),this._options=s.createResolver(s.chartOptionScopes(),this.getContext())),n=this._animationsDisabled=!a.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1!==this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0})){const o=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let i=0;for(let t=0,e=this.data.datasets.length;t{t.reset()}),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(ta("z","_idx"));var{_active:t,_lastEvent:e}=this;e?this._eventHandler(e,!0):t.length&&this._updateHoverStyles(t,t,!0),this.render()}}_updateScales(){k(this.scales,t=>{a.removeBox(this,t)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){var t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);Z(e,i)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){var t,e,i,s,a=this["_hiddenIndices"];for({method:t,start:e,count:i}of this._getUniformDataChanges()||[]){n=void 0;o=void 0;r=void 0;s=void 0;var n=a;var o=e;var r="_removeElements"===t?-i:i;const l=Object.keys(n);for(const h of l){const l=+h;l>=o&&(s=n[h],delete n[h],(0o)&&(n[l+r]=s))}}}_getUniformDataChanges(){const t=this._dataChanges;if(t&&t.length){this._dataChanges=[];var e=this.data.datasets.length,i=e=>new Set(t.filter(t=>t[0]===e).map((t,e)=>e+","+t.splice(1).join(","))),s=i(0);for(let t=1;tt.split(",")).map(t=>({method:t[1],start:+t[2],count:+t[3]}))}}_updateLayout(t){if(!1!==this.notifyPlugins("beforeLayout",{cancelable:!0})){a.update(this,this.width,this.height,t);const e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],k(this.boxes,t=>{i&&"chartArea"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))},this),this._layers.forEach((t,e)=>{t._idx=e}),this.notifyPlugins("afterLayout")}}_updateDatasets(i){if(!1!==this.notifyPlugins("beforeDatasetsUpdate",{mode:i,cancelable:!0})){for(let t=0,e=this.data.datasets.length;tt&&t._dataset===e).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(s)),s}getContext(){return this.$context||(this.$context=Pi(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){var e=this.data.datasets[t];if(!e)return!1;t=this.getDatasetMeta(t);return"boolean"==typeof t.hidden?!t.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(e,t,i){const s=i?"show":"hide",a=this.getDatasetMeta(e),n=a.controller._resolveAnimations(void 0,s);G(t)?(a.data[t].hidden=!i,this.update()):(this.setDatasetVisibility(e,i),n.update(a,{visible:i}),this.update(t=>t.datasetIndex===e?s:void 0))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),l.remove(this),t=0,e=this.data.datasets.length;t{s.addEventListener(this,t,e),i[t]=e},a=(t,e,i)=>{t.offsetX=e,t.offsetY=i,this._eventHandler(t)};k(this.options.events,t=>e(t,a))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const i=this._responsiveListeners,s=this.platform,t=(t,e)=>{s.addEventListener(this,t,e),i[t]=e},e=(t,e)=>{i[t]&&(s.removeEventListener(this,t,e),delete i[t])},a=(t,e)=>{this.canvas&&this.resize(t,e)};let n;const o=()=>{e("attach",o),this.attached=!0,this.resize(),t("resize",a),t("detach",n)};n=()=>{this.attached=!1,e("resize",a),this._stop(),this._resize(0,0),t("attach",o)},(s.isAttached(this.canvas)?o:n)()}unbindEvents(){k(this._listeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._listeners={},k(this._responsiveListeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){var s=i?"set":"remove";let a,n,o,r;for("dataset"===e&&(a=this.getDatasetMeta(t[0].datasetIndex)).controller["_"+s+"DatasetHoverStyle"](),o=0,r=t.length;o{var i=this.getDatasetMeta(t);if(i)return{datasetIndex:t,element:i.data[e],index:e};throw new Error("No dataset found at index "+t)});W(t,e)||(this._active=t,this._lastEvent=null,this._updateHoverStyles(t,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(e){return 1===this._plugins._cache.filter(t=>t.plugin.id===e).length}_updateHoverStyles(t,e,i){var s=this.options.hover,a=(t,i)=>t.filter(e=>!i.some(t=>e.datasetIndex===t.datasetIndex&&e.index===t.index)),n=a(e,t),i=i?t:a(t,e);n.length&&this.updateHoverStyle(n,s.mode,!1),i.length&&s.mode&&this.updateHoverStyle(i,s.mode,!0)}_eventHandler(e,t){const i={event:e,replay:t,cancelable:!0,inChartArea:this.isPointInArea(e)},s=t=>(t.options.events||this.options.events).includes(e.native.type);if(!1!==this.notifyPlugins("beforeEvent",i,s))return t=this._handleEvent(e,t,i.inChartArea),i.cancelable=!1,this.notifyPlugins("afterEvent",i,s),(t||i.changed)&&this.render(),this}_handleEvent(t,e,i){const{_active:s=[],options:a}=this,n=e,o=this._getActiveElements(t,s,i,n),r=J(t),l=(h=t,c=this._lastEvent,i&&"mouseout"!==h.type?r?c:h:null);i&&(this._lastEvent=null,d(a.onHover,[t,o,this],this),r&&d(a.onClick,[t,o,this],this));var h,c=!W(o,s);return(c||e)&&(this._active=o,this._updateHoverStyles(o,s,e)),this._lastEvent=l,c}_getActiveElements(t,e,i,s){if("mouseout"===t.type)return[];if(!i)return e;i=this.options.hover;return this.getElementsAtEventForMode(t,i.mode,i,s)}}function ra(){k(i.instances,t=>t._plugins.invalidate())}function la(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}var ha={_date:class Xn{static override(t){Object.assign(Xn.prototype,t)}options;constructor(t){this.options=t||{}}init(){}formats(){return la()}parse(){return la()}format(){return la()}add(){return la()}diff(){return la()}startOf(){return la()}endOf(){return la()}}};function ca(i,s,a,n){if(O(i)){var o=i,r=s,l=a,h=n,c=l.parse(o[0],h),o=l.parse(o[1],h),h=Math.min(c,o),d=Math.max(c,o);let t=h,e=d;Math.abs(h)>Math.abs(d)&&(t=d,e=h),r[l.axis]=e,r._custom={barStart:t,barEnd:e,start:c,end:o,min:h,max:d}}else s[a.axis]=a.parse(i,n);return s}function da(t,e,i,s){const a=t.iScale,n=t.vScale,o=a.getLabels(),r=a===n,l=[];let h,c,d,u;for(c=(h=i)+s;h"spacing"!==t,_indexable:t=>"spacing"!==t&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(s){const t=s.data;if(t.labels.length&&t.datasets.length){const{pointStyle:a,color:n}=s.legend.options["labels"];return t.labels.map((t,e)=>{var i=s.getDatasetMeta(0).controller.getStyle(e);return{text:t,fillStyle:i.backgroundColor,strokeStyle:i.borderColor,fontColor:n,lineWidth:i.borderWidth,pointStyle:a,hidden:!s.getDataVisibility(e),index:e}})}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}};constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(s,a){const n=this.getDataset().data,o=this._cachedMeta;if(!1===this._parsing)o._parsed=n;else{let t,e,i=t=>+n[t];if(A(n[s])){const{key:s="value"}=this._parsing;i=t=>+m(n[t],s)}for(e=(t=s)+a;tpt(t,r,l,!0)?1:Math.max(e,e*s,i,i*s),f=(t,e,i)=>pt(t,r,l,!0)?-1:Math.min(e,e*s,i,i*s),p=g(0,h,d),m=g(D,c,u),b=f(S,h,d),x=f(S+D,c,u);i=(p-b)/2,a=(m-x)/2,n=-(p+b)/2,o=-(m+x)/2}return{ratioX:i,ratioY:a,offsetX:n,offsetY:o}}(c,h,r),p=(i.width-n)/d,m=(i.height-n)/u,b=Math.max(Math.min(p,m)/2,0),x=B(this.options.radius,b),v=(x-Math.max(x*r,0))/this._getVisibleDatasetWeightTotal();this.offsetX=g*x,this.offsetY=f*x,s.total=this.calculateTotal(),this.outerRadius=x-v*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-v*l,0),this.updateElements(a,0,a.length,t)}_circumference(t,e){var i=this.options,s=this._cachedMeta,a=this._getCircumference();return e&&i.animation.animateRotate||!this.chart.getDataVisibility(t)||null===s._parsed[t]||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*a/_)}updateElements(t,e,i,s){const a="reset"===s,n=this.chart,o=n.chartArea,r=n.options.animation,l=(o.left+o.right)/2,h=(o.top+o.bottom)/2,c=a&&r.animateScale,d=c?0:this.innerRadius,u=c?0:this.outerRadius,{sharedOptions:g,includeOptions:f}=this._getSharedOptions(e,s);let p,m=this._getRotation();for(p=0;p{var i=s.getDatasetMeta(0).controller.getStyle(e);return{text:t,fillStyle:i.backgroundColor,strokeStyle:i.borderColor,fontColor:n,lineWidth:i.borderWidth,pointStyle:a,hidden:!s.getDataVisibility(e),index:e}})}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){var e=this._cachedMeta,i=this.chart,s=i.data.labels||[],e=de(e._parsed[t].r,i.options.locale);return{label:s[t]||"",value:e}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){var e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){const t=this._cachedMeta,s={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach((t,e)=>{var i=this.getParsed(e).r;!isNaN(i)&&this.chart.getDataVisibility(e)&&(is.max&&(s.max=i))}),s}_updateRadius(){const t=this.chart,e=t.chartArea,i=t.options,s=Math.min(e.right-e.left,e.bottom-e.top),a=Math.max(s/2,0),n=(a-Math.max(i.cutoutPercentage?a/100*i.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=a-n*this.index,this.innerRadius=this.outerRadius-n}updateElements(s,a,t,n){const o="reset"===n,r=this.chart,l=r.options.animation,h=this._cachedMeta.rScale,c=h.xCenter,d=h.yCenter,u=h.getIndexAngle(0)-.5*S;let g,f=u;var p=360/this.countVisibleElements();for(g=0;g{!isNaN(this.getParsed(e).r)&&this.chart.getDataVisibility(e)&&i++}),i}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?L(this.resolveDataElementOptions(t,e).angle||i):0}}var ba=Object.freeze({__proto__:null,BarController:class extends Os{static id="bar";static defaults={datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}};static overrides={scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}};parsePrimitiveData(t,e,i,s){return da(t,e,i,s)}parseArrayData(t,e,i,s){return da(t,e,i,s)}parseObjectData(t,e,i,s){const{iScale:a,vScale:n}=t,{xAxisKey:o="x",yAxisKey:r="y"}=this._parsing,l="x"===a.axis?o:r,h="x"===n.axis?o:r,c=[];let d,u,g,f;for(u=(d=i)+s;dn.x,e="left","right"):(t=n.baset.controller.options.grouped),a=e.options.stacked,n=[];for(const e of s)if((void 0===i||!(t=>{var e=t.controller.getParsed(i),e=e&&e[t.vScale.axis];if(P(e)||isNaN(e))return!0})(e))&&((!1===a||-1===n.indexOf(e.stack)||void 0===a&&void 0===e.stack)&&n.push(e.stack),e.index===t))break;return n.length||n.push(void 0),n}_getStackCount(t){return this._getStacks(void 0,t).length}_getStackIndex(t,e,i){const s=this._getStacks(t,i),a=void 0!==e?s.indexOf(e):-1;return-1===a?s.length-1:a}_getRuler(){const t=this.options,e=this._cachedMeta,i=e.iScale,s=[];let a,n;for(a=0,n=e.data.length;at-e))}return s._cache.$bar}(e,t.type);let s,a,n,o,r=e._length;var l=()=>{32767!==n&&-32768!==n&&(G(o)&&(r=Math.min(r,Math.abs(n-o)||r)),o=n)};for(s=0,a=i.length;s=m?1:-1))*n),u===o&&(x-=d/2);const t=e.getPixelForDecimal(0),P=e.getPixelForDecimal(1),a=Math.min(t,P),l=Math.max(t,P);x=Math.max(Math.min(x,l),a),c=x+d,i&&!h&&(r._stacks[e.axis]._visualValues[s]=e.getValueForPixel(c)-e.getValueForPixel(x))}if(x===e.getPixelForValue(o)){const t=y(d)*e.getLineWidthForValue(o)/2;x+=t,d-=t}return{size:d,base:x,head:c,center:c+d/2}}_calculateBarIndexPixels(t,e){const i=e.scale,s=this.options,a=s.skipNull,n=T(s.maxBarThickness,1/0);let o,r;if(e.grouped){const i=a?this._getStackCount(t):e.stackCount,T=("flex"===s.barThickness?function(t,e,i,s){var a=e.pixels,n=a[t];let o=0=b?x.skip=!0:(y=P((_=this.getParsed(t))[u]),M=x[d]=n.getPixelForValue(_[d],t),w=x[u]=a||y?o.getBasePixel():o.getPixelForValue(r?this.applyStack(o,_,r):_[u],t),x.skip=isNaN(M)||isNaN(w)||y,x.stop=0p,f&&(x.parsed=_,x.raw=l.data[t]),c&&(x.options=h||this.resolveDataElementOptions(t,g.active?"active":s)),m||this.updateElement(g,t,x,s),v=_)}}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,s=t.data||[];if(!s.length)return i;var a=s[0].size(this.resolveDataElementOptions(0)),n=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(i,a,n)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}},PieController:class extends pa{static id="pie";static defaults={cutout:0,rotation:0,circumference:360,radius:"100%"}},PolarAreaController:ma,RadarController:class extends Os{static id="radar";static defaults={datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}};static overrides={aspectRatio:1,scales:{r:{type:"radialLinear"}}};getLabelAndValue(t){const e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta,i=e.dataset,s=e.data||[],a=e.iScale.getLabels();if(i.points=s,"resize"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);var n={_loop:!0,_fullLoop:a.length===s.length,options:e};this.updateElement(i,void 0,n,t)}this.updateElements(s,0,s.length,t)}updateElements(e,i,s,a){const n=this._cachedMeta.rScale,o="reset"===a;for(let t=i;tm,p&&(f.parsed=s,f.raw=h.data[t]),d&&(f.options=c||this.resolveDataElementOptions(t,i.active?"active":a)),b||this.updateElement(i,t,f,a),x=s}this.updateSharedOptions(c,a,t)}getMaxOverflow(){const t=this._cachedMeta,i=t.data||[];if(!this.options.showLine){let e=0;for(let t=i.length-1;0<=t;--t)e=Math.max(e,i[t].size(this.resolveDataElementOptions(t))/2);return 0{var e=(i-Math.min(a,t))*s/2;return C(t,0,Math.min(a,e))};return{outerStart:o(t.outerStart),outerEnd:o(t.outerEnd),innerStart:C(t.innerStart,0,n),innerEnd:C(t.innerEnd,0,n)}}(e,h,d,l-g),b=d-c,x=d-f,v=g+c/b,_=l-f/x,y=h+p,M=h+m,w=g+p/y,k=l-m/M;if(t.beginPath(),n){const e=(v+_)/2;if(t.arc(o,r,d,v,e),t.arc(o,r,d,e,_),0(o+(h?r-t:t))%n,v=()=>{g!==f&&(t.lineTo(m,f),t.lineTo(m,g),t.lineTo(m,p))};for(l&&(d=a[x(0)],t.moveTo(d.x,d.y)),c=0;c<=r;++c)if(!(d=a[x(c)]).skip){const e=d.x,i=d.y,s=0|e;s===u?(if&&(f=i),m=(b*m+e)/++b):(v(),t.lineTo(e,i),u=s,b=0,g=f=i),p=i}v()}function Sa(t){var e=t.options,i=e.borderDash&&e.borderDash.length;return t._decimated||t._loop||e.tension||"monotone"===e.cubicInterpolationMode||e.stepped||i?wa:ka}const Pa="function"==typeof Path2D;class Da extends e{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t&&"fill"!==t};constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){var i,s=this.options;!s.tension&&"monotone"!==s.cubicInterpolationMode||s.stepped||this._pointsUpdated||(i=s.spanGaps?this._loop:this._fullLoop,hi(this._points,s,t,i,e),this._pointsUpdated=!0)}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=Ri(this,this.options.segment))}first(){var t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){var t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(i,s){var a=this.options,n=i[s],o=this.points,r=Ei(this,{property:s,start:n,end:n});if(r.length){const l=[],h=a.stepped?pi:a.tension||"monotone"===a.cubicInterpolationMode?mi:fi;let e,t;for(e=0,t=r.length;e"borderDash"!==t};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;constructor(t){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,t&&Object.assign(this,t)}inRange(t,e,i){var{angle:t,distance:e}=ut(this.getProps(["x","y"],i),{x:t,y:e}),{startAngle:i,endAngle:s,innerRadius:a,outerRadius:n,circumference:o}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),r=(this.options.spacing+this.options.borderWidth)/2,o=T(o,s-i)>=_||pt(t,i,s),t=c(e,a+r,n+r);return o&&t}getCenterPoint(t){var{x:t,y:e,startAngle:i,endAngle:s,innerRadius:a,outerRadius:n}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],t),{offset:o,spacing:r}=this.options,i=(i+s)/2,s=(a+n+r+o)/2;return{x:t+Math.cos(i)*s,y:e+Math.sin(i)*s}}tooltipPosition(t){return this.getCenterPoint(t)}draw(e){var{options:i,circumference:s}=this,a=(i.offset||0)/4,n=(i.spacing||0)/2,o=i.circular;if(this.pixelMargin="inner"===i.borderAlign?.33:0,this.fullCircles=s>_?Math.floor(s/_):0,!(0===s||this.innerRadius<0||this.outerRadius<0)){e.save();var r=(this.startAngle+this.endAngle)/2,r=(e.translate(Math.cos(r)*a,Math.sin(r)*a),a*(1-Math.sin(Math.min(S,s||0))));e.fillStyle=i.backgroundColor,e.strokeStyle=i.borderColor;{var l=e;a=this;s=r;i=n;var h=o;var{fullCircles:c,startAngle:d,circumference:u}=a;let t=a.endAngle;if(c){va(l,a,s,i,t,h);for(let t=0;ts=e?s:t,r=t=>a=i?a:t;if(t){const t=y(s),e=y(a);t<0&&e<0?r(0):0g&&(k=nt(w*k/g/u)*u),P(r)||(_=Math.pow(10,r),k=Math.ceil(k*_)/_),M="ticks"===s?(y=Math.floor(f/k)*k,Math.ceil(p/k)*k):(y=f,p),m&&b&&a&<((o-n)/a,k/1e3)?(w=Math.round(Math.min((o-n)/k,h)),k=(o-n)/w,y=n,M=o):x?(y=m?n:y,M=b?o:M,w=l-1,k=(M-y)/w):w=at(w=(M-y)/k,Math.round(w),k/1e3)?Math.round(w):Math.ceil(w);e=Math.max(dt(k),dt(y));_=Math.pow(10,P(r)?e:r),y=Math.round(y*_)/_,M=Math.round(M*_)/_;let S=0;for(m&&(d&&y!==n?(i.push({value:n}),yo)break;i.push({value:t})}return b&&d&&M!==o?i.length&&at(i[i.length-1].value,o,za(o,v,t))?i[i.length-1].value=o:i.push({value:o}):b&&M!==o||i.push({value:M}),i}({maxTicks:Math.max(2,i),bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:!1!==e.includeBounds},this._range||this);return"ticks"===t.bounds&&ht(s,this,"value"),t.reverse?(s.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),s}configure(){var t=this.ticks;let e=this.min,i=this.max;super.configure(),this.options.offset&&t.length&&(t=(i-e)/Math.max(t.length-1,1)/2,e-=t,i+=t),this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return de(t,this.chart.options.locale,this.options.ticks.format)}}class Va extends Fa{static id="linear";static defaults={ticks:{callback:ge.formatters.numeric}};determineDataLimits(){var{min:t,max:e}=this.getMinMax(!0);this.min=p(t)?t:0,this.max=p(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){var t=this.isHorizontal(),e=t?this.width:this.height,i=L(this.options.ticks.minRotation),t=(t?Math.sin(i):Math.cos(i))||.001,i=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,i.lineHeight/t))}getPixelForValue(t){return null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}const Ba=t=>Math.floor(r(t)),Wa=(t,e)=>Math.pow(10,Ba(t)+e);function Na(t){return 1==t/Math.pow(10,Ba(t))}function Ha(t,e,i){i=Math.pow(10,i),t=Math.floor(t/i);return Math.ceil(e/i)-t}class ja extends zs{static id="logarithmic";static defaults={ticks:{callback:ge.formatters.logarithmic,major:{enabled:!0}}};constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){t=Fa.prototype.parse.apply(this,[t,e]);if(0!==t)return p(t)&&0s=e?s:t,n=t=>a=i?a:t;s===a&&(s<=0?(t(1),n(10)):(t(Wa(s,-1)),n(Wa(a,1)))),s<=0&&t(Wa(a,-1)),a<=0&&n(Wa(s,1)),this.min=s,this.max=a}buildTicks(){const t=this.options,e=function(t,{min:e,max:i}){e=g(t.min,e);const s=[],a=Ba(e);let n=function(t,e){let i=Ba(e-t);for(;10n?Math.pow(10,a):0,h=Math.round((e-l)*o)/o,c=Math.floor((e-l)/r/10)*r*10;let d=Math.floor((h-c)/Math.pow(10,n)),u=g(t.min,Math.round((l+c+d*Math.pow(10,n))*o)/o);for(;uf.r&&(t=(m.end-f.r)/x,g.r=Math.max(g.r,f.r+t)),b.startf.b&&(e=(b.end-f.b)/p,g.b=Math.max(g.b,f.b+e))}}var d,u;e.setCenterPoint(i.l-s.l,s.r-i.r,i.t-s.t,s.b-i.b),e._pointLabelItems=function(e,i,s){const a=[],n=e._pointLabels.length,t=e.options,{centerPointLabels:o,display:r}=t.pointLabels,l={extra:Ya(t)/2,additionalAngle:o?S/n:0};let h;for(let t=0;tt,padding:5,centerPointLabels:!1}};static defaultRoutes={"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"};static descriptors={angleLines:{_fallback:"grid"}};constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){var t=this._padding=I(Ya(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){var{min:t,max:e}=this.getMinMax(!1);this.min=p(t)&&!isNaN(t)?t:0,this.max=p(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/Ya(this.options))}generateTickLabels(t){Fa.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((t,e)=>{t=d(this.options.pointLabels.callback,[t,e],this);return t||0===t?t:""}).filter((t,e)=>this.chart.getDataVisibility(e))}fit(){var t=this.options;t.display&&t.pointLabels.display?Ua(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,s){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,s))}getIndexAngle(t){return v(t*(_/(this._pointLabels.length||1))+L(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if(P(t))return NaN;var e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(P(t))return NaN;t/=this.drawingArea/(this.max-this.min);return this.options.reverse?this.max-t:this.min+t}getPointLabelContext(t){var e=this._pointLabels||[];if(0<=t&&t0!==t)?(g.beginPath(),je(g,{x:f,y:r,w:x,h:m,radius:p}),g.fill()):g.fillRect(f,r,x,m)}var p=z(l.font),{x:v,y:b,textAlign:g}=o;He(_,n._pointLabels[t],v,b+p.lineHeight/2,p,{color:l.color,textAlign:g,textBaseline:"middle"})}}}if(h.display&&this.ticks.forEach((t,e)=>{if(0!==e){u=this.getDistanceFromCenterForValue(t.value);t=this.getContext(e),e=h.setContext(t),t=c.setContext(t);{var i=this,s=u,a=d;const n=i.ctx,o=e.circular,{color:r,lineWidth:l}=e;!o&&!a||!r||!l||s<0||(n.save(),n.strokeStyle=r,n.lineWidth=l,n.setLineDash(t.dash),n.lineDashOffset=t.dashOffset,n.beginPath(),Xa(i,s,o,a),n.closePath(),n.stroke(),n.restore())}}}),i.display){for(t.save(),s=d-1;0<=s;s--){const h=i.setContext(this.getPointLabelContext(s)),{color:c,lineWidth:d}=h;d&&c&&(t.lineWidth=d,t.strokeStyle=c,t.setLineDash(h.borderDash),t.lineDashOffset=h.borderDashOffset,u=this.getDistanceFromCenterForValue(e.ticks.reverse?this.min:this.max),a=this.getPointPosition(s,u),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(a.x,a.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const o=this.ctx,r=this.options,l=r.ticks;if(l.display){var t=this.getIndexAngle(0);let a,n;o.save(),o.translate(this.xCenter,this.yCenter),o.rotate(t),o.textAlign="center",o.textBaseline="middle",this.ticks.forEach((t,e)=>{if(0!==e||r.reverse){var i=l.setContext(this.getContext(e)),s=z(i.font);if(a=this.getDistanceFromCenterForValue(this.ticks[e].value),i.showLabelBackdrop){o.font=s.string,n=o.measureText(t.label).width,o.fillStyle=i.backdropColor;const r=I(i.backdropPadding);o.fillRect(-n/2-r.left,-a-s.size/2-r.top,n+r.width,s.size+r.height)}He(o,t.label,0,-a,s,{color:i.color,strokeColor:i.textStrokeColor,strokeWidth:i.textStrokeWidth})}}),o.restore()}}drawTitle(){}}const Ka={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},h=Object.keys(Ka);function Ga(t,e){return t-e}function Za(t,e){if(P(e))return null;const i=t._adapter,{parser:s,round:a,isoWeekday:n}=t._parseOpts;let o=e;return null===(o=p(o="function"==typeof s?s(o):o)?o:"string"==typeof s?i.parse(o,s):i.parse(o))?null:+(o=a?"week"!==a||!rt(n)&&!0!==n?i.startOf(o,a):i.startOf(o,"isoWeek",n):o)}function Ja(e,i,s,a){const n=h.length;for(let t=h.indexOf(e);t=e?i[s]:i[a]]=!0):t[e]=!0}function tn(i,t,s){const a=[],n={},e=t.length;let o,r;for(o=0;o=h.indexOf(s);t--){const s=h[t];if(Ka[s].common&&e._adapter.diff(n,a,s)>=i-1)return s}return h[s?h.indexOf(s):0]}(this,n.length,e.minUnit,this.min,this.max)),this._majorUnit=i.major.enabled&&"year"!==this._unit?function(i){for(let t=h.indexOf(i)+1,e=h.length;t+t.value))}initOffsets(t=[]){let e,i,s=0,a=0;this.options.offset&&t.length&&(e=this.getDecimalForValue(t[0]),s=1===t.length?1-e:(this.getDecimalForValue(t[1])-e)/2,i=this.getDecimalForValue(t[t.length-1]),a=1===t.length?i:(i-this.getDecimalForValue(t[t.length-2]))/2);t=t.length<3?.5:.25;s=C(s,0,t),a=C(a,0,t),this._offsets={start:s,end:a,factor:1/(s+1+a)}}_generate(){const t=this._adapter,e=this.min,i=this.max,s=this.options,a=s.time,n=a.unit||Ja(a.minUnit,e,i,this._getLabelCapacity(e)),o=T(s.ticks.stepSize,1),r="week"===n&&a.isoWeekday,l=rt(r)||!0===r,h={};let c,d,u=e;if(l&&(u=+t.startOf(u,"isoWeek",r)),u=+t.startOf(u,l?"day":n),t.diff(i,e,n)>1e5*o)throw new Error(e+" and "+i+" are too far apart with stepSize of "+o+" "+n);var g="data"===s.ticks.source&&this.getDataTimestamps();for(c=u,d=0;c+t)}getLabelForValue(t){const e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){var i=this.options.time.displayFormats,s=this._unit,e=e||i[s];return this._adapter.format(t,e)}_tickFormatFunction(t,e,i,s){var a=this.options,n=a.ticks.callback;if(n)return d(n,[t,e,i],this);var n=a.time.displayFormats,a=this._unit,o=this._majorUnit,a=a&&n[a],n=o&&n[o],i=i[e],e=o&&n&&i&&i.major;return this._adapter.format(t,s||(e?n:a))}generateTickLabels(t){let e,i,s;for(e=0,i=t.length;e=t[r].pos&&e<=t[l].pos&&({lo:r,hi:l}=f(t,"pos",e)),{pos:s,time:n}=t[r],{pos:a,time:o}=t[l]):(e>=t[r].time&&e<=t[l].time&&({lo:r,hi:l}=f(t,"time",e)),{time:s,pos:n}=t[r],{time:a,pos:o}=t[l]);i=a-s;return i?n+(o-n)*(e-s)/i:n}var an=Object.freeze({__proto__:null,CategoryScale:class extends zs{static id="category";static defaults={ticks:{callback:Ia}};constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){var e=this._addedLabels;if(e.length){const t=this.getLabels();for(var{index:i,label:s}of e)t[i]===s&&t.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(P(t))return null;var i,s,a,n,o,r,l=this.getLabels();return a=e=isFinite(e)&&l[e]===t?e:(i=l,s=T(e,t=t),a=this._addedLabels,-1===(r=i.indexOf(t))?(o=s,a=a,"string"==typeof(n=t)?(o=i.push(n)-1,a.unshift({index:o,label:n})):isNaN(n)&&(o=null),o):r!==i.lastIndexOf(t)?s:r),n=l.length-1,null===a?null:C(Math.round(a),0,n)}determineDataLimits(){var{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:i,max:s}=this.getMinMax(!0);"ticks"===this.options.bounds&&(t||(i=0),e||(s=this.getLabels().length-1)),this.min=i,this.max=s}buildTicks(){const e=this.min,i=this.max,t=this.options.offset,s=[];let a=this.getLabels();a=0===e&&i===a.length-1?a:a.slice(e,i+1),this._valueRange=Math.max(a.length-(t?0:1),1),this._startValue=this.min-(t?.5:0);for(let t=e;t<=i;t++)s.push({value:t});return s}getLabelForValue(t){return Ia.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return null===(t="number"!=typeof t?this.parse(t):t)?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){var e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}},LinearScale:Va,LogarithmicScale:ja,RadialLinearScale:qa,TimeScale:en,TimeSeriesScale:class extends en{static id="timeseries";static defaults=en.defaults;constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){var t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=sn(e,this.min),this._tableRange=sn(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:i}=this,s=[],a=[];let n,o,r,l,h;for(n=0,o=t.length;n=e&&l<=i&&s.push(l);if(s.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(n=0,o=s.length;nt-e)}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;const e=this.getDataTimestamps(),i=this.getLabelTimestamps();return t=e.length&&i.length?this.normalize(e.concat(i)):e.length?e:i,t=this._cache.all=t}getDecimalForValue(t){return(sn(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){var e=this._offsets,t=this.getDecimalForPixel(t)/e.factor-e.end;return sn(this._table,t*this._tableRange+this._minPos,!0)}}});const nn=["rgb(54, 162, 235)","rgb(255, 99, 132)","rgb(255, 159, 64)","rgb(255, 205, 86)","rgb(75, 192, 192)","rgb(153, 102, 255)","rgb(201, 203, 207)"],on=nn.map(t=>t.replace("rgb(","rgba(").replace(")",", 0.5)"));function rn(t){return nn[t%nn.length]}function ln(t){return on[t%on.length]}function hn(n){let o=0;return(t,e)=>{var i,s,a,e=n.getDatasetMeta(e).controller;e instanceof pa?o=(s=t,a=o,s.backgroundColor=s.data.map(()=>rn(a++)),a):e instanceof ma?o=(s=t,i=o,s.backgroundColor=s.data.map(()=>ln(i++)),i):e&&(o=(e=t,t=o,e.borderColor=rn(t),e.backgroundColor=ln(t),++t))}}function cn(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return 1}var dn={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,i){if(i.enabled){const{data:{datasets:s},options:a}=t.config,n=a["elements"];!i.forceOverride&&(cn(s)||a&&(a.borderColor||a.backgroundColor)||n&&cn(n))||(i=hn(t),s.forEach(i))}}};function un(t){var e;t._decimated&&(e=t._data,delete t._decimated,delete t._data,Object.defineProperty(t,"data",{configurable:!0,enumerable:!0,writable:!0,value:e}))}function gn(t){t.data.datasets.forEach(t=>{un(t)})}var fn={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(r,t,M)=>{if(M.enabled){const l=r.width;r.data.datasets.forEach((e,t)=>{var{_data:i,indexAxis:s}=e,h=r.getDatasetMeta(t),a=i||e.data;if("y"!==ki([s,r.options.indexAxis])&&h.controller.supportsDecimation){t=r.scales[h.xAxisID];if(("linear"===t.type||"time"===t.type)&&!r.options.parsing){var{start:n,count:o}=function(t){var e=t.length;let i,s=0;const a=h["iScale"],{min:n,max:o,minDefined:r,maxDefined:l}=a.getUserBounds();return r&&(s=C(f(t,a.axis,n).lo,0,e-1)),i=l?C(f(t,a.axis,o).hi+1,s,e)-s:e-s,{start:s,count:i}}(a);if(o<=(M.threshold||4*l))un(e);else{let t;switch(P(i)&&(e._data=a,delete e.data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),M.algorithm){case"lttb":t=function(s,a,n,t){var e=M.samples||t;if(n<=e)return s.slice(a,a+n);const o=[],r=(n-2)/(e-2);let l=0;const h=a+n-1;let c,d,u,g,f,p=a;for(o[l++]=s[p],c=0;cu&&(u=g,d=s[t],f=t);o[l++]=d,p=f}return o[l++]=s[h],o}(a,n,o,l);break;case"min-max":t=function(t,e,i,s){let a,n,o,r,l,h,c,d,u,g,f=0,p=0;const m=[],b=e+i-1,x=t[e].x,v=t[b].x-x;for(a=e;ag&&(g=r,c=a),f=(p*f+n.x)/++p;else{const i=a-1;if(!P(h)&&!P(c)){const e=Math.min(h,c),P=Math.max(h,c);e!==d&&e!==i&&m.push({...t[e],x:f}),P!==d&&P!==i&&m.push({...t[P],x:f})}0{e=mn(t,e,a);t=a[t],e=a[e];null!==s?(n.push({x:t.x,y:s}),n.push({x:e.x,y:s})):null!==i&&(n.push({x:i,y:t.y}),n.push({x:i,y:e.y}))}),n}(t)).length?new Da({points:i,options:{tension:0},_loop:s,_fullLoop:s}):null}function vn(t){return t&&!1!==t.fill}function _n(e,i,s){const a=[];for(let t=0;t{let{boxHeight:i=e,boxWidth:s=e}=t;return t.usePointStyle&&(i=Math.min(i,e),s=t.pointStyleWidth||Math.min(s,e)),{boxWidth:s,boxHeight:i,itemHeight:Math.max(e,i)}};class On extends e{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const i=this.options.labels||{};let t=d(i.generateLabels,[this.chart],this)||[];i.filter&&(t=t.filter(t=>i.filter(t,this.chart.data))),i.sort&&(t=t.sort((t,e)=>i.sort(t,e,this.chart.data))),this.options.reverse&&t.reverse(),this.legendItems=t}fit(){const{options:i,ctx:s}=this;if(i.display){var a=i.labels,n=z(a.font),o=n.size,r=this._computeTitleHeight(),{boxWidth:a,itemHeight:l}=Cn(a,o);let t,e;s.font=n.string,this.isHorizontal()?(t=this.maxWidth,e=this._fitRows(r,o,a,l)+10):(e=this.maxHeight,t=this._fitCols(r,n,a,l)+10),this.width=Math.min(t,i.maxWidth||this.maxWidth),this.height=Math.min(e,i.maxHeight||this.maxHeight)}else this.width=this.height=0}_fitRows(t,i,s,a){const{ctx:n,maxWidth:o,options:{labels:{padding:r}}}=this,l=this.legendHitBoxes=[],h=this.lineWidths=[0],c=a+r;let d=t,u=(n.textAlign="left",n.textBaseline="middle",-1),g=-c;return this.legendItems.forEach((t,e)=>{t=s+i/2+n.measureText(t.text).width;(0===e||h[h.length-1]+t+2*r>o)&&(d+=c,h[h.length-(0{o=l,i=r,s=c,a=t,n=h;var i,s,a,n,{itemWidth:t,itemHeight:o}={itemWidth:function(t,e,i){let s=a.text;return s&&"string"!=typeof s&&(s=s.reduce((t,e)=>t.length>e.length?t:e)),t+e.size/2+i.measureText(s).width}(o,i,s),itemHeight:function(t){let e=n;return e="string"!=typeof a.text?An(a,t):e}(i.lineHeight)};0f&&(p+=m+d,g.push({width:m,height:b}),x+=m+d,v++,m=b=0),u[e]={left:x,top:b,col:v,width:t,height:o},m=Math.max(m,t),b+=o+d}),p+=m,g.push({width:m,height:b}),p}adjustHitBoxes(){if(this.options.display){const i=this._computeTitleHeight(),{legendHitBoxes:s,options:{align:a,labels:{padding:n},rtl:t}}=this,o=Di(t,this.left,this.width);if(this.isHorizontal()){let t=0,e=E(a,this.left+n,this.right-this.lineWidths[t]);for(const r of s)t!==r.row&&(t=r.row,e=E(a,this.left+n,this.right-this.lineWidths[t])),r.top+=this.top+i+n,r.left=o.leftForLtr(o.x(e),r.width),e+=r.width+n}else{let t=0,e=E(a,this.top+i+n,this.bottom-this.columnSizes[t].height);for(const l of s)l.col!==t&&(t=l.col,e=E(a,this.top+i+n,this.bottom-this.columnSizes[t].height)),l.top=e,l.left+=this.left+n,l.left=o.leftForLtr(o.x(l.left),l.width),e+=l.height+n}}}isHorizontal(){return"top"===this.options.position||"bottom"===this.options.position}draw(){var t;this.options.display&&(Ve(t=this.ctx,this),this._draw(),Be(t))}_draw(){const{options:h,columnSizes:c,lineWidths:d,ctx:u}=this,{align:g,labels:f}=h,p=R.color,m=Di(h.rtl,this.left,this.width),b=z(f.font),x=f["padding"],v=b.size,_=v/2;let y;this.drawTitle(),u.textAlign=m.textAlign("left"),u.textBaseline="middle",u.lineWidth=.5,u.font=b.string;const{boxWidth:M,boxHeight:w,itemHeight:k}=Cn(f,v),S=this.isHorizontal(),P=this._computeTitleHeight(),D=(y=S?{x:E(g,this.left+x,this.right-d[0]),y:this.top+x+P,line:0}:{x:this.left+x,y:E(g,this.top+P+x,this.bottom-c[0].height),line:0},Ci(this.ctx,h.textDirection),k+x);this.legendItems.forEach((t,e)=>{u.strokeStyle=t.fontColor,u.fillStyle=t.fontColor;var i=u.measureText(t.text).width,s=m.textAlign(t.textAlign||(t.textAlign=f.textAlign)),i=M+_+i;let a=y.x,n=y.y;m.setWidth(this.width),S?0this.right&&(n=y.y+=D,y.line++,a=y.x=E(g,this.left+x,this.right-d[y.line])):0this.bottom&&(a=y.x=a+c[y.line].width+x,y.line++,n=y.y=E(g,this.top+P+x,this.bottom-c[y.line].height));var e=m.x(a),o=n,r=t;if(!(isNaN(M)||M<=0||isNaN(w)||w<0)){u.save();var l=T(r.lineWidth,1);if(u.fillStyle=T(r.fillStyle,p),u.lineCap=T(r.lineCap,"butt"),u.lineDashOffset=T(r.lineDashOffset,0),u.lineJoin=T(r.lineJoin,"miter"),u.lineWidth=l,u.strokeStyle=T(r.strokeStyle,p),u.setLineDash(T(r.lineDash,[])),f.usePointStyle){const p={radius:w*Math.SQRT2/2,pointStyle:r.pointStyle,rotation:r.rotation,borderWidth:l},T=m.xPlus(e,M/2);Fe(u,p,T,o+_,f.pointStyleWidth&&M)}else{const f=o+Math.max((v-w)/2,0),p=m.leftForLtr(e,M),T=wi(r.borderRadius);u.beginPath(),Object.values(T).some(t=>0!==t)?je(u,{x:p,y:f,w:M,h:w,radius:T}):u.rect(p,f,M,w),u.fill(),0!==l&&u.stroke()}u.restore()}if(a=Ct(s,a+M+_,S?a+i:this.right,h.rtl),o=m.x(a),e=n,r=t,He(u,r.text,o,e+k/2,b,{strikethrough:r.hidden,textAlign:m.textAlign(r.textAlign)}),S)y.x+=i+x;else if("string"!=typeof t.text){const h=b.lineHeight;y.y+=An(t,h)+x}else y.y+=D}),Oi(this.ctx,h.textDirection)}drawTitle(){const s=this.options,a=s.title,n=z(a.font),o=I(a.padding);if(a.display){const l=Di(s.rtl,this.left,this.width),h=this.ctx,c=a.position,d=n.size/2,u=o.top+d;let t,e=this.left,i=this.width;if(this.isHorizontal())i=Math.max(...this.lineWidths),t=this.top+u,e=E(s.align,e,this.right-i);else{const a=this.columnSizes.reduce((t,e)=>Math.max(t,e.height),0);t=u+E(s.align,this.top,this.bottom-a-s.labels.padding-this._computeTitleHeight())}var r=E(c,e,e+i);h.textAlign=l.textAlign(Dt(c)),h.textBaseline="middle",h.strokeStyle=a.color,h.fillStyle=a.color,h.font=n.string,He(h,a.text,r,t,n)}}_computeTitleHeight(){var t=this.options.title,e=z(t.font),i=I(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,s,a;if(c(t,this.left,this.right)&&c(e,this.top,this.bottom))for(a=this.legendHitBoxes,i=0;it.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const s=t.data.datasets,{usePointStyle:a,pointStyle:n,textAlign:o,color:r,useBorderRadius:l,borderRadius:h}=t.legend.options["labels"];return t._getSortedDatasetMetas().map(t=>{var e=t.controller.getStyle(a?0:void 0),i=I(e.borderWidth);return{text:s[t.index].label,fillStyle:e.backgroundColor,fontColor:r,hidden:!t.visible,lineCap:e.borderCapStyle,lineDash:e.borderDash,lineDashOffset:e.borderDashOffset,lineJoin:e.borderJoinStyle,lineWidth:(i.width+i.height)/4,strokeStyle:e.borderColor,pointStyle:n||e.pointStyle,rotation:e.rotation,textAlign:o||e.textAlign,borderRadius:l&&(h||e.borderRadius),datasetIndex:t.index}},this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class Ln extends e{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){var i=this.options;this.left=0,this.top=0,i.display?(this.width=this.right=t,this.height=this.bottom=e,t=O(i.text)?i.text.length:1,this._padding=I(i.padding),e=t*z(i.font).lineHeight+this._padding.height,this.isHorizontal()?this.height=e:this.width=e):this.width=this.height=this.right=this.bottom=0}isHorizontal(){var t=this.options.position;return"top"===t||"bottom"===t}_drawArgs(t){var{top:e,left:i,bottom:s,right:a,options:n}=this,o=n.align;let r,l,h,c=0;return r=this.isHorizontal()?(l=E(o,i,a),h=e+t,a-i):(c="left"===n.position?(l=i+t,h=E(o,s,e),-.5*S):(l=a-t,h=E(o,e,s),.5*S),s-e),{titleX:l,titleY:h,maxWidth:r,rotation:c}}draw(){var t,e,i,s,a,n=this.ctx,o=this.options;o.display&&(e=(t=z(o.font)).lineHeight/2+this._padding.top,{titleX:e,titleY:i,maxWidth:s,rotation:a}=this._drawArgs(e),He(n,o.text,0,0,t,{color:o.color,maxWidth:s,rotation:a,textAlign:Dt(o.align),textBaseline:"middle",translation:[e,i]}))}}var En={id:"title",_element:Ln,start(t,e,i){var s;t=t,i=i,s=new Ln({ctx:t.ctx,options:i,chart:t}),a.configure(t,s,i),a.addBox(t,s),t.titleBlock=s},stop(t){var e=t.titleBlock;a.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,i){const s=t.titleBlock;a.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Rn=new WeakMap;var In={id:"subtitle",start(t,e,i){var s=new Ln({ctx:t.ctx,options:i,chart:t});a.configure(t,s,i),a.addBox(t,s),Rn.set(t,s)},stop(t){a.removeBox(t,Rn.get(t)),Rn.delete(t)},beforeUpdate(t,e,i){const s=Rn.get(t);a.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const zn={average(t){if(!t.length)return!1;let e,i,s=0,a=0,n=0;for(e=0,i=t.length;et+e.before.length+e.lines.length+e.after.length,0),x=(b+=t.beforeBody.length+t.afterBody.length,d&&(p+=d*h.lineHeight+(d-1)*e.titleSpacing+e.titleMarginBottom),b&&(p+=g*(e.displayColors?Math.max(r,l.lineHeight):l.lineHeight)+(b-g)*l.lineHeight+(b-1)*e.bodySpacing),u&&(p+=e.footerMarginTop+u*c.lineHeight+(u-1)*e.footerSpacing),0);function v(t){m=Math.max(m,i.measureText(t).width+x)}return i.save(),i.font=h.string,k(t.title,v),i.font=l.string,k(t.beforeBody.concat(t.afterBody),v),x=e.displayColors?o+2+e.boxPadding:0,k(s,t=>{k(t.before,v),k(t.lines,v),k(t.after,v)}),x=0,i.font=c.string,k(t.footer,v),i.restore(),{width:m+=f.width,height:p}}function Bn(i,t,s){var e=s.yAlign||t.yAlign||function(){var{y:t,height:e}=s;return ti.height-e/2?"bottom":"center"}();return{xAlign:s.xAlign||t.xAlign||function(a,n,o,t){var{x:e,width:i}=o,{width:s,chartArea:{left:r,right:l}}=a;let h="center";return"center"===t?h=e<=(r+l)/2?"left":"right":e<=i/2?h="left":s-i/2<=e&&(h="right"),h=function(t){var{x:e,width:i}=o,s=n.caretSize+n.caretPadding;return"left"===t&&e+i+s>a.width||"right"===t&&e-i-s<0}(h)?"center":h}(i,t,s,e),yAlign:e}}function Wn(t,i,e,s){var{caretSize:t,caretPadding:a,cornerRadius:n}=t,{xAlign:o,yAlign:r}=e,l=t+a,{topLeft:e,topRight:a,bottomLeft:n,bottomRight:h}=wi(n);let c=function(){let{x:t,width:e}=i;return"right"===o?t-=e:"center"===o&&(t-=e/2),t}();var d=function(){let{y:t,height:e}=i;return"top"===r?t+=l:t-="bottom"===r?e+l:e/2,t}();return"center"===r?"left"===o?c+=l:"right"===o&&(c-=l):"left"===o?c-=Math.max(e,n)+t:"right"===o&&(c+=Math.max(a,h)+t),{x:C(c,0,s.width-i.width),y:C(d,0,s.height-i.height)}}function Nn(t,e,i){i=I(i.padding);return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-i.right:t.x+i.left}function Hn(t){return x([],Fn(t))}function jn(t,e){e=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return e?t.override(e):t}const Yn={beforeTitle:t,title(t){if(0{var e={before:[],lines:[],after:[]},i=jn(s,t);x(e.before,Fn(w(i,"beforeLabel",this,t))),x(e.lines,w(i,"label",this,t)),x(e.after,Fn(w(i,"afterLabel",this,t))),a.push(e)}),a}getAfterBody(t,e){return Hn(w(e.callbacks,"afterBody",this,t))}getFooter(t,e){var e=e["callbacks"],i=w(e,"beforeFooter",this,t),s=w(e,"footer",this,t),e=w(e,"afterFooter",this,t),t=x([],Fn(i));return t=x(t,Fn(s)),x(t,Fn(e))}_createItems(s){const t=this._active,a=this.chart.data,i=[],n=[],o=[];let e,r,l=[];for(e=0,r=t.length;es.filter(t,e,i,a))),k(l=s.itemSort?l.sort((t,e)=>s.itemSort(t,e,a)):l,t=>{var e=jn(s.callbacks,t);i.push(w(e,"labelColor",this,t)),n.push(w(e,"labelPointStyle",this,t)),o.push(w(e,"labelTextColor",this,t))}),this.labelColors=i,this.labelPointStyles=n,this.labelTextColors=o,this.dataPoints=l}update(t,e){const i=this.options.setContext(this.getContext()),s=this._active;let a,n=[];if(s.length){const t=zn[i.position].call(this,s,this._eventPosition),e=(n=this._createItems(i),this.title=this.getTitle(n,i),this.beforeBody=this.getBeforeBody(n,i),this.body=this.getBody(n,i),this.afterBody=this.getAfterBody(n,i),this.footer=this.getFooter(n,i),this._size=Vn(this,i)),o=Object.assign({},t,e),r=Bn(this.chart,i,o),l=Wn(i,o,r,this.chart);this.xAlign=r.xAlign,this.yAlign=r.yAlign,a={opacity:1,x:l.x,y:l.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(a={opacity:0});this._tooltipItems=n,this.$context=void 0,a&&this._resolveAnimations().update(this,a),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,s){t=this.getCaretPosition(t,i,s);e.lineTo(t.x1,t.y1),e.lineTo(t.x2,t.y2),e.lineTo(t.x3,t.y3)}getCaretPosition(t,e,i){var{xAlign:s,yAlign:a}=this,{caretSize:i,cornerRadius:n}=i,{topLeft:n,topRight:o,bottomLeft:r,bottomRight:l}=wi(n),{x:t,y:h}=t,{width:e,height:c}=e;let d,u,g,f,p,m;return"center"===a?(p=h+c/2,m="left"===s?(d=t,u=d-i,f=p+i,p-i):(d=t+e,u=d+i,f=p-i,p+i),g=d):(u="left"===s?t+Math.max(n,r)+i:"right"===s?t+e-Math.max(o,l)-i:this.caretX,g="top"===a?(f=h,p=f-i,d=u-i,u+i):(f=h+c,p=f+i,d=u+i,u-i),m=f),{x1:d,x2:u,x3:g,y1:f,y2:p,y3:m}}drawTitle(t,e,i){var s=this.title,a=s.length;let n,o,r;if(a){const l=Di(i.rtl,this.x,this.width);for(t.x=Nn(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",n=z(i.titleFont),o=i.titleSpacing,e.fillStyle=i.titleColor,e.font=n.string,r=0;r0!==t)?(t.beginPath(),t.fillStyle=a.multiKeyBackground,je(t,{x:e,y:g,w:l,h:r,radius:o}),t.fill(),t.stroke(),t.fillStyle=n.backgroundColor,t.beginPath(),je(t,{x:i,y:g+1,w:l-2,h:r-2,radius:o}),t.fill()):(t.fillStyle=a.multiKeyBackground,t.fillRect(e,g,l,r),t.strokeRect(e,g,l,r),t.fillStyle=n.backgroundColor,t.fillRect(i,g+1,l-2,r-2))}t.fillStyle=this.labelTextColors[i]}drawBody(e,i,t){const s=this["body"],{bodySpacing:a,bodyAlign:n,displayColors:o,boxHeight:r,boxWidth:l,boxPadding:h}=t,c=z(t.bodyFont);let d=c.lineHeight,u=0;function g(t){i.fillText(t,f.x(e.x+u),e.y+d/2),e.y+=d+a}const f=Di(t.rtl,this.x,this.width),p=f.textAlign(n);let m,b,x,v,_,y,M;for(i.textAlign=n,i.textBaseline="middle",i.font=c.string,e.x=Nn(this,p,t),i.fillStyle=t.bodyColor,k(this.beforeBody,g),u=o&&"right"!==p?"center"===n?l/2+h:l+2+h:0,v=0,y=s.length;v{var i=this.chart.getDatasetMeta(t);if(i)return{datasetIndex:t,element:i.data[e],index:e};throw new Error("Cannot find a dataset at index "+t)}),i=!W(i,t),s=this._positionChanged(t,e);(i||s)&&(this._active=t,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;var s=this.options,a=this._active||[],i=this._getActiveElements(t,a,e,i),n=this._positionChanged(i,t),a=e||!W(i,a)||n;return a&&(this._active=i,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),a}_getActiveElements(t,e,i,s){var a=this.options;if("mouseout"===t.type)return[];if(!s)return e.filter(t=>this.chart.data.datasets[t.datasetIndex]&&void 0!==this.chart.getDatasetMeta(t.datasetIndex).controller.getParsed(t.index));const n=this.chart.getElementsAtEventForMode(t,a.mode,a,i);return a.reverse&&n.reverse(),n}_positionChanged(t,e){var{caretX:i,caretY:s,options:a}=this,a=zn[a.position].call(this,t,e);return!1!==a&&(i!==a.x||s!==a.y)}}var Un={id:"tooltip",_element:$n,positioners:zn,afterInit(t,e,i){i&&(t.tooltip=new $n({chart:t,options:i}))},beforeUpdate(t,e,i){t.tooltip&&t.tooltip.initialize(i)},reset(t,e,i){t.tooltip&&t.tooltip.initialize(i)},afterDraw(t){const e=t.tooltip;var i;e&&e._willRender()&&(!(i={tooltip:e})!==t.notifyPlugins("beforeTooltipDraw",{...i,cancelable:!0})&&(e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",i)))},afterEvent(t,e){var i;t.tooltip&&(i=e.replay,t.tooltip.handleEvent(e.event,i,e.inChartArea)&&(e.changed=!0))},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:Yn},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>"filter"!==t&&"itemSort"!==t&&"external"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};return i.register(ba,an,Ra,s),i.helpers={...Fi},i._adapters=ha,i.Animation=bs,i.Animations=xs,i.animator=l,i.controllers=b.controllers.items,i.DatasetController=Os,i.Element=e,i.elements=Ra,i.Interaction=Hi,i.layouts=a,i.platforms=Oe,i.Scale=zs,i.Ticks=ge,Object.assign(i,ba,an,Ra,s,Oe),i.Chart=i,"undefined"!=typeof window&&(window.Chart=i),i}); \ No newline at end of file diff --git a/primary/public/lib/chart.umd.js.map b/primary/public/lib/chart.umd.js.map new file mode 100644 index 00000000..3c391bf5 --- /dev/null +++ b/primary/public/lib/chart.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chart.umd.js","sources":["../src/helpers/helpers.core.ts","../src/helpers/helpers.math.ts","../src/helpers/helpers.collection.ts","../src/helpers/helpers.extras.ts","../src/core/core.animator.js","../node_modules/.pnpm/@kurkle+color@0.3.2/node_modules/@kurkle/color/dist/color.esm.js","../src/helpers/helpers.color.ts","../src/core/core.animations.defaults.js","../src/helpers/helpers.intl.ts","../src/core/core.ticks.js","../src/core/core.defaults.js","../src/core/core.layouts.defaults.js","../src/core/core.scale.defaults.js","../src/helpers/helpers.dom.ts","../src/helpers/helpers.canvas.ts","../src/helpers/helpers.config.ts","../src/helpers/helpers.curve.ts","../src/helpers/helpers.easing.ts","../src/helpers/helpers.interpolation.ts","../src/helpers/helpers.options.ts","../src/helpers/helpers.rtl.ts","../src/helpers/helpers.segment.js","../src/core/core.interaction.js","../src/core/core.layouts.js","../src/platform/platform.base.js","../src/platform/platform.basic.js","../src/platform/platform.dom.js","../src/platform/index.js","../src/core/core.animation.js","../src/core/core.animations.js","../src/core/core.datasetController.js","../src/core/core.element.ts","../src/core/core.scale.autoskip.js","../src/core/core.scale.js","../src/core/core.typedRegistry.js","../src/core/core.registry.js","../src/core/core.plugins.js","../src/core/core.config.js","../src/core/core.controller.js","../src/core/core.adapters.ts","../src/controllers/controller.bar.js","../src/controllers/controller.doughnut.js","../src/controllers/controller.polarArea.js","../src/controllers/controller.bubble.js","../src/controllers/controller.line.js","../src/controllers/controller.pie.js","../src/controllers/controller.radar.js","../src/controllers/controller.scatter.js","../src/elements/element.arc.ts","../src/elements/element.line.js","../src/elements/element.point.ts","../src/elements/element.bar.js","../src/scales/scale.category.js","../src/scales/scale.linearbase.js","../src/scales/scale.linear.js","../src/scales/scale.logarithmic.js","../src/scales/scale.radialLinear.js","../src/scales/scale.time.js","../src/scales/scale.timeseries.js","../src/plugins/plugin.colors.ts","../src/plugins/plugin.decimation.js","../src/plugins/plugin.filler/filler.segment.js","../src/plugins/plugin.filler/filler.helper.js","../src/plugins/plugin.filler/filler.options.js","../src/plugins/plugin.filler/filler.target.stack.js","../src/plugins/plugin.filler/simpleArc.js","../src/plugins/plugin.filler/filler.target.js","../src/plugins/plugin.filler/filler.drawing.js","../src/plugins/plugin.filler/index.js","../src/plugins/plugin.legend.js","../src/plugins/plugin.title.js","../src/plugins/plugin.subtitle.js","../src/plugins/plugin.tooltip.js","../src/index.umd.ts"],"sourcesContent":["/**\n * @namespace Chart.helpers\n */\n\nimport type {AnyObject} from '../types/basic.js';\nimport type {ActiveDataPoint, ChartEvent} from '../types/index.js';\n\n/**\n * An empty function that can be used, for example, for optional callback.\n */\nexport function noop() {\n /* noop */\n}\n\n/**\n * Returns a unique id, sequentially generated from a global variable.\n */\nexport const uid = (() => {\n let id = 0;\n return () => id++;\n})();\n\n/**\n * Returns true if `value` is neither null nor undefined, else returns false.\n * @param value - The value to test.\n * @since 2.7.0\n */\nexport function isNullOrUndef(value: unknown): value is null | undefined {\n return value === null || typeof value === 'undefined';\n}\n\n/**\n * Returns true if `value` is an array (including typed arrays), else returns false.\n * @param value - The value to test.\n * @function\n */\nexport function isArray(value: unknown): value is T[] {\n if (Array.isArray && Array.isArray(value)) {\n return true;\n }\n const type = Object.prototype.toString.call(value);\n if (type.slice(0, 7) === '[object' && type.slice(-6) === 'Array]') {\n return true;\n }\n return false;\n}\n\n/**\n * Returns true if `value` is an object (excluding null), else returns false.\n * @param value - The value to test.\n * @since 2.7.0\n */\nexport function isObject(value: unknown): value is AnyObject {\n return value !== null && Object.prototype.toString.call(value) === '[object Object]';\n}\n\n/**\n * Returns true if `value` is a finite number, else returns false\n * @param value - The value to test.\n */\nfunction isNumberFinite(value: unknown): value is number {\n return (typeof value === 'number' || value instanceof Number) && isFinite(+value);\n}\nexport {\n isNumberFinite as isFinite,\n};\n\n/**\n * Returns `value` if finite, else returns `defaultValue`.\n * @param value - The value to return if defined.\n * @param defaultValue - The value to return if `value` is not finite.\n */\nexport function finiteOrDefault(value: unknown, defaultValue: number) {\n return isNumberFinite(value) ? value : defaultValue;\n}\n\n/**\n * Returns `value` if defined, else returns `defaultValue`.\n * @param value - The value to return if defined.\n * @param defaultValue - The value to return if `value` is undefined.\n */\nexport function valueOrDefault(value: T | undefined, defaultValue: T) {\n return typeof value === 'undefined' ? defaultValue : value;\n}\n\nexport const toPercentage = (value: number | string, dimension: number) =>\n typeof value === 'string' && value.endsWith('%') ?\n parseFloat(value) / 100\n : +value / dimension;\n\nexport const toDimension = (value: number | string, dimension: number) =>\n typeof value === 'string' && value.endsWith('%') ?\n parseFloat(value) / 100 * dimension\n : +value;\n\n/**\n * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the\n * value returned by `fn`. If `fn` is not a function, this method returns undefined.\n * @param fn - The function to call.\n * @param args - The arguments with which `fn` should be called.\n * @param [thisArg] - The value of `this` provided for the call to `fn`.\n */\nexport function callback R, TA, R>(\n fn: T | undefined,\n args: unknown[],\n thisArg?: TA\n): R | undefined {\n if (fn && typeof fn.call === 'function') {\n return fn.apply(thisArg, args);\n }\n}\n\n/**\n * Note(SB) for performance sake, this method should only be used when loopable type\n * is unknown or in none intensive code (not called often and small loopable). Else\n * it's preferable to use a regular for() loop and save extra function calls.\n * @param loopable - The object or array to be iterated.\n * @param fn - The function to call for each item.\n * @param [thisArg] - The value of `this` provided for the call to `fn`.\n * @param [reverse] - If true, iterates backward on the loopable.\n */\nexport function each(\n loopable: Record,\n fn: (this: TA, v: T, i: string) => void,\n thisArg?: TA,\n reverse?: boolean\n): void;\nexport function each(\n loopable: T[],\n fn: (this: TA, v: T, i: number) => void,\n thisArg?: TA,\n reverse?: boolean\n): void;\nexport function each(\n loopable: T[] | Record,\n fn: (this: TA, v: T, i: any) => void,\n thisArg?: TA,\n reverse?: boolean\n) {\n let i: number, len: number, keys: string[];\n if (isArray(loopable)) {\n len = loopable.length;\n if (reverse) {\n for (i = len - 1; i >= 0; i--) {\n fn.call(thisArg, loopable[i], i);\n }\n } else {\n for (i = 0; i < len; i++) {\n fn.call(thisArg, loopable[i], i);\n }\n }\n } else if (isObject(loopable)) {\n keys = Object.keys(loopable);\n len = keys.length;\n for (i = 0; i < len; i++) {\n fn.call(thisArg, loopable[keys[i]], keys[i]);\n }\n }\n}\n\n/**\n * Returns true if the `a0` and `a1` arrays have the same content, else returns false.\n * @param a0 - The array to compare\n * @param a1 - The array to compare\n * @private\n */\nexport function _elementsEqual(a0: ActiveDataPoint[], a1: ActiveDataPoint[]) {\n let i: number, ilen: number, v0: ActiveDataPoint, v1: ActiveDataPoint;\n\n if (!a0 || !a1 || a0.length !== a1.length) {\n return false;\n }\n\n for (i = 0, ilen = a0.length; i < ilen; ++i) {\n v0 = a0[i];\n v1 = a1[i];\n\n if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Returns a deep copy of `source` without keeping references on objects and arrays.\n * @param source - The value to clone.\n */\nexport function clone(source: T): T {\n if (isArray(source)) {\n return source.map(clone) as unknown as T;\n }\n\n if (isObject(source)) {\n const target = Object.create(null);\n const keys = Object.keys(source);\n const klen = keys.length;\n let k = 0;\n\n for (; k < klen; ++k) {\n target[keys[k]] = clone(source[keys[k]]);\n }\n\n return target;\n }\n\n return source;\n}\n\nfunction isValidKey(key: string) {\n return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;\n}\n\n/**\n * The default merger when Chart.helpers.merge is called without merger option.\n * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.\n * @private\n */\nexport function _merger(key: string, target: AnyObject, source: AnyObject, options: AnyObject) {\n if (!isValidKey(key)) {\n return;\n }\n\n const tval = target[key];\n const sval = source[key];\n\n if (isObject(tval) && isObject(sval)) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n merge(tval, sval, options);\n } else {\n target[key] = clone(sval);\n }\n}\n\nexport interface MergeOptions {\n merger?: (key: string, target: AnyObject, source: AnyObject, options?: AnyObject) => void;\n}\n\n/**\n * Recursively deep copies `source` properties into `target` with the given `options`.\n * IMPORTANT: `target` is not cloned and will be updated with `source` properties.\n * @param target - The target object in which all sources are merged into.\n * @param source - Object(s) to merge into `target`.\n * @param [options] - Merging options:\n * @param [options.merger] - The merge method (key, target, source, options)\n * @returns The `target` object.\n */\nexport function merge(target: T, source: [], options?: MergeOptions): T;\nexport function merge(target: T, source: S1, options?: MergeOptions): T & S1;\nexport function merge(target: T, source: [S1], options?: MergeOptions): T & S1;\nexport function merge(target: T, source: [S1, S2], options?: MergeOptions): T & S1 & S2;\nexport function merge(target: T, source: [S1, S2, S3], options?: MergeOptions): T & S1 & S2 & S3;\nexport function merge(\n target: T,\n source: [S1, S2, S3, S4],\n options?: MergeOptions\n): T & S1 & S2 & S3 & S4;\nexport function merge(target: T, source: AnyObject[], options?: MergeOptions): AnyObject;\nexport function merge(target: T, source: AnyObject[], options?: MergeOptions): AnyObject {\n const sources = isArray(source) ? source : [source];\n const ilen = sources.length;\n\n if (!isObject(target)) {\n return target as AnyObject;\n }\n\n options = options || {};\n const merger = options.merger || _merger;\n let current: AnyObject;\n\n for (let i = 0; i < ilen; ++i) {\n current = sources[i];\n if (!isObject(current)) {\n continue;\n }\n\n const keys = Object.keys(current);\n for (let k = 0, klen = keys.length; k < klen; ++k) {\n merger(keys[k], target, current, options as AnyObject);\n }\n }\n\n return target;\n}\n\n/**\n * Recursively deep copies `source` properties into `target` *only* if not defined in target.\n * IMPORTANT: `target` is not cloned and will be updated with `source` properties.\n * @param target - The target object in which all sources are merged into.\n * @param source - Object(s) to merge into `target`.\n * @returns The `target` object.\n */\nexport function mergeIf(target: T, source: []): T;\nexport function mergeIf(target: T, source: S1): T & S1;\nexport function mergeIf(target: T, source: [S1]): T & S1;\nexport function mergeIf(target: T, source: [S1, S2]): T & S1 & S2;\nexport function mergeIf(target: T, source: [S1, S2, S3]): T & S1 & S2 & S3;\nexport function mergeIf(target: T, source: [S1, S2, S3, S4]): T & S1 & S2 & S3 & S4;\nexport function mergeIf(target: T, source: AnyObject[]): AnyObject;\nexport function mergeIf(target: T, source: AnyObject[]): AnyObject {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return merge(target, source, {merger: _mergerIf});\n}\n\n/**\n * Merges source[key] in target[key] only if target[key] is undefined.\n * @private\n */\nexport function _mergerIf(key: string, target: AnyObject, source: AnyObject) {\n if (!isValidKey(key)) {\n return;\n }\n\n const tval = target[key];\n const sval = source[key];\n\n if (isObject(tval) && isObject(sval)) {\n mergeIf(tval, sval);\n } else if (!Object.prototype.hasOwnProperty.call(target, key)) {\n target[key] = clone(sval);\n }\n}\n\n/**\n * @private\n */\nexport function _deprecated(scope: string, value: unknown, previous: string, current: string) {\n if (value !== undefined) {\n console.warn(scope + ': \"' + previous +\n '\" is deprecated. Please use \"' + current + '\" instead');\n }\n}\n\n// resolveObjectKey resolver cache\nconst keyResolvers = {\n // Chart.helpers.core resolveObjectKey should resolve empty key to root object\n '': v => v,\n // default resolvers\n x: o => o.x,\n y: o => o.y\n};\n\n/**\n * @private\n */\nexport function _splitKey(key: string) {\n const parts = key.split('.');\n const keys: string[] = [];\n let tmp = '';\n for (const part of parts) {\n tmp += part;\n if (tmp.endsWith('\\\\')) {\n tmp = tmp.slice(0, -1) + '.';\n } else {\n keys.push(tmp);\n tmp = '';\n }\n }\n return keys;\n}\n\nfunction _getKeyResolver(key: string) {\n const keys = _splitKey(key);\n return obj => {\n for (const k of keys) {\n if (k === '') {\n // For backward compatibility:\n // Chart.helpers.core resolveObjectKey should break at empty key\n break;\n }\n obj = obj && obj[k];\n }\n return obj;\n };\n}\n\nexport function resolveObjectKey(obj: AnyObject, key: string): any {\n const resolver = keyResolvers[key] || (keyResolvers[key] = _getKeyResolver(key));\n return resolver(obj);\n}\n\n/**\n * @private\n */\nexport function _capitalize(str: string) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n\nexport const defined = (value: unknown) => typeof value !== 'undefined';\n\nexport const isFunction = (value: unknown): value is (...args: any[]) => any => typeof value === 'function';\n\n// Adapted from https://stackoverflow.com/questions/31128855/comparing-ecma6-sets-for-equality#31129384\nexport const setsEqual = (a: Set, b: Set) => {\n if (a.size !== b.size) {\n return false;\n }\n\n for (const item of a) {\n if (!b.has(item)) {\n return false;\n }\n }\n\n return true;\n};\n\n/**\n * @param e - The event\n * @private\n */\nexport function _isClickEvent(e: ChartEvent) {\n return e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu';\n}\n","import type {Point} from '../types/geometric.js';\nimport {isFinite as isFiniteNumber} from './helpers.core.js';\n\n/**\n * @alias Chart.helpers.math\n * @namespace\n */\n\nexport const PI = Math.PI;\nexport const TAU = 2 * PI;\nexport const PITAU = TAU + PI;\nexport const INFINITY = Number.POSITIVE_INFINITY;\nexport const RAD_PER_DEG = PI / 180;\nexport const HALF_PI = PI / 2;\nexport const QUARTER_PI = PI / 4;\nexport const TWO_THIRDS_PI = PI * 2 / 3;\n\nexport const log10 = Math.log10;\nexport const sign = Math.sign;\n\nexport function almostEquals(x: number, y: number, epsilon: number) {\n return Math.abs(x - y) < epsilon;\n}\n\n/**\n * Implementation of the nice number algorithm used in determining where axis labels will go\n */\nexport function niceNum(range: number) {\n const roundedRange = Math.round(range);\n range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range;\n const niceRange = Math.pow(10, Math.floor(log10(range)));\n const fraction = range / niceRange;\n const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;\n return niceFraction * niceRange;\n}\n\n/**\n * Returns an array of factors sorted from 1 to sqrt(value)\n * @private\n */\nexport function _factorize(value: number) {\n const result: number[] = [];\n const sqrt = Math.sqrt(value);\n let i: number;\n\n for (i = 1; i < sqrt; i++) {\n if (value % i === 0) {\n result.push(i);\n result.push(value / i);\n }\n }\n if (sqrt === (sqrt | 0)) { // if value is a square number\n result.push(sqrt);\n }\n\n result.sort((a, b) => a - b).pop();\n return result;\n}\n\nexport function isNumber(n: unknown): n is number {\n return !isNaN(parseFloat(n as string)) && isFinite(n as number);\n}\n\nexport function almostWhole(x: number, epsilon: number) {\n const rounded = Math.round(x);\n return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);\n}\n\n/**\n * @private\n */\nexport function _setMinAndMaxByKey(\n array: Record[],\n target: { min: number, max: number },\n property: string\n) {\n let i: number, ilen: number, value: number;\n\n for (i = 0, ilen = array.length; i < ilen; i++) {\n value = array[i][property];\n if (!isNaN(value)) {\n target.min = Math.min(target.min, value);\n target.max = Math.max(target.max, value);\n }\n }\n}\n\nexport function toRadians(degrees: number) {\n return degrees * (PI / 180);\n}\n\nexport function toDegrees(radians: number) {\n return radians * (180 / PI);\n}\n\n/**\n * Returns the number of decimal places\n * i.e. the number of digits after the decimal point, of the value of this Number.\n * @param x - A number.\n * @returns The number of decimal places.\n * @private\n */\nexport function _decimalPlaces(x: number) {\n if (!isFiniteNumber(x)) {\n return;\n }\n let e = 1;\n let p = 0;\n while (Math.round(x * e) / e !== x) {\n e *= 10;\n p++;\n }\n return p;\n}\n\n// Gets the angle from vertical upright to the point about a centre.\nexport function getAngleFromPoint(\n centrePoint: Point,\n anglePoint: Point\n) {\n const distanceFromXCenter = anglePoint.x - centrePoint.x;\n const distanceFromYCenter = anglePoint.y - centrePoint.y;\n const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);\n\n let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);\n\n if (angle < (-0.5 * PI)) {\n angle += TAU; // make sure the returned angle is in the range of (-PI/2, 3PI/2]\n }\n\n return {\n angle,\n distance: radialDistanceFromCenter\n };\n}\n\nexport function distanceBetweenPoints(pt1: Point, pt2: Point) {\n return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));\n}\n\n/**\n * Shortest distance between angles, in either direction.\n * @private\n */\nexport function _angleDiff(a: number, b: number) {\n return (a - b + PITAU) % TAU - PI;\n}\n\n/**\n * Normalize angle to be between 0 and 2*PI\n * @private\n */\nexport function _normalizeAngle(a: number) {\n return (a % TAU + TAU) % TAU;\n}\n\n/**\n * @private\n */\nexport function _angleBetween(angle: number, start: number, end: number, sameAngleIsFullCircle?: boolean) {\n const a = _normalizeAngle(angle);\n const s = _normalizeAngle(start);\n const e = _normalizeAngle(end);\n const angleToStart = _normalizeAngle(s - a);\n const angleToEnd = _normalizeAngle(e - a);\n const startToAngle = _normalizeAngle(a - s);\n const endToAngle = _normalizeAngle(a - e);\n return a === s || a === e || (sameAngleIsFullCircle && s === e)\n || (angleToStart > angleToEnd && startToAngle < endToAngle);\n}\n\n/**\n * Limit `value` between `min` and `max`\n * @param value\n * @param min\n * @param max\n * @private\n */\nexport function _limitValue(value: number, min: number, max: number) {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * @param {number} value\n * @private\n */\nexport function _int16Range(value: number) {\n return _limitValue(value, -32768, 32767);\n}\n\n/**\n * @param value\n * @param start\n * @param end\n * @param [epsilon]\n * @private\n */\nexport function _isBetween(value: number, start: number, end: number, epsilon = 1e-6) {\n return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon;\n}\n","import {_capitalize} from './helpers.core.js';\n\n/**\n * Binary search\n * @param table - the table search. must be sorted!\n * @param value - value to find\n * @param cmp\n * @private\n */\nexport function _lookup(\n table: number[],\n value: number,\n cmp?: (value: number) => boolean\n): {lo: number, hi: number};\nexport function _lookup(\n table: T[],\n value: number,\n cmp: (value: number) => boolean\n): {lo: number, hi: number};\nexport function _lookup(\n table: unknown[],\n value: number,\n cmp?: (value: number) => boolean\n) {\n cmp = cmp || ((index) => table[index] < value);\n let hi = table.length - 1;\n let lo = 0;\n let mid: number;\n\n while (hi - lo > 1) {\n mid = (lo + hi) >> 1;\n if (cmp(mid)) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n\n return {lo, hi};\n}\n\n/**\n * Binary search\n * @param table - the table search. must be sorted!\n * @param key - property name for the value in each entry\n * @param value - value to find\n * @param last - lookup last index\n * @private\n */\nexport const _lookupByKey = (\n table: Record[],\n key: string,\n value: number,\n last?: boolean\n) =>\n _lookup(table, value, last\n ? index => {\n const ti = table[index][key];\n return ti < value || ti === value && table[index + 1][key] === value;\n }\n : index => table[index][key] < value);\n\n/**\n * Reverse binary search\n * @param table - the table search. must be sorted!\n * @param key - property name for the value in each entry\n * @param value - value to find\n * @private\n */\nexport const _rlookupByKey = (\n table: Record[],\n key: string,\n value: number\n) =>\n _lookup(table, value, index => table[index][key] >= value);\n\n/**\n * Return subset of `values` between `min` and `max` inclusive.\n * Values are assumed to be in sorted order.\n * @param values - sorted array of values\n * @param min - min value\n * @param max - max value\n */\nexport function _filterBetween(values: number[], min: number, max: number) {\n let start = 0;\n let end = values.length;\n\n while (start < end && values[start] < min) {\n start++;\n }\n while (end > start && values[end - 1] > max) {\n end--;\n }\n\n return start > 0 || end < values.length\n ? values.slice(start, end)\n : values;\n}\n\nconst arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'] as const;\n\nexport interface ArrayListener {\n _onDataPush?(...item: T[]): void;\n _onDataPop?(): void;\n _onDataShift?(): void;\n _onDataSplice?(index: number, deleteCount: number, ...items: T[]): void;\n _onDataUnshift?(...item: T[]): void;\n}\n\n/**\n * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',\n * 'unshift') and notify the listener AFTER the array has been altered. Listeners are\n * called on the '_onData*' callbacks (e.g. _onDataPush, etc.) with same arguments.\n */\nexport function listenArrayEvents(array: T[], listener: ArrayListener): void;\nexport function listenArrayEvents(array, listener) {\n if (array._chartjs) {\n array._chartjs.listeners.push(listener);\n return;\n }\n\n Object.defineProperty(array, '_chartjs', {\n configurable: true,\n enumerable: false,\n value: {\n listeners: [listener]\n }\n });\n\n arrayEvents.forEach((key) => {\n const method = '_onData' + _capitalize(key);\n const base = array[key];\n\n Object.defineProperty(array, key, {\n configurable: true,\n enumerable: false,\n value(...args) {\n const res = base.apply(this, args);\n\n array._chartjs.listeners.forEach((object) => {\n if (typeof object[method] === 'function') {\n object[method](...args);\n }\n });\n\n return res;\n }\n });\n });\n}\n\n\n/**\n * Removes the given array event listener and cleanup extra attached properties (such as\n * the _chartjs stub and overridden methods) if array doesn't have any more listeners.\n */\nexport function unlistenArrayEvents(array: T[], listener: ArrayListener): void;\nexport function unlistenArrayEvents(array, listener) {\n const stub = array._chartjs;\n if (!stub) {\n return;\n }\n\n const listeners = stub.listeners;\n const index = listeners.indexOf(listener);\n if (index !== -1) {\n listeners.splice(index, 1);\n }\n\n if (listeners.length > 0) {\n return;\n }\n\n arrayEvents.forEach((key) => {\n delete array[key];\n });\n\n delete array._chartjs;\n}\n\n/**\n * @param items\n */\nexport function _arrayUnique(items: T[]) {\n const set = new Set(items);\n\n if (set.size === items.length) {\n return items;\n }\n\n return Array.from(set);\n}\n","import type {ChartMeta, PointElement} from '../types/index.js';\n\nimport {_limitValue} from './helpers.math.js';\nimport {_lookupByKey} from './helpers.collection.js';\n\nexport function fontString(pixelSize: number, fontStyle: string, fontFamily: string) {\n return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;\n}\n\n/**\n* Request animation polyfill\n*/\nexport const requestAnimFrame = (function() {\n if (typeof window === 'undefined') {\n return function(callback) {\n return callback();\n };\n }\n return window.requestAnimationFrame;\n}());\n\n/**\n * Throttles calling `fn` once per animation frame\n * Latest arguments are used on the actual call\n */\nexport function throttled>(\n fn: (...args: TArgs) => void,\n thisArg: any,\n) {\n let argsToUse = [] as TArgs;\n let ticking = false;\n\n return function(...args: TArgs) {\n // Save the args for use later\n argsToUse = args;\n if (!ticking) {\n ticking = true;\n requestAnimFrame.call(window, () => {\n ticking = false;\n fn.apply(thisArg, argsToUse);\n });\n }\n };\n}\n\n/**\n * Debounces calling `fn` for `delay` ms\n */\nexport function debounce>(fn: (...args: TArgs) => void, delay: number) {\n let timeout;\n return function(...args: TArgs) {\n if (delay) {\n clearTimeout(timeout);\n timeout = setTimeout(fn, delay, args);\n } else {\n fn.apply(this, args);\n }\n return delay;\n };\n}\n\n/**\n * Converts 'start' to 'left', 'end' to 'right' and others to 'center'\n * @private\n */\nexport const _toLeftRightCenter = (align: 'start' | 'end' | 'center') => align === 'start' ? 'left' : align === 'end' ? 'right' : 'center';\n\n/**\n * Returns `start`, `end` or `(start + end) / 2` depending on `align`. Defaults to `center`\n * @private\n */\nexport const _alignStartEnd = (align: 'start' | 'end' | 'center', start: number, end: number) => align === 'start' ? start : align === 'end' ? end : (start + end) / 2;\n\n/**\n * Returns `left`, `right` or `(left + right) / 2` depending on `align`. Defaults to `left`\n * @private\n */\nexport const _textX = (align: 'left' | 'right' | 'center', left: number, right: number, rtl: boolean) => {\n const check = rtl ? 'left' : 'right';\n return align === check ? right : align === 'center' ? (left + right) / 2 : left;\n};\n\n/**\n * Return start and count of visible points.\n * @private\n */\nexport function _getStartAndCountOfVisiblePoints(meta: ChartMeta<'line' | 'scatter'>, points: PointElement[], animationsDisabled: boolean) {\n const pointCount = points.length;\n\n let start = 0;\n let count = pointCount;\n\n if (meta._sorted) {\n const {iScale, _parsed} = meta;\n const axis = iScale.axis;\n const {min, max, minDefined, maxDefined} = iScale.getUserBounds();\n\n if (minDefined) {\n start = _limitValue(Math.min(\n // @ts-expect-error Need to type _parsed\n _lookupByKey(_parsed, axis, min).lo,\n // @ts-expect-error Need to fix types on _lookupByKey\n animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo),\n 0, pointCount - 1);\n }\n if (maxDefined) {\n count = _limitValue(Math.max(\n // @ts-expect-error Need to type _parsed\n _lookupByKey(_parsed, iScale.axis, max, true).hi + 1,\n // @ts-expect-error Need to fix types on _lookupByKey\n animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max), true).hi + 1),\n start, pointCount) - start;\n } else {\n count = pointCount - start;\n }\n }\n\n return {start, count};\n}\n\n/**\n * Checks if the scale ranges have changed.\n * @param {object} meta - dataset meta.\n * @returns {boolean}\n * @private\n */\nexport function _scaleRangesChanged(meta) {\n const {xScale, yScale, _scaleRanges} = meta;\n const newRanges = {\n xmin: xScale.min,\n xmax: xScale.max,\n ymin: yScale.min,\n ymax: yScale.max\n };\n if (!_scaleRanges) {\n meta._scaleRanges = newRanges;\n return true;\n }\n const changed = _scaleRanges.xmin !== xScale.min\n\t\t|| _scaleRanges.xmax !== xScale.max\n\t\t|| _scaleRanges.ymin !== yScale.min\n\t\t|| _scaleRanges.ymax !== yScale.max;\n\n Object.assign(_scaleRanges, newRanges);\n return changed;\n}\n","import {requestAnimFrame} from '../helpers/helpers.extras.js';\n\n/**\n * @typedef { import('./core.animation.js').default } Animation\n * @typedef { import('./core.controller.js').default } Chart\n */\n\n/**\n * Please use the module's default export which provides a singleton instance\n * Note: class is export for typedoc\n */\nexport class Animator {\n constructor() {\n this._request = null;\n this._charts = new Map();\n this._running = false;\n this._lastDate = undefined;\n }\n\n /**\n\t * @private\n\t */\n _notify(chart, anims, date, type) {\n const callbacks = anims.listeners[type];\n const numSteps = anims.duration;\n\n callbacks.forEach(fn => fn({\n chart,\n initial: anims.initial,\n numSteps,\n currentStep: Math.min(date - anims.start, numSteps)\n }));\n }\n\n /**\n\t * @private\n\t */\n _refresh() {\n if (this._request) {\n return;\n }\n this._running = true;\n\n this._request = requestAnimFrame.call(window, () => {\n this._update();\n this._request = null;\n\n if (this._running) {\n this._refresh();\n }\n });\n }\n\n /**\n\t * @private\n\t */\n _update(date = Date.now()) {\n let remaining = 0;\n\n this._charts.forEach((anims, chart) => {\n if (!anims.running || !anims.items.length) {\n return;\n }\n const items = anims.items;\n let i = items.length - 1;\n let draw = false;\n let item;\n\n for (; i >= 0; --i) {\n item = items[i];\n\n if (item._active) {\n if (item._total > anims.duration) {\n // if the animation has been updated and its duration prolonged,\n // update to total duration of current animations run (for progress event)\n anims.duration = item._total;\n }\n item.tick(date);\n draw = true;\n } else {\n // Remove the item by replacing it with last item and removing the last\n // A lot faster than splice.\n items[i] = items[items.length - 1];\n items.pop();\n }\n }\n\n if (draw) {\n chart.draw();\n this._notify(chart, anims, date, 'progress');\n }\n\n if (!items.length) {\n anims.running = false;\n this._notify(chart, anims, date, 'complete');\n anims.initial = false;\n }\n\n remaining += items.length;\n });\n\n this._lastDate = date;\n\n if (remaining === 0) {\n this._running = false;\n }\n }\n\n /**\n\t * @private\n\t */\n _getAnims(chart) {\n const charts = this._charts;\n let anims = charts.get(chart);\n if (!anims) {\n anims = {\n running: false,\n initial: true,\n items: [],\n listeners: {\n complete: [],\n progress: []\n }\n };\n charts.set(chart, anims);\n }\n return anims;\n }\n\n /**\n\t * @param {Chart} chart\n\t * @param {string} event - event name\n\t * @param {Function} cb - callback\n\t */\n listen(chart, event, cb) {\n this._getAnims(chart).listeners[event].push(cb);\n }\n\n /**\n\t * Add animations\n\t * @param {Chart} chart\n\t * @param {Animation[]} items - animations\n\t */\n add(chart, items) {\n if (!items || !items.length) {\n return;\n }\n this._getAnims(chart).items.push(...items);\n }\n\n /**\n\t * Counts number of active animations for the chart\n\t * @param {Chart} chart\n\t */\n has(chart) {\n return this._getAnims(chart).items.length > 0;\n }\n\n /**\n\t * Start animating (all charts)\n\t * @param {Chart} chart\n\t */\n start(chart) {\n const anims = this._charts.get(chart);\n if (!anims) {\n return;\n }\n anims.running = true;\n anims.start = Date.now();\n anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0);\n this._refresh();\n }\n\n running(chart) {\n if (!this._running) {\n return false;\n }\n const anims = this._charts.get(chart);\n if (!anims || !anims.running || !anims.items.length) {\n return false;\n }\n return true;\n }\n\n /**\n\t * Stop all animations for the chart\n\t * @param {Chart} chart\n\t */\n stop(chart) {\n const anims = this._charts.get(chart);\n if (!anims || !anims.items.length) {\n return;\n }\n const items = anims.items;\n let i = items.length - 1;\n\n for (; i >= 0; --i) {\n items[i].cancel();\n }\n anims.items = [];\n this._notify(chart, anims, Date.now(), 'complete');\n }\n\n /**\n\t * Remove chart from Animator\n\t * @param {Chart} chart\n\t */\n remove(chart) {\n return this._charts.delete(chart);\n }\n}\n\n// singleton instance\nexport default /* #__PURE__ */ new Animator();\n","/*!\n * @kurkle/color v0.3.2\n * https://github.com/kurkle/color#readme\n * (c) 2023 Jukka Kurkela\n * Released under the MIT License\n */\nfunction round(v) {\n return v + 0.5 | 0;\n}\nconst lim = (v, l, h) => Math.max(Math.min(v, h), l);\nfunction p2b(v) {\n return lim(round(v * 2.55), 0, 255);\n}\nfunction b2p(v) {\n return lim(round(v / 2.55), 0, 100);\n}\nfunction n2b(v) {\n return lim(round(v * 255), 0, 255);\n}\nfunction b2n(v) {\n return lim(round(v / 2.55) / 100, 0, 1);\n}\nfunction n2p(v) {\n return lim(round(v * 100), 0, 100);\n}\n\nconst map$1 = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 10, B: 11, C: 12, D: 13, E: 14, F: 15, a: 10, b: 11, c: 12, d: 13, e: 14, f: 15};\nconst hex = [...'0123456789ABCDEF'];\nconst h1 = b => hex[b & 0xF];\nconst h2 = b => hex[(b & 0xF0) >> 4] + hex[b & 0xF];\nconst eq = b => ((b & 0xF0) >> 4) === (b & 0xF);\nconst isShort = v => eq(v.r) && eq(v.g) && eq(v.b) && eq(v.a);\nfunction hexParse(str) {\n var len = str.length;\n var ret;\n if (str[0] === '#') {\n if (len === 4 || len === 5) {\n ret = {\n r: 255 & map$1[str[1]] * 17,\n g: 255 & map$1[str[2]] * 17,\n b: 255 & map$1[str[3]] * 17,\n a: len === 5 ? map$1[str[4]] * 17 : 255\n };\n } else if (len === 7 || len === 9) {\n ret = {\n r: map$1[str[1]] << 4 | map$1[str[2]],\n g: map$1[str[3]] << 4 | map$1[str[4]],\n b: map$1[str[5]] << 4 | map$1[str[6]],\n a: len === 9 ? (map$1[str[7]] << 4 | map$1[str[8]]) : 255\n };\n }\n }\n return ret;\n}\nconst alpha = (a, f) => a < 255 ? f(a) : '';\nfunction hexString(v) {\n var f = isShort(v) ? h1 : h2;\n return v\n ? '#' + f(v.r) + f(v.g) + f(v.b) + alpha(v.a, f)\n : undefined;\n}\n\nconst HUE_RE = /^(hsla?|hwb|hsv)\\(\\s*([-+.e\\d]+)(?:deg)?[\\s,]+([-+.e\\d]+)%[\\s,]+([-+.e\\d]+)%(?:[\\s,]+([-+.e\\d]+)(%)?)?\\s*\\)$/;\nfunction hsl2rgbn(h, s, l) {\n const a = s * Math.min(l, 1 - l);\n const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n return [f(0), f(8), f(4)];\n}\nfunction hsv2rgbn(h, s, v) {\n const f = (n, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0);\n return [f(5), f(3), f(1)];\n}\nfunction hwb2rgbn(h, w, b) {\n const rgb = hsl2rgbn(h, 1, 0.5);\n let i;\n if (w + b > 1) {\n i = 1 / (w + b);\n w *= i;\n b *= i;\n }\n for (i = 0; i < 3; i++) {\n rgb[i] *= 1 - w - b;\n rgb[i] += w;\n }\n return rgb;\n}\nfunction hueValue(r, g, b, d, max) {\n if (r === max) {\n return ((g - b) / d) + (g < b ? 6 : 0);\n }\n if (g === max) {\n return (b - r) / d + 2;\n }\n return (r - g) / d + 4;\n}\nfunction rgb2hsl(v) {\n const range = 255;\n const r = v.r / range;\n const g = v.g / range;\n const b = v.b / range;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const l = (max + min) / 2;\n let h, s, d;\n if (max !== min) {\n d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n h = hueValue(r, g, b, d, max);\n h = h * 60 + 0.5;\n }\n return [h | 0, s || 0, l];\n}\nfunction calln(f, a, b, c) {\n return (\n Array.isArray(a)\n ? f(a[0], a[1], a[2])\n : f(a, b, c)\n ).map(n2b);\n}\nfunction hsl2rgb(h, s, l) {\n return calln(hsl2rgbn, h, s, l);\n}\nfunction hwb2rgb(h, w, b) {\n return calln(hwb2rgbn, h, w, b);\n}\nfunction hsv2rgb(h, s, v) {\n return calln(hsv2rgbn, h, s, v);\n}\nfunction hue(h) {\n return (h % 360 + 360) % 360;\n}\nfunction hueParse(str) {\n const m = HUE_RE.exec(str);\n let a = 255;\n let v;\n if (!m) {\n return;\n }\n if (m[5] !== v) {\n a = m[6] ? p2b(+m[5]) : n2b(+m[5]);\n }\n const h = hue(+m[2]);\n const p1 = +m[3] / 100;\n const p2 = +m[4] / 100;\n if (m[1] === 'hwb') {\n v = hwb2rgb(h, p1, p2);\n } else if (m[1] === 'hsv') {\n v = hsv2rgb(h, p1, p2);\n } else {\n v = hsl2rgb(h, p1, p2);\n }\n return {\n r: v[0],\n g: v[1],\n b: v[2],\n a: a\n };\n}\nfunction rotate(v, deg) {\n var h = rgb2hsl(v);\n h[0] = hue(h[0] + deg);\n h = hsl2rgb(h);\n v.r = h[0];\n v.g = h[1];\n v.b = h[2];\n}\nfunction hslString(v) {\n if (!v) {\n return;\n }\n const a = rgb2hsl(v);\n const h = a[0];\n const s = n2p(a[1]);\n const l = n2p(a[2]);\n return v.a < 255\n ? `hsla(${h}, ${s}%, ${l}%, ${b2n(v.a)})`\n : `hsl(${h}, ${s}%, ${l}%)`;\n}\n\nconst map = {\n x: 'dark',\n Z: 'light',\n Y: 're',\n X: 'blu',\n W: 'gr',\n V: 'medium',\n U: 'slate',\n A: 'ee',\n T: 'ol',\n S: 'or',\n B: 'ra',\n C: 'lateg',\n D: 'ights',\n R: 'in',\n Q: 'turquois',\n E: 'hi',\n P: 'ro',\n O: 'al',\n N: 'le',\n M: 'de',\n L: 'yello',\n F: 'en',\n K: 'ch',\n G: 'arks',\n H: 'ea',\n I: 'ightg',\n J: 'wh'\n};\nconst names$1 = {\n OiceXe: 'f0f8ff',\n antiquewEte: 'faebd7',\n aqua: 'ffff',\n aquamarRe: '7fffd4',\n azuY: 'f0ffff',\n beige: 'f5f5dc',\n bisque: 'ffe4c4',\n black: '0',\n blanKedOmond: 'ffebcd',\n Xe: 'ff',\n XeviTet: '8a2be2',\n bPwn: 'a52a2a',\n burlywood: 'deb887',\n caMtXe: '5f9ea0',\n KartYuse: '7fff00',\n KocTate: 'd2691e',\n cSO: 'ff7f50',\n cSnflowerXe: '6495ed',\n cSnsilk: 'fff8dc',\n crimson: 'dc143c',\n cyan: 'ffff',\n xXe: '8b',\n xcyan: '8b8b',\n xgTMnPd: 'b8860b',\n xWay: 'a9a9a9',\n xgYF: '6400',\n xgYy: 'a9a9a9',\n xkhaki: 'bdb76b',\n xmagFta: '8b008b',\n xTivegYF: '556b2f',\n xSange: 'ff8c00',\n xScEd: '9932cc',\n xYd: '8b0000',\n xsOmon: 'e9967a',\n xsHgYF: '8fbc8f',\n xUXe: '483d8b',\n xUWay: '2f4f4f',\n xUgYy: '2f4f4f',\n xQe: 'ced1',\n xviTet: '9400d3',\n dAppRk: 'ff1493',\n dApskyXe: 'bfff',\n dimWay: '696969',\n dimgYy: '696969',\n dodgerXe: '1e90ff',\n fiYbrick: 'b22222',\n flSOwEte: 'fffaf0',\n foYstWAn: '228b22',\n fuKsia: 'ff00ff',\n gaRsbSo: 'dcdcdc',\n ghostwEte: 'f8f8ff',\n gTd: 'ffd700',\n gTMnPd: 'daa520',\n Way: '808080',\n gYF: '8000',\n gYFLw: 'adff2f',\n gYy: '808080',\n honeyMw: 'f0fff0',\n hotpRk: 'ff69b4',\n RdianYd: 'cd5c5c',\n Rdigo: '4b0082',\n ivSy: 'fffff0',\n khaki: 'f0e68c',\n lavFMr: 'e6e6fa',\n lavFMrXsh: 'fff0f5',\n lawngYF: '7cfc00',\n NmoncEffon: 'fffacd',\n ZXe: 'add8e6',\n ZcSO: 'f08080',\n Zcyan: 'e0ffff',\n ZgTMnPdLw: 'fafad2',\n ZWay: 'd3d3d3',\n ZgYF: '90ee90',\n ZgYy: 'd3d3d3',\n ZpRk: 'ffb6c1',\n ZsOmon: 'ffa07a',\n ZsHgYF: '20b2aa',\n ZskyXe: '87cefa',\n ZUWay: '778899',\n ZUgYy: '778899',\n ZstAlXe: 'b0c4de',\n ZLw: 'ffffe0',\n lime: 'ff00',\n limegYF: '32cd32',\n lRF: 'faf0e6',\n magFta: 'ff00ff',\n maPon: '800000',\n VaquamarRe: '66cdaa',\n VXe: 'cd',\n VScEd: 'ba55d3',\n VpurpN: '9370db',\n VsHgYF: '3cb371',\n VUXe: '7b68ee',\n VsprRggYF: 'fa9a',\n VQe: '48d1cc',\n VviTetYd: 'c71585',\n midnightXe: '191970',\n mRtcYam: 'f5fffa',\n mistyPse: 'ffe4e1',\n moccasR: 'ffe4b5',\n navajowEte: 'ffdead',\n navy: '80',\n Tdlace: 'fdf5e6',\n Tive: '808000',\n TivedBb: '6b8e23',\n Sange: 'ffa500',\n SangeYd: 'ff4500',\n ScEd: 'da70d6',\n pOegTMnPd: 'eee8aa',\n pOegYF: '98fb98',\n pOeQe: 'afeeee',\n pOeviTetYd: 'db7093',\n papayawEp: 'ffefd5',\n pHKpuff: 'ffdab9',\n peru: 'cd853f',\n pRk: 'ffc0cb',\n plum: 'dda0dd',\n powMrXe: 'b0e0e6',\n purpN: '800080',\n YbeccapurpN: '663399',\n Yd: 'ff0000',\n Psybrown: 'bc8f8f',\n PyOXe: '4169e1',\n saddNbPwn: '8b4513',\n sOmon: 'fa8072',\n sandybPwn: 'f4a460',\n sHgYF: '2e8b57',\n sHshell: 'fff5ee',\n siFna: 'a0522d',\n silver: 'c0c0c0',\n skyXe: '87ceeb',\n UXe: '6a5acd',\n UWay: '708090',\n UgYy: '708090',\n snow: 'fffafa',\n sprRggYF: 'ff7f',\n stAlXe: '4682b4',\n tan: 'd2b48c',\n teO: '8080',\n tEstN: 'd8bfd8',\n tomato: 'ff6347',\n Qe: '40e0d0',\n viTet: 'ee82ee',\n JHt: 'f5deb3',\n wEte: 'ffffff',\n wEtesmoke: 'f5f5f5',\n Lw: 'ffff00',\n LwgYF: '9acd32'\n};\nfunction unpack() {\n const unpacked = {};\n const keys = Object.keys(names$1);\n const tkeys = Object.keys(map);\n let i, j, k, ok, nk;\n for (i = 0; i < keys.length; i++) {\n ok = nk = keys[i];\n for (j = 0; j < tkeys.length; j++) {\n k = tkeys[j];\n nk = nk.replace(k, map[k]);\n }\n k = parseInt(names$1[ok], 16);\n unpacked[nk] = [k >> 16 & 0xFF, k >> 8 & 0xFF, k & 0xFF];\n }\n return unpacked;\n}\n\nlet names;\nfunction nameParse(str) {\n if (!names) {\n names = unpack();\n names.transparent = [0, 0, 0, 0];\n }\n const a = names[str.toLowerCase()];\n return a && {\n r: a[0],\n g: a[1],\n b: a[2],\n a: a.length === 4 ? a[3] : 255\n };\n}\n\nconst RGB_RE = /^rgba?\\(\\s*([-+.\\d]+)(%)?[\\s,]+([-+.e\\d]+)(%)?[\\s,]+([-+.e\\d]+)(%)?(?:[\\s,/]+([-+.e\\d]+)(%)?)?\\s*\\)$/;\nfunction rgbParse(str) {\n const m = RGB_RE.exec(str);\n let a = 255;\n let r, g, b;\n if (!m) {\n return;\n }\n if (m[7] !== r) {\n const v = +m[7];\n a = m[8] ? p2b(v) : lim(v * 255, 0, 255);\n }\n r = +m[1];\n g = +m[3];\n b = +m[5];\n r = 255 & (m[2] ? p2b(r) : lim(r, 0, 255));\n g = 255 & (m[4] ? p2b(g) : lim(g, 0, 255));\n b = 255 & (m[6] ? p2b(b) : lim(b, 0, 255));\n return {\n r: r,\n g: g,\n b: b,\n a: a\n };\n}\nfunction rgbString(v) {\n return v && (\n v.a < 255\n ? `rgba(${v.r}, ${v.g}, ${v.b}, ${b2n(v.a)})`\n : `rgb(${v.r}, ${v.g}, ${v.b})`\n );\n}\n\nconst to = v => v <= 0.0031308 ? v * 12.92 : Math.pow(v, 1.0 / 2.4) * 1.055 - 0.055;\nconst from = v => v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);\nfunction interpolate(rgb1, rgb2, t) {\n const r = from(b2n(rgb1.r));\n const g = from(b2n(rgb1.g));\n const b = from(b2n(rgb1.b));\n return {\n r: n2b(to(r + t * (from(b2n(rgb2.r)) - r))),\n g: n2b(to(g + t * (from(b2n(rgb2.g)) - g))),\n b: n2b(to(b + t * (from(b2n(rgb2.b)) - b))),\n a: rgb1.a + t * (rgb2.a - rgb1.a)\n };\n}\n\nfunction modHSL(v, i, ratio) {\n if (v) {\n let tmp = rgb2hsl(v);\n tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1));\n tmp = hsl2rgb(tmp);\n v.r = tmp[0];\n v.g = tmp[1];\n v.b = tmp[2];\n }\n}\nfunction clone(v, proto) {\n return v ? Object.assign(proto || {}, v) : v;\n}\nfunction fromObject(input) {\n var v = {r: 0, g: 0, b: 0, a: 255};\n if (Array.isArray(input)) {\n if (input.length >= 3) {\n v = {r: input[0], g: input[1], b: input[2], a: 255};\n if (input.length > 3) {\n v.a = n2b(input[3]);\n }\n }\n } else {\n v = clone(input, {r: 0, g: 0, b: 0, a: 1});\n v.a = n2b(v.a);\n }\n return v;\n}\nfunction functionParse(str) {\n if (str.charAt(0) === 'r') {\n return rgbParse(str);\n }\n return hueParse(str);\n}\nclass Color {\n constructor(input) {\n if (input instanceof Color) {\n return input;\n }\n const type = typeof input;\n let v;\n if (type === 'object') {\n v = fromObject(input);\n } else if (type === 'string') {\n v = hexParse(input) || nameParse(input) || functionParse(input);\n }\n this._rgb = v;\n this._valid = !!v;\n }\n get valid() {\n return this._valid;\n }\n get rgb() {\n var v = clone(this._rgb);\n if (v) {\n v.a = b2n(v.a);\n }\n return v;\n }\n set rgb(obj) {\n this._rgb = fromObject(obj);\n }\n rgbString() {\n return this._valid ? rgbString(this._rgb) : undefined;\n }\n hexString() {\n return this._valid ? hexString(this._rgb) : undefined;\n }\n hslString() {\n return this._valid ? hslString(this._rgb) : undefined;\n }\n mix(color, weight) {\n if (color) {\n const c1 = this.rgb;\n const c2 = color.rgb;\n let w2;\n const p = weight === w2 ? 0.5 : weight;\n const w = 2 * p - 1;\n const a = c1.a - c2.a;\n const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;\n w2 = 1 - w1;\n c1.r = 0xFF & w1 * c1.r + w2 * c2.r + 0.5;\n c1.g = 0xFF & w1 * c1.g + w2 * c2.g + 0.5;\n c1.b = 0xFF & w1 * c1.b + w2 * c2.b + 0.5;\n c1.a = p * c1.a + (1 - p) * c2.a;\n this.rgb = c1;\n }\n return this;\n }\n interpolate(color, t) {\n if (color) {\n this._rgb = interpolate(this._rgb, color._rgb, t);\n }\n return this;\n }\n clone() {\n return new Color(this.rgb);\n }\n alpha(a) {\n this._rgb.a = n2b(a);\n return this;\n }\n clearer(ratio) {\n const rgb = this._rgb;\n rgb.a *= 1 - ratio;\n return this;\n }\n greyscale() {\n const rgb = this._rgb;\n const val = round(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11);\n rgb.r = rgb.g = rgb.b = val;\n return this;\n }\n opaquer(ratio) {\n const rgb = this._rgb;\n rgb.a *= 1 + ratio;\n return this;\n }\n negate() {\n const v = this._rgb;\n v.r = 255 - v.r;\n v.g = 255 - v.g;\n v.b = 255 - v.b;\n return this;\n }\n lighten(ratio) {\n modHSL(this._rgb, 2, ratio);\n return this;\n }\n darken(ratio) {\n modHSL(this._rgb, 2, -ratio);\n return this;\n }\n saturate(ratio) {\n modHSL(this._rgb, 1, ratio);\n return this;\n }\n desaturate(ratio) {\n modHSL(this._rgb, 1, -ratio);\n return this;\n }\n rotate(deg) {\n rotate(this._rgb, deg);\n return this;\n }\n}\n\nfunction index_esm(input) {\n return new Color(input);\n}\n\nexport { Color, b2n, b2p, index_esm as default, hexParse, hexString, hsl2rgb, hslString, hsv2rgb, hueParse, hwb2rgb, lim, n2b, n2p, nameParse, p2b, rgb2hsl, rgbParse, rgbString, rotate, round };\n","import {Color} from '@kurkle/color';\n\nexport function isPatternOrGradient(value: unknown): value is CanvasPattern | CanvasGradient {\n if (value && typeof value === 'object') {\n const type = value.toString();\n return type === '[object CanvasPattern]' || type === '[object CanvasGradient]';\n }\n\n return false;\n}\n\nexport function color(value: CanvasGradient): CanvasGradient;\nexport function color(value: CanvasPattern): CanvasPattern;\nexport function color(\n value:\n | string\n | { r: number; g: number; b: number; a: number }\n | [number, number, number]\n | [number, number, number, number]\n): Color;\nexport function color(value) {\n return isPatternOrGradient(value) ? value : new Color(value);\n}\n\nexport function getHoverColor(value: CanvasGradient): CanvasGradient;\nexport function getHoverColor(value: CanvasPattern): CanvasPattern;\nexport function getHoverColor(value: string): string;\nexport function getHoverColor(value) {\n return isPatternOrGradient(value)\n ? value\n : new Color(value).saturate(0.5).darken(0.1).hexString();\n}\n","const numbers = ['x', 'y', 'borderWidth', 'radius', 'tension'];\nconst colors = ['color', 'borderColor', 'backgroundColor'];\n\nexport function applyAnimationsDefaults(defaults) {\n defaults.set('animation', {\n delay: undefined,\n duration: 1000,\n easing: 'easeOutQuart',\n fn: undefined,\n from: undefined,\n loop: undefined,\n to: undefined,\n type: undefined,\n });\n\n defaults.describe('animation', {\n _fallback: false,\n _indexable: false,\n _scriptable: (name) => name !== 'onProgress' && name !== 'onComplete' && name !== 'fn',\n });\n\n defaults.set('animations', {\n colors: {\n type: 'color',\n properties: colors\n },\n numbers: {\n type: 'number',\n properties: numbers\n },\n });\n\n defaults.describe('animations', {\n _fallback: 'animation',\n });\n\n defaults.set('transitions', {\n active: {\n animation: {\n duration: 400\n }\n },\n resize: {\n animation: {\n duration: 0\n }\n },\n show: {\n animations: {\n colors: {\n from: 'transparent'\n },\n visible: {\n type: 'boolean',\n duration: 0 // show immediately\n },\n }\n },\n hide: {\n animations: {\n colors: {\n to: 'transparent'\n },\n visible: {\n type: 'boolean',\n easing: 'linear',\n fn: v => v | 0 // for keeping the dataset visible all the way through the animation\n },\n }\n }\n });\n}\n","\nconst intlCache = new Map();\n\nfunction getNumberFormat(locale: string, options?: Intl.NumberFormatOptions) {\n options = options || {};\n const cacheKey = locale + JSON.stringify(options);\n let formatter = intlCache.get(cacheKey);\n if (!formatter) {\n formatter = new Intl.NumberFormat(locale, options);\n intlCache.set(cacheKey, formatter);\n }\n return formatter;\n}\n\nexport function formatNumber(num: number, locale: string, options?: Intl.NumberFormatOptions) {\n return getNumberFormat(locale, options).format(num);\n}\n","import {isArray} from '../helpers/helpers.core.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\nimport {log10} from '../helpers/helpers.math.js';\n\n/**\n * Namespace to hold formatters for different types of ticks\n * @namespace Chart.Ticks.formatters\n */\nconst formatters = {\n /**\n * Formatter for value labels\n * @method Chart.Ticks.formatters.values\n * @param value the value to display\n * @return {string|string[]} the label to display\n */\n values(value) {\n return isArray(value) ? /** @type {string[]} */ (value) : '' + value;\n },\n\n /**\n * Formatter for numeric ticks\n * @method Chart.Ticks.formatters.numeric\n * @param tickValue {number} the value to be formatted\n * @param index {number} the position of the tickValue parameter in the ticks array\n * @param ticks {object[]} the list of ticks being converted\n * @return {string} string representation of the tickValue parameter\n */\n numeric(tickValue, index, ticks) {\n if (tickValue === 0) {\n return '0'; // never show decimal places for 0\n }\n\n const locale = this.chart.options.locale;\n let notation;\n let delta = tickValue; // This is used when there are less than 2 ticks as the tick interval.\n\n if (ticks.length > 1) {\n // all ticks are small or there huge numbers; use scientific notation\n const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));\n if (maxTick < 1e-4 || maxTick > 1e+15) {\n notation = 'scientific';\n }\n\n delta = calculateDelta(tickValue, ticks);\n }\n\n const logDelta = log10(Math.abs(delta));\n\n // When datasets have values approaching Number.MAX_VALUE, the tick calculations might result in\n // infinity and eventually NaN. Passing NaN for minimumFractionDigits or maximumFractionDigits\n // will make the number formatter throw. So instead we check for isNaN and use a fallback value.\n //\n // toFixed has a max of 20 decimal places\n const numDecimal = isNaN(logDelta) ? 1 : Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);\n\n const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal};\n Object.assign(options, this.options.ticks.format);\n\n return formatNumber(tickValue, locale, options);\n },\n\n\n /**\n * Formatter for logarithmic ticks\n * @method Chart.Ticks.formatters.logarithmic\n * @param tickValue {number} the value to be formatted\n * @param index {number} the position of the tickValue parameter in the ticks array\n * @param ticks {object[]} the list of ticks being converted\n * @return {string} string representation of the tickValue parameter\n */\n logarithmic(tickValue, index, ticks) {\n if (tickValue === 0) {\n return '0';\n }\n const remain = ticks[index].significand || (tickValue / (Math.pow(10, Math.floor(log10(tickValue)))));\n if ([1, 2, 3, 5, 10, 15].includes(remain) || index > 0.8 * ticks.length) {\n return formatters.numeric.call(this, tickValue, index, ticks);\n }\n return '';\n }\n\n};\n\n\nfunction calculateDelta(tickValue, ticks) {\n // Figure out how many digits to show\n // The space between the first two ticks might be smaller than normal spacing\n let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;\n\n // If we have a number like 2.5 as the delta, figure out how many decimal places we need\n if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) {\n // not an integer\n delta = tickValue - Math.floor(tickValue);\n }\n return delta;\n}\n\n/**\n * Namespace to hold static tick generation functions\n * @namespace Chart.Ticks\n */\nexport default {formatters};\n","import {getHoverColor} from '../helpers/helpers.color.js';\nimport {isObject, merge, valueOrDefault} from '../helpers/helpers.core.js';\nimport {applyAnimationsDefaults} from './core.animations.defaults.js';\nimport {applyLayoutsDefaults} from './core.layouts.defaults.js';\nimport {applyScaleDefaults} from './core.scale.defaults.js';\n\nexport const overrides = Object.create(null);\nexport const descriptors = Object.create(null);\n\n/**\n * @param {object} node\n * @param {string} key\n * @return {object}\n */\nfunction getScope(node, key) {\n if (!key) {\n return node;\n }\n const keys = key.split('.');\n for (let i = 0, n = keys.length; i < n; ++i) {\n const k = keys[i];\n node = node[k] || (node[k] = Object.create(null));\n }\n return node;\n}\n\nfunction set(root, scope, values) {\n if (typeof scope === 'string') {\n return merge(getScope(root, scope), values);\n }\n return merge(getScope(root, ''), scope);\n}\n\n/**\n * Please use the module's default export which provides a singleton instance\n * Note: class is exported for typedoc\n */\nexport class Defaults {\n constructor(_descriptors, _appliers) {\n this.animation = undefined;\n this.backgroundColor = 'rgba(0,0,0,0.1)';\n this.borderColor = 'rgba(0,0,0,0.1)';\n this.color = '#666';\n this.datasets = {};\n this.devicePixelRatio = (context) => context.chart.platform.getDevicePixelRatio();\n this.elements = {};\n this.events = [\n 'mousemove',\n 'mouseout',\n 'click',\n 'touchstart',\n 'touchmove'\n ];\n this.font = {\n family: \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\",\n size: 12,\n style: 'normal',\n lineHeight: 1.2,\n weight: null\n };\n this.hover = {};\n this.hoverBackgroundColor = (ctx, options) => getHoverColor(options.backgroundColor);\n this.hoverBorderColor = (ctx, options) => getHoverColor(options.borderColor);\n this.hoverColor = (ctx, options) => getHoverColor(options.color);\n this.indexAxis = 'x';\n this.interaction = {\n mode: 'nearest',\n intersect: true,\n includeInvisible: false\n };\n this.maintainAspectRatio = true;\n this.onHover = null;\n this.onClick = null;\n this.parsing = true;\n this.plugins = {};\n this.responsive = true;\n this.scale = undefined;\n this.scales = {};\n this.showLine = true;\n this.drawActiveElementsOnTop = true;\n\n this.describe(_descriptors);\n this.apply(_appliers);\n }\n\n /**\n\t * @param {string|object} scope\n\t * @param {object} [values]\n\t */\n set(scope, values) {\n return set(this, scope, values);\n }\n\n /**\n\t * @param {string} scope\n\t */\n get(scope) {\n return getScope(this, scope);\n }\n\n /**\n\t * @param {string|object} scope\n\t * @param {object} [values]\n\t */\n describe(scope, values) {\n return set(descriptors, scope, values);\n }\n\n override(scope, values) {\n return set(overrides, scope, values);\n }\n\n /**\n\t * Routes the named defaults to fallback to another scope/name.\n\t * This routing is useful when those target values, like defaults.color, are changed runtime.\n\t * If the values would be copied, the runtime change would not take effect. By routing, the\n\t * fallback is evaluated at each access, so its always up to date.\n\t *\n\t * Example:\n\t *\n\t * \tdefaults.route('elements.arc', 'backgroundColor', '', 'color')\n\t * - reads the backgroundColor from defaults.color when undefined locally\n\t *\n\t * @param {string} scope Scope this route applies to.\n\t * @param {string} name Property name that should be routed to different namespace when not defined here.\n\t * @param {string} targetScope The namespace where those properties should be routed to.\n\t * Empty string ('') is the root of defaults.\n\t * @param {string} targetName The target name in the target scope the property should be routed to.\n\t */\n route(scope, name, targetScope, targetName) {\n const scopeObject = getScope(this, scope);\n const targetScopeObject = getScope(this, targetScope);\n const privateName = '_' + name;\n\n Object.defineProperties(scopeObject, {\n // A private property is defined to hold the actual value, when this property is set in its scope (set in the setter)\n [privateName]: {\n value: scopeObject[name],\n writable: true\n },\n // The actual property is defined as getter/setter so we can do the routing when value is not locally set.\n [name]: {\n enumerable: true,\n get() {\n const local = this[privateName];\n const target = targetScopeObject[targetName];\n if (isObject(local)) {\n return Object.assign({}, target, local);\n }\n return valueOrDefault(local, target);\n },\n set(value) {\n this[privateName] = value;\n }\n }\n });\n }\n\n apply(appliers) {\n appliers.forEach((apply) => apply(this));\n }\n}\n\n// singleton instance\nexport default /* #__PURE__ */ new Defaults({\n _scriptable: (name) => !name.startsWith('on'),\n _indexable: (name) => name !== 'events',\n hover: {\n _fallback: 'interaction'\n },\n interaction: {\n _scriptable: false,\n _indexable: false,\n }\n}, [applyAnimationsDefaults, applyLayoutsDefaults, applyScaleDefaults]);\n","export function applyLayoutsDefaults(defaults) {\n defaults.set('layout', {\n autoPadding: true,\n padding: {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n }\n });\n}\n","import Ticks from './core.ticks.js';\n\nexport function applyScaleDefaults(defaults) {\n defaults.set('scale', {\n display: true,\n offset: false,\n reverse: false,\n beginAtZero: false,\n\n /**\n * Scale boundary strategy (bypassed by min/max time options)\n * - `data`: make sure data are fully visible, ticks outside are removed\n * - `ticks`: make sure ticks are fully visible, data outside are truncated\n * @see https://github.com/chartjs/Chart.js/pull/4556\n * @since 3.0.0\n */\n bounds: 'ticks',\n\n clip: true,\n\n /**\n * Addition grace added to max and reduced from min data value.\n * @since 3.0.0\n */\n grace: 0,\n\n // grid line settings\n grid: {\n display: true,\n lineWidth: 1,\n drawOnChartArea: true,\n drawTicks: true,\n tickLength: 8,\n tickWidth: (_ctx, options) => options.lineWidth,\n tickColor: (_ctx, options) => options.color,\n offset: false,\n },\n\n border: {\n display: true,\n dash: [],\n dashOffset: 0.0,\n width: 1\n },\n\n // scale title\n title: {\n // display property\n display: false,\n\n // actual label\n text: '',\n\n // top/bottom padding\n padding: {\n top: 4,\n bottom: 4\n }\n },\n\n // label settings\n ticks: {\n minRotation: 0,\n maxRotation: 50,\n mirror: false,\n textStrokeWidth: 0,\n textStrokeColor: '',\n padding: 3,\n display: true,\n autoSkip: true,\n autoSkipPadding: 3,\n labelOffset: 0,\n // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.\n callback: Ticks.formatters.values,\n minor: {},\n major: {},\n align: 'center',\n crossAlign: 'near',\n\n showLabelBackdrop: false,\n backdropColor: 'rgba(255, 255, 255, 0.75)',\n backdropPadding: 2,\n }\n });\n\n defaults.route('scale.ticks', 'color', '', 'color');\n defaults.route('scale.grid', 'color', '', 'borderColor');\n defaults.route('scale.border', 'color', '', 'borderColor');\n defaults.route('scale.title', 'color', '', 'color');\n\n defaults.describe('scale', {\n _fallback: false,\n _scriptable: (name) => !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser',\n _indexable: (name) => name !== 'borderDash' && name !== 'tickBorderDash' && name !== 'dash',\n });\n\n defaults.describe('scales', {\n _fallback: 'scale',\n });\n\n defaults.describe('scale.ticks', {\n _scriptable: (name) => name !== 'backdropPadding' && name !== 'callback',\n _indexable: (name) => name !== 'backdropPadding',\n });\n}\n","import type {ChartArea, Scale} from '../types/index.js';\nimport type Chart from '../core/core.controller.js';\nimport type {ChartEvent} from '../types.js';\nimport {INFINITY} from './helpers.math.js';\n\n/**\n * Note: typedefs are auto-exported, so use a made-up `dom` namespace where\n * necessary to avoid duplicates with `export * from './helpers`; see\n * https://github.com/microsoft/TypeScript/issues/46011\n * @typedef { import('../core/core.controller.js').default } dom.Chart\n * @typedef { import('../../types').ChartEvent } ChartEvent\n */\n\n/**\n * @private\n */\nexport function _isDomSupported(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * @private\n */\nexport function _getParentNode(domNode: HTMLCanvasElement): HTMLCanvasElement {\n let parent = domNode.parentNode;\n if (parent && parent.toString() === '[object ShadowRoot]') {\n parent = (parent as ShadowRoot).host;\n }\n return parent as HTMLCanvasElement;\n}\n\n/**\n * convert max-width/max-height values that may be percentages into a number\n * @private\n */\n\nfunction parseMaxStyle(styleValue: string | number, node: HTMLElement, parentProperty: string) {\n let valueInPixels: number;\n if (typeof styleValue === 'string') {\n valueInPixels = parseInt(styleValue, 10);\n\n if (styleValue.indexOf('%') !== -1) {\n // percentage * size in dimension\n valueInPixels = (valueInPixels / 100) * node.parentNode[parentProperty];\n }\n } else {\n valueInPixels = styleValue;\n }\n\n return valueInPixels;\n}\n\nconst getComputedStyle = (element: HTMLElement): CSSStyleDeclaration =>\n element.ownerDocument.defaultView.getComputedStyle(element, null);\n\nexport function getStyle(el: HTMLElement, property: string): string {\n return getComputedStyle(el).getPropertyValue(property);\n}\n\nconst positions = ['top', 'right', 'bottom', 'left'];\nfunction getPositionedStyle(styles: CSSStyleDeclaration, style: string, suffix?: string): ChartArea {\n const result = {} as ChartArea;\n suffix = suffix ? '-' + suffix : '';\n for (let i = 0; i < 4; i++) {\n const pos = positions[i];\n result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0;\n }\n result.width = result.left + result.right;\n result.height = result.top + result.bottom;\n return result;\n}\n\nconst useOffsetPos = (x: number, y: number, target: HTMLElement | EventTarget) =>\n (x > 0 || y > 0) && (!target || !(target as HTMLElement).shadowRoot);\n\n/**\n * @param e\n * @param canvas\n * @returns Canvas position\n */\nfunction getCanvasPosition(\n e: Event | TouchEvent | MouseEvent,\n canvas: HTMLCanvasElement\n): {\n x: number;\n y: number;\n box: boolean;\n } {\n const touches = (e as TouchEvent).touches;\n const source = (touches && touches.length ? touches[0] : e) as MouseEvent;\n const {offsetX, offsetY} = source as MouseEvent;\n let box = false;\n let x, y;\n if (useOffsetPos(offsetX, offsetY, e.target)) {\n x = offsetX;\n y = offsetY;\n } else {\n const rect = canvas.getBoundingClientRect();\n x = source.clientX - rect.left;\n y = source.clientY - rect.top;\n box = true;\n }\n return {x, y, box};\n}\n\n/**\n * Gets an event's x, y coordinates, relative to the chart area\n * @param event\n * @param chart\n * @returns x and y coordinates of the event\n */\n\nexport function getRelativePosition(\n event: Event | ChartEvent | TouchEvent | MouseEvent,\n chart: Chart\n): { x: number; y: number } {\n if ('native' in event) {\n return event;\n }\n\n const {canvas, currentDevicePixelRatio} = chart;\n const style = getComputedStyle(canvas);\n const borderBox = style.boxSizing === 'border-box';\n const paddings = getPositionedStyle(style, 'padding');\n const borders = getPositionedStyle(style, 'border', 'width');\n const {x, y, box} = getCanvasPosition(event, canvas);\n const xOffset = paddings.left + (box && borders.left);\n const yOffset = paddings.top + (box && borders.top);\n\n let {width, height} = chart;\n if (borderBox) {\n width -= paddings.width + borders.width;\n height -= paddings.height + borders.height;\n }\n return {\n x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio),\n y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio)\n };\n}\n\nfunction getContainerSize(canvas: HTMLCanvasElement, width: number, height: number): Partial {\n let maxWidth: number, maxHeight: number;\n\n if (width === undefined || height === undefined) {\n const container = _getParentNode(canvas);\n if (!container) {\n width = canvas.clientWidth;\n height = canvas.clientHeight;\n } else {\n const rect = container.getBoundingClientRect(); // this is the border box of the container\n const containerStyle = getComputedStyle(container);\n const containerBorder = getPositionedStyle(containerStyle, 'border', 'width');\n const containerPadding = getPositionedStyle(containerStyle, 'padding');\n width = rect.width - containerPadding.width - containerBorder.width;\n height = rect.height - containerPadding.height - containerBorder.height;\n maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth');\n maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight');\n }\n }\n return {\n width,\n height,\n maxWidth: maxWidth || INFINITY,\n maxHeight: maxHeight || INFINITY\n };\n}\n\nconst round1 = (v: number) => Math.round(v * 10) / 10;\n\n// eslint-disable-next-line complexity\nexport function getMaximumSize(\n canvas: HTMLCanvasElement,\n bbWidth?: number,\n bbHeight?: number,\n aspectRatio?: number\n): { width: number; height: number } {\n const style = getComputedStyle(canvas);\n const margins = getPositionedStyle(style, 'margin');\n const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY;\n const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY;\n const containerSize = getContainerSize(canvas, bbWidth, bbHeight);\n let {width, height} = containerSize;\n\n if (style.boxSizing === 'content-box') {\n const borders = getPositionedStyle(style, 'border', 'width');\n const paddings = getPositionedStyle(style, 'padding');\n width -= paddings.width + borders.width;\n height -= paddings.height + borders.height;\n }\n width = Math.max(0, width - margins.width);\n height = Math.max(0, aspectRatio ? width / aspectRatio : height - margins.height);\n width = round1(Math.min(width, maxWidth, containerSize.maxWidth));\n height = round1(Math.min(height, maxHeight, containerSize.maxHeight));\n if (width && !height) {\n // https://github.com/chartjs/Chart.js/issues/4659\n // If the canvas has width, but no height, default to aspectRatio of 2 (canvas default)\n height = round1(width / 2);\n }\n\n const maintainHeight = bbWidth !== undefined || bbHeight !== undefined;\n\n if (maintainHeight && aspectRatio && containerSize.height && height > containerSize.height) {\n height = containerSize.height;\n width = round1(Math.floor(height * aspectRatio));\n }\n\n return {width, height};\n}\n\n/**\n * @param chart\n * @param forceRatio\n * @param forceStyle\n * @returns True if the canvas context size or transformation has changed.\n */\nexport function retinaScale(\n chart: Chart,\n forceRatio: number,\n forceStyle?: boolean\n): boolean | void {\n const pixelRatio = forceRatio || 1;\n const deviceHeight = Math.floor(chart.height * pixelRatio);\n const deviceWidth = Math.floor(chart.width * pixelRatio);\n\n chart.height = Math.floor(chart.height);\n chart.width = Math.floor(chart.width);\n\n const canvas = chart.canvas;\n\n // If no style has been set on the canvas, the render size is used as display size,\n // making the chart visually bigger, so let's enforce it to the \"correct\" values.\n // See https://github.com/chartjs/Chart.js/issues/3575\n if (canvas.style && (forceStyle || (!canvas.style.height && !canvas.style.width))) {\n canvas.style.height = `${chart.height}px`;\n canvas.style.width = `${chart.width}px`;\n }\n\n if (chart.currentDevicePixelRatio !== pixelRatio\n || canvas.height !== deviceHeight\n || canvas.width !== deviceWidth) {\n chart.currentDevicePixelRatio = pixelRatio;\n canvas.height = deviceHeight;\n canvas.width = deviceWidth;\n chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);\n return true;\n }\n return false;\n}\n\n/**\n * Detects support for options object argument in addEventListener.\n * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support\n * @private\n */\nexport const supportsEventListenerOptions = (function() {\n let passiveSupported = false;\n try {\n const options = {\n get passive() { // This function will be called when the browser attempts to access the passive property.\n passiveSupported = true;\n return false;\n }\n } as EventListenerOptions;\n\n if (_isDomSupported()) {\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n }\n } catch (e) {\n // continue regardless of error\n }\n return passiveSupported;\n}());\n\n/**\n * The \"used\" size is the final value of a dimension property after all calculations have\n * been performed. This method uses the computed style of `element` but returns undefined\n * if the computed style is not expressed in pixels. That can happen in some cases where\n * `element` has a size relative to its parent and this last one is not yet displayed,\n * for example because of `display: none` on a parent node.\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value\n * @returns Size in pixels or undefined if unknown.\n */\n\nexport function readUsedSize(\n element: HTMLElement,\n property: 'width' | 'height'\n): number | undefined {\n const value = getStyle(element, property);\n const matches = value && value.match(/^(\\d+)(\\.\\d+)?px$/);\n return matches ? +matches[1] : undefined;\n}\n","import type {\n Chart,\n Point,\n FontSpec,\n CanvasFontSpec,\n PointStyle,\n RenderTextOpts,\n BackdropOptions\n} from '../types/index.js';\nimport type {\n TRBL,\n SplinePoint,\n RoundedRect,\n TRBLCorners\n} from '../types/geometric.js';\nimport {isArray, isNullOrUndef} from './helpers.core.js';\nimport {PI, TAU, HALF_PI, QUARTER_PI, TWO_THIRDS_PI, RAD_PER_DEG} from './helpers.math.js';\n\n/**\n * Converts the given font object into a CSS font string.\n * @param font - A font object.\n * @return The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font\n * @private\n */\nexport function toFontString(font: FontSpec) {\n if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) {\n return null;\n }\n\n return (font.style ? font.style + ' ' : '')\n\t\t+ (font.weight ? font.weight + ' ' : '')\n\t\t+ font.size + 'px '\n\t\t+ font.family;\n}\n\n/**\n * @private\n */\nexport function _measureText(\n ctx: CanvasRenderingContext2D,\n data: Record,\n gc: string[],\n longest: number,\n string: string\n) {\n let textWidth = data[string];\n if (!textWidth) {\n textWidth = data[string] = ctx.measureText(string).width;\n gc.push(string);\n }\n if (textWidth > longest) {\n longest = textWidth;\n }\n return longest;\n}\n\ntype Thing = string | undefined | null\ntype Things = (Thing | Thing[])[]\n\n/**\n * @private\n */\n// eslint-disable-next-line complexity\nexport function _longestText(\n ctx: CanvasRenderingContext2D,\n font: string,\n arrayOfThings: Things,\n cache?: {data?: Record, garbageCollect?: string[], font?: string}\n) {\n cache = cache || {};\n let data = cache.data = cache.data || {};\n let gc = cache.garbageCollect = cache.garbageCollect || [];\n\n if (cache.font !== font) {\n data = cache.data = {};\n gc = cache.garbageCollect = [];\n cache.font = font;\n }\n\n ctx.save();\n\n ctx.font = font;\n let longest = 0;\n const ilen = arrayOfThings.length;\n let i: number, j: number, jlen: number, thing: Thing | Thing[], nestedThing: Thing | Thing[];\n for (i = 0; i < ilen; i++) {\n thing = arrayOfThings[i];\n\n // Undefined strings and arrays should not be measured\n if (thing !== undefined && thing !== null && !isArray(thing)) {\n longest = _measureText(ctx, data, gc, longest, thing);\n } else if (isArray(thing)) {\n // if it is an array lets measure each element\n // to do maybe simplify this function a bit so we can do this more recursively?\n for (j = 0, jlen = thing.length; j < jlen; j++) {\n nestedThing = thing[j];\n // Undefined strings and arrays should not be measured\n if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) {\n longest = _measureText(ctx, data, gc, longest, nestedThing);\n }\n }\n }\n }\n\n ctx.restore();\n\n const gcLen = gc.length / 2;\n if (gcLen > arrayOfThings.length) {\n for (i = 0; i < gcLen; i++) {\n delete data[gc[i]];\n }\n gc.splice(0, gcLen);\n }\n return longest;\n}\n\n/**\n * Returns the aligned pixel value to avoid anti-aliasing blur\n * @param chart - The chart instance.\n * @param pixel - A pixel value.\n * @param width - The width of the element.\n * @returns The aligned pixel value.\n * @private\n */\nexport function _alignPixel(chart: Chart, pixel: number, width: number) {\n const devicePixelRatio = chart.currentDevicePixelRatio;\n const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0;\n return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;\n}\n\n/**\n * Clears the entire canvas.\n */\nexport function clearCanvas(canvas: HTMLCanvasElement, ctx?: CanvasRenderingContext2D) {\n ctx = ctx || canvas.getContext('2d');\n\n ctx.save();\n // canvas.width and canvas.height do not consider the canvas transform,\n // while clearRect does\n ctx.resetTransform();\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n}\n\nexport interface DrawPointOptions {\n pointStyle: PointStyle;\n rotation?: number;\n radius: number;\n borderWidth: number;\n}\n\nexport function drawPoint(\n ctx: CanvasRenderingContext2D,\n options: DrawPointOptions,\n x: number,\n y: number\n) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n drawPointLegend(ctx, options, x, y, null);\n}\n\n// eslint-disable-next-line complexity\nexport function drawPointLegend(\n ctx: CanvasRenderingContext2D,\n options: DrawPointOptions,\n x: number,\n y: number,\n w: number\n) {\n let type: string, xOffset: number, yOffset: number, size: number, cornerRadius: number, width: number, xOffsetW: number, yOffsetW: number;\n const style = options.pointStyle;\n const rotation = options.rotation;\n const radius = options.radius;\n let rad = (rotation || 0) * RAD_PER_DEG;\n\n if (style && typeof style === 'object') {\n type = style.toString();\n if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {\n ctx.save();\n ctx.translate(x, y);\n ctx.rotate(rad);\n ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);\n ctx.restore();\n return;\n }\n }\n\n if (isNaN(radius) || radius <= 0) {\n return;\n }\n\n ctx.beginPath();\n\n switch (style) {\n // Default includes circle\n default:\n if (w) {\n ctx.ellipse(x, y, w / 2, radius, 0, 0, TAU);\n } else {\n ctx.arc(x, y, radius, 0, TAU);\n }\n ctx.closePath();\n break;\n case 'triangle':\n width = w ? w / 2 : radius;\n ctx.moveTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n rad += TWO_THIRDS_PI;\n ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n rad += TWO_THIRDS_PI;\n ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n ctx.closePath();\n break;\n case 'rectRounded':\n // NOTE: the rounded rect implementation changed to use `arc` instead of\n // `quadraticCurveTo` since it generates better results when rect is\n // almost a circle. 0.516 (instead of 0.5) produces results with visually\n // closer proportion to the previous impl and it is inscribed in the\n // circle with `radius`. For more details, see the following PRs:\n // https://github.com/chartjs/Chart.js/issues/5597\n // https://github.com/chartjs/Chart.js/issues/5858\n cornerRadius = radius * 0.516;\n size = radius - cornerRadius;\n xOffset = Math.cos(rad + QUARTER_PI) * size;\n xOffsetW = Math.cos(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);\n yOffset = Math.sin(rad + QUARTER_PI) * size;\n yOffsetW = Math.sin(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);\n ctx.arc(x - xOffsetW, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);\n ctx.arc(x + yOffsetW, y - xOffset, cornerRadius, rad - HALF_PI, rad);\n ctx.arc(x + xOffsetW, y + yOffset, cornerRadius, rad, rad + HALF_PI);\n ctx.arc(x - yOffsetW, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);\n ctx.closePath();\n break;\n case 'rect':\n if (!rotation) {\n size = Math.SQRT1_2 * radius;\n width = w ? w / 2 : size;\n ctx.rect(x - width, y - size, 2 * width, 2 * size);\n break;\n }\n rad += QUARTER_PI;\n /* falls through */\n case 'rectRot':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n ctx.closePath();\n break;\n case 'crossRot':\n rad += QUARTER_PI;\n /* falls through */\n case 'cross':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n break;\n case 'star':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n rad += QUARTER_PI;\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n break;\n case 'line':\n xOffset = w ? w / 2 : Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n ctx.moveTo(x - xOffset, y - yOffset);\n ctx.lineTo(x + xOffset, y + yOffset);\n break;\n case 'dash':\n ctx.moveTo(x, y);\n ctx.lineTo(x + Math.cos(rad) * (w ? w / 2 : radius), y + Math.sin(rad) * radius);\n break;\n case false:\n ctx.closePath();\n break;\n }\n\n ctx.fill();\n if (options.borderWidth > 0) {\n ctx.stroke();\n }\n}\n\n/**\n * Returns true if the point is inside the rectangle\n * @param point - The point to test\n * @param area - The rectangle\n * @param margin - allowed margin\n * @private\n */\nexport function _isPointInArea(\n point: Point,\n area: TRBL,\n margin?: number\n) {\n margin = margin || 0.5; // margin - default is to match rounded decimals\n\n return !area || (point && point.x > area.left - margin && point.x < area.right + margin &&\n\t\tpoint.y > area.top - margin && point.y < area.bottom + margin);\n}\n\nexport function clipArea(ctx: CanvasRenderingContext2D, area: TRBL) {\n ctx.save();\n ctx.beginPath();\n ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);\n ctx.clip();\n}\n\nexport function unclipArea(ctx: CanvasRenderingContext2D) {\n ctx.restore();\n}\n\n/**\n * @private\n */\nexport function _steppedLineTo(\n ctx: CanvasRenderingContext2D,\n previous: Point,\n target: Point,\n flip?: boolean,\n mode?: string\n) {\n if (!previous) {\n return ctx.lineTo(target.x, target.y);\n }\n if (mode === 'middle') {\n const midpoint = (previous.x + target.x) / 2.0;\n ctx.lineTo(midpoint, previous.y);\n ctx.lineTo(midpoint, target.y);\n } else if (mode === 'after' !== !!flip) {\n ctx.lineTo(previous.x, target.y);\n } else {\n ctx.lineTo(target.x, previous.y);\n }\n ctx.lineTo(target.x, target.y);\n}\n\n/**\n * @private\n */\nexport function _bezierCurveTo(\n ctx: CanvasRenderingContext2D,\n previous: SplinePoint,\n target: SplinePoint,\n flip?: boolean\n) {\n if (!previous) {\n return ctx.lineTo(target.x, target.y);\n }\n ctx.bezierCurveTo(\n flip ? previous.cp1x : previous.cp2x,\n flip ? previous.cp1y : previous.cp2y,\n flip ? target.cp2x : target.cp1x,\n flip ? target.cp2y : target.cp1y,\n target.x,\n target.y);\n}\n\nfunction setRenderOpts(ctx: CanvasRenderingContext2D, opts: RenderTextOpts) {\n if (opts.translation) {\n ctx.translate(opts.translation[0], opts.translation[1]);\n }\n\n if (!isNullOrUndef(opts.rotation)) {\n ctx.rotate(opts.rotation);\n }\n\n if (opts.color) {\n ctx.fillStyle = opts.color;\n }\n\n if (opts.textAlign) {\n ctx.textAlign = opts.textAlign;\n }\n\n if (opts.textBaseline) {\n ctx.textBaseline = opts.textBaseline;\n }\n}\n\nfunction decorateText(\n ctx: CanvasRenderingContext2D,\n x: number,\n y: number,\n line: string,\n opts: RenderTextOpts\n) {\n if (opts.strikethrough || opts.underline) {\n /**\n * Now that IE11 support has been dropped, we can use more\n * of the TextMetrics object. The actual bounding boxes\n * are unflagged in Chrome, Firefox, Edge, and Safari so they\n * can be safely used.\n * See https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics#Browser_compatibility\n */\n const metrics = ctx.measureText(line);\n const left = x - metrics.actualBoundingBoxLeft;\n const right = x + metrics.actualBoundingBoxRight;\n const top = y - metrics.actualBoundingBoxAscent;\n const bottom = y + metrics.actualBoundingBoxDescent;\n const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom;\n\n ctx.strokeStyle = ctx.fillStyle;\n ctx.beginPath();\n ctx.lineWidth = opts.decorationWidth || 2;\n ctx.moveTo(left, yDecoration);\n ctx.lineTo(right, yDecoration);\n ctx.stroke();\n }\n}\n\nfunction drawBackdrop(ctx: CanvasRenderingContext2D, opts: BackdropOptions) {\n const oldColor = ctx.fillStyle;\n\n ctx.fillStyle = opts.color as string;\n ctx.fillRect(opts.left, opts.top, opts.width, opts.height);\n ctx.fillStyle = oldColor;\n}\n\n/**\n * Render text onto the canvas\n */\nexport function renderText(\n ctx: CanvasRenderingContext2D,\n text: string | string[],\n x: number,\n y: number,\n font: CanvasFontSpec,\n opts: RenderTextOpts = {}\n) {\n const lines = isArray(text) ? text : [text];\n const stroke = opts.strokeWidth > 0 && opts.strokeColor !== '';\n let i: number, line: string;\n\n ctx.save();\n ctx.font = font.string;\n setRenderOpts(ctx, opts);\n\n for (i = 0; i < lines.length; ++i) {\n line = lines[i];\n\n if (opts.backdrop) {\n drawBackdrop(ctx, opts.backdrop);\n }\n\n if (stroke) {\n if (opts.strokeColor) {\n ctx.strokeStyle = opts.strokeColor;\n }\n\n if (!isNullOrUndef(opts.strokeWidth)) {\n ctx.lineWidth = opts.strokeWidth;\n }\n\n ctx.strokeText(line, x, y, opts.maxWidth);\n }\n\n ctx.fillText(line, x, y, opts.maxWidth);\n decorateText(ctx, x, y, line, opts);\n\n y += Number(font.lineHeight);\n }\n\n ctx.restore();\n}\n\n/**\n * Add a path of a rectangle with rounded corners to the current sub-path\n * @param ctx - Context\n * @param rect - Bounding rect\n */\nexport function addRoundedRectPath(\n ctx: CanvasRenderingContext2D,\n rect: RoundedRect & { radius: TRBLCorners }\n) {\n const {x, y, w, h, radius} = rect;\n\n // top left arc\n ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, 1.5 * PI, PI, true);\n\n // line from top left to bottom left\n ctx.lineTo(x, y + h - radius.bottomLeft);\n\n // bottom left arc\n ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true);\n\n // line from bottom left to bottom right\n ctx.lineTo(x + w - radius.bottomRight, y + h);\n\n // bottom right arc\n ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true);\n\n // line from bottom right to top right\n ctx.lineTo(x + w, y + radius.topRight);\n\n // top right arc\n ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true);\n\n // line from top right to top left\n ctx.lineTo(x + radius.topLeft, y);\n}\n","/* eslint-disable @typescript-eslint/no-use-before-define */\nimport type {AnyObject} from '../types/basic.js';\nimport type {ChartMeta} from '../types/index.js';\nimport type {\n ResolverObjectKey,\n ResolverCache,\n ResolverProxy,\n DescriptorDefaults,\n Descriptor,\n ContextCache,\n ContextProxy\n} from './helpers.config.types.js';\nimport {isArray, isFunction, isObject, resolveObjectKey, _capitalize} from './helpers.core.js';\n\nexport * from './helpers.config.types.js';\n\n/**\n * Creates a Proxy for resolving raw values for options.\n * @param scopes - The option scopes to look for values, in resolution order\n * @param prefixes - The prefixes for values, in resolution order.\n * @param rootScopes - The root option scopes\n * @param fallback - Parent scopes fallback\n * @param getTarget - callback for getting the target for changed values\n * @returns Proxy\n * @private\n */\nexport function _createResolver<\n T extends AnyObject[] = AnyObject[],\n R extends AnyObject[] = T\n>(\n scopes: T,\n prefixes = [''],\n rootScopes?: R,\n fallback?: ResolverObjectKey,\n getTarget = () => scopes[0]\n) {\n const finalRootScopes = rootScopes || scopes;\n if (typeof fallback === 'undefined') {\n fallback = _resolve('_fallback', scopes);\n }\n const cache: ResolverCache = {\n [Symbol.toStringTag]: 'Object',\n _cacheable: true,\n _scopes: scopes,\n _rootScopes: finalRootScopes,\n _fallback: fallback,\n _getTarget: getTarget,\n override: (scope: AnyObject) => _createResolver([scope, ...scopes], prefixes, finalRootScopes, fallback),\n };\n return new Proxy(cache, {\n /**\n * A trap for the delete operator.\n */\n deleteProperty(target, prop: string) {\n delete target[prop]; // remove from cache\n delete target._keys; // remove cached keys\n delete scopes[0][prop]; // remove from top level scope\n return true;\n },\n\n /**\n * A trap for getting property values.\n */\n get(target, prop: string) {\n return _cached(target, prop,\n () => _resolveWithPrefixes(prop, prefixes, scopes, target));\n },\n\n /**\n * A trap for Object.getOwnPropertyDescriptor.\n * Also used by Object.hasOwnProperty.\n */\n getOwnPropertyDescriptor(target, prop) {\n return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop);\n },\n\n /**\n * A trap for Object.getPrototypeOf.\n */\n getPrototypeOf() {\n return Reflect.getPrototypeOf(scopes[0]);\n },\n\n /**\n * A trap for the in operator.\n */\n has(target, prop: string) {\n return getKeysFromAllScopes(target).includes(prop);\n },\n\n /**\n * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.\n */\n ownKeys(target) {\n return getKeysFromAllScopes(target);\n },\n\n /**\n * A trap for setting property values.\n */\n set(target, prop: string, value) {\n const storage = target._storage || (target._storage = getTarget());\n target[prop] = storage[prop] = value; // set to top level scope + cache\n delete target._keys; // remove cached keys\n return true;\n }\n }) as ResolverProxy;\n}\n\n/**\n * Returns an Proxy for resolving option values with context.\n * @param proxy - The Proxy returned by `_createResolver`\n * @param context - Context object for scriptable/indexable options\n * @param subProxy - The proxy provided for scriptable options\n * @param descriptorDefaults - Defaults for descriptors\n * @private\n */\nexport function _attachContext<\n T extends AnyObject[] = AnyObject[],\n R extends AnyObject[] = T\n>(\n proxy: ResolverProxy,\n context: AnyObject,\n subProxy?: ResolverProxy,\n descriptorDefaults?: DescriptorDefaults\n) {\n const cache: ContextCache = {\n _cacheable: false,\n _proxy: proxy,\n _context: context,\n _subProxy: subProxy,\n _stack: new Set(),\n _descriptors: _descriptors(proxy, descriptorDefaults),\n setContext: (ctx: AnyObject) => _attachContext(proxy, ctx, subProxy, descriptorDefaults),\n override: (scope: AnyObject) => _attachContext(proxy.override(scope), context, subProxy, descriptorDefaults)\n };\n return new Proxy(cache, {\n /**\n * A trap for the delete operator.\n */\n deleteProperty(target, prop) {\n delete target[prop]; // remove from cache\n delete proxy[prop]; // remove from proxy\n return true;\n },\n\n /**\n * A trap for getting property values.\n */\n get(target, prop: string, receiver) {\n return _cached(target, prop,\n () => _resolveWithContext(target, prop, receiver));\n },\n\n /**\n * A trap for Object.getOwnPropertyDescriptor.\n * Also used by Object.hasOwnProperty.\n */\n getOwnPropertyDescriptor(target, prop) {\n return target._descriptors.allKeys\n ? Reflect.has(proxy, prop) ? {enumerable: true, configurable: true} : undefined\n : Reflect.getOwnPropertyDescriptor(proxy, prop);\n },\n\n /**\n * A trap for Object.getPrototypeOf.\n */\n getPrototypeOf() {\n return Reflect.getPrototypeOf(proxy);\n },\n\n /**\n * A trap for the in operator.\n */\n has(target, prop) {\n return Reflect.has(proxy, prop);\n },\n\n /**\n * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.\n */\n ownKeys() {\n return Reflect.ownKeys(proxy);\n },\n\n /**\n * A trap for setting property values.\n */\n set(target, prop, value) {\n proxy[prop] = value; // set to proxy\n delete target[prop]; // remove from cache\n return true;\n }\n }) as ContextProxy;\n}\n\n/**\n * @private\n */\nexport function _descriptors(\n proxy: ResolverCache,\n defaults: DescriptorDefaults = {scriptable: true, indexable: true}\n): Descriptor {\n const {_scriptable = defaults.scriptable, _indexable = defaults.indexable, _allKeys = defaults.allKeys} = proxy;\n return {\n allKeys: _allKeys,\n scriptable: _scriptable,\n indexable: _indexable,\n isScriptable: isFunction(_scriptable) ? _scriptable : () => _scriptable,\n isIndexable: isFunction(_indexable) ? _indexable : () => _indexable\n };\n}\n\nconst readKey = (prefix: string, name: string) => prefix ? prefix + _capitalize(name) : name;\nconst needsSubResolver = (prop: string, value: unknown) => isObject(value) && prop !== 'adapters' &&\n (Object.getPrototypeOf(value) === null || value.constructor === Object);\n\nfunction _cached(\n target: AnyObject,\n prop: string,\n resolve: () => unknown\n) {\n if (Object.prototype.hasOwnProperty.call(target, prop)) {\n return target[prop];\n }\n\n const value = resolve();\n // cache the resolved value\n target[prop] = value;\n return value;\n}\n\nfunction _resolveWithContext(\n target: ContextCache,\n prop: string,\n receiver: AnyObject\n) {\n const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;\n let value = _proxy[prop]; // resolve from proxy\n\n // resolve with context\n if (isFunction(value) && descriptors.isScriptable(prop)) {\n value = _resolveScriptable(prop, value, target, receiver);\n }\n if (isArray(value) && value.length) {\n value = _resolveArray(prop, value, target, descriptors.isIndexable);\n }\n if (needsSubResolver(prop, value)) {\n // if the resolved value is an object, create a sub resolver for it\n value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors);\n }\n return value;\n}\n\nfunction _resolveScriptable(\n prop: string,\n getValue: (ctx: AnyObject, sub: AnyObject) => unknown,\n target: ContextCache,\n receiver: AnyObject\n) {\n const {_proxy, _context, _subProxy, _stack} = target;\n if (_stack.has(prop)) {\n throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop);\n }\n _stack.add(prop);\n let value = getValue(_context, _subProxy || receiver);\n _stack.delete(prop);\n if (needsSubResolver(prop, value)) {\n // When scriptable option returns an object, create a resolver on that.\n value = createSubResolver(_proxy._scopes, _proxy, prop, value);\n }\n return value;\n}\n\nfunction _resolveArray(\n prop: string,\n value: unknown[],\n target: ContextCache,\n isIndexable: (key: string) => boolean\n) {\n const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;\n\n if (typeof _context.index !== 'undefined' && isIndexable(prop)) {\n return value[_context.index % value.length];\n } else if (isObject(value[0])) {\n // Array of objects, return array or resolvers\n const arr = value;\n const scopes = _proxy._scopes.filter(s => s !== arr);\n value = [];\n for (const item of arr) {\n const resolver = createSubResolver(scopes, _proxy, prop, item);\n value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors));\n }\n }\n return value;\n}\n\nfunction resolveFallback(\n fallback: ResolverObjectKey | ((prop: ResolverObjectKey, value: unknown) => ResolverObjectKey),\n prop: ResolverObjectKey,\n value: unknown\n) {\n return isFunction(fallback) ? fallback(prop, value) : fallback;\n}\n\nconst getScope = (key: ResolverObjectKey, parent: AnyObject) => key === true ? parent\n : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined;\n\nfunction addScopes(\n set: Set,\n parentScopes: AnyObject[],\n key: ResolverObjectKey,\n parentFallback: ResolverObjectKey,\n value: unknown\n) {\n for (const parent of parentScopes) {\n const scope = getScope(key, parent);\n if (scope) {\n set.add(scope);\n const fallback = resolveFallback(scope._fallback, key, value);\n if (typeof fallback !== 'undefined' && fallback !== key && fallback !== parentFallback) {\n // When we reach the descriptor that defines a new _fallback, return that.\n // The fallback will resume to that new scope.\n return fallback;\n }\n } else if (scope === false && typeof parentFallback !== 'undefined' && key !== parentFallback) {\n // Fallback to `false` results to `false`, when falling back to different key.\n // For example `interaction` from `hover` or `plugins.tooltip` and `animation` from `animations`\n return null;\n }\n }\n return false;\n}\n\nfunction createSubResolver(\n parentScopes: AnyObject[],\n resolver: ResolverCache,\n prop: ResolverObjectKey,\n value: unknown\n) {\n const rootScopes = resolver._rootScopes;\n const fallback = resolveFallback(resolver._fallback, prop, value);\n const allScopes = [...parentScopes, ...rootScopes];\n const set = new Set();\n set.add(value);\n let key = addScopesFromKey(set, allScopes, prop, fallback || prop, value);\n if (key === null) {\n return false;\n }\n if (typeof fallback !== 'undefined' && fallback !== prop) {\n key = addScopesFromKey(set, allScopes, fallback, key, value);\n if (key === null) {\n return false;\n }\n }\n return _createResolver(Array.from(set), [''], rootScopes, fallback,\n () => subGetTarget(resolver, prop as string, value));\n}\n\nfunction addScopesFromKey(\n set: Set,\n allScopes: AnyObject[],\n key: ResolverObjectKey,\n fallback: ResolverObjectKey,\n item: unknown\n) {\n while (key) {\n key = addScopes(set, allScopes, key, fallback, item);\n }\n return key;\n}\n\nfunction subGetTarget(\n resolver: ResolverCache,\n prop: string,\n value: unknown\n) {\n const parent = resolver._getTarget();\n if (!(prop in parent)) {\n parent[prop] = {};\n }\n const target = parent[prop];\n if (isArray(target) && isObject(value)) {\n // For array of objects, the object is used to store updated values\n return value;\n }\n return target || {};\n}\n\nfunction _resolveWithPrefixes(\n prop: string,\n prefixes: string[],\n scopes: AnyObject[],\n proxy: ResolverProxy\n) {\n let value: unknown;\n for (const prefix of prefixes) {\n value = _resolve(readKey(prefix, prop), scopes);\n if (typeof value !== 'undefined') {\n return needsSubResolver(prop, value)\n ? createSubResolver(scopes, proxy, prop, value)\n : value;\n }\n }\n}\n\nfunction _resolve(key: string, scopes: AnyObject[]) {\n for (const scope of scopes) {\n if (!scope) {\n continue;\n }\n const value = scope[key];\n if (typeof value !== 'undefined') {\n return value;\n }\n }\n}\n\nfunction getKeysFromAllScopes(target: ResolverCache) {\n let keys = target._keys;\n if (!keys) {\n keys = target._keys = resolveKeysFromAllScopes(target._scopes);\n }\n return keys;\n}\n\nfunction resolveKeysFromAllScopes(scopes: AnyObject[]) {\n const set = new Set();\n for (const scope of scopes) {\n for (const key of Object.keys(scope).filter(k => !k.startsWith('_'))) {\n set.add(key);\n }\n }\n return Array.from(set);\n}\n\nexport function _parseObjectDataRadialScale(\n meta: ChartMeta<'line' | 'scatter'>,\n data: AnyObject[],\n start: number,\n count: number\n) {\n const {iScale} = meta;\n const {key = 'r'} = this._parsing;\n const parsed = new Array<{r: unknown}>(count);\n let i: number, ilen: number, index: number, item: AnyObject;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n r: iScale.parse(resolveObjectKey(item, key), index)\n };\n }\n return parsed;\n}\n","import {almostEquals, distanceBetweenPoints, sign} from './helpers.math.js';\nimport {_isPointInArea} from './helpers.canvas.js';\nimport type {ChartArea} from '../types/index.js';\nimport type {SplinePoint} from '../types/geometric.js';\n\nconst EPSILON = Number.EPSILON || 1e-14;\n\ntype OptionalSplinePoint = SplinePoint | false\nconst getPoint = (points: SplinePoint[], i: number): OptionalSplinePoint => i < points.length && !points[i].skip && points[i];\nconst getValueAxis = (indexAxis: 'x' | 'y') => indexAxis === 'x' ? 'y' : 'x';\n\nexport function splineCurve(\n firstPoint: SplinePoint,\n middlePoint: SplinePoint,\n afterPoint: SplinePoint,\n t: number\n): {\n previous: SplinePoint\n next: SplinePoint\n } {\n // Props to Rob Spencer at scaled innovation for his post on splining between points\n // http://scaledinnovation.com/analytics/splines/aboutSplines.html\n\n // This function must also respect \"skipped\" points\n\n const previous = firstPoint.skip ? middlePoint : firstPoint;\n const current = middlePoint;\n const next = afterPoint.skip ? middlePoint : afterPoint;\n const d01 = distanceBetweenPoints(current, previous);\n const d12 = distanceBetweenPoints(next, current);\n\n let s01 = d01 / (d01 + d12);\n let s12 = d12 / (d01 + d12);\n\n // If all points are the same, s01 & s02 will be inf\n s01 = isNaN(s01) ? 0 : s01;\n s12 = isNaN(s12) ? 0 : s12;\n\n const fa = t * s01; // scaling factor for triangle Ta\n const fb = t * s12;\n\n return {\n previous: {\n x: current.x - fa * (next.x - previous.x),\n y: current.y - fa * (next.y - previous.y)\n },\n next: {\n x: current.x + fb * (next.x - previous.x),\n y: current.y + fb * (next.y - previous.y)\n }\n };\n}\n\n/**\n * Adjust tangents to ensure monotonic properties\n */\nfunction monotoneAdjust(points: SplinePoint[], deltaK: number[], mK: number[]) {\n const pointsLen = points.length;\n\n let alphaK: number, betaK: number, tauK: number, squaredMagnitude: number, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n for (let i = 0; i < pointsLen - 1; ++i) {\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent || !pointAfter) {\n continue;\n }\n\n if (almostEquals(deltaK[i], 0, EPSILON)) {\n mK[i] = mK[i + 1] = 0;\n continue;\n }\n\n alphaK = mK[i] / deltaK[i];\n betaK = mK[i + 1] / deltaK[i];\n squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);\n if (squaredMagnitude <= 9) {\n continue;\n }\n\n tauK = 3 / Math.sqrt(squaredMagnitude);\n mK[i] = alphaK * tauK * deltaK[i];\n mK[i + 1] = betaK * tauK * deltaK[i];\n }\n}\n\nfunction monotoneCompute(points: SplinePoint[], mK: number[], indexAxis: 'x' | 'y' = 'x') {\n const valueAxis = getValueAxis(indexAxis);\n const pointsLen = points.length;\n let delta: number, pointBefore: OptionalSplinePoint, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n\n for (let i = 0; i < pointsLen; ++i) {\n pointBefore = pointCurrent;\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent) {\n continue;\n }\n\n const iPixel = pointCurrent[indexAxis];\n const vPixel = pointCurrent[valueAxis];\n if (pointBefore) {\n delta = (iPixel - pointBefore[indexAxis]) / 3;\n pointCurrent[`cp1${indexAxis}`] = iPixel - delta;\n pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i];\n }\n if (pointAfter) {\n delta = (pointAfter[indexAxis] - iPixel) / 3;\n pointCurrent[`cp2${indexAxis}`] = iPixel + delta;\n pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i];\n }\n }\n}\n\n/**\n * This function calculates Bézier control points in a similar way than |splineCurve|,\n * but preserves monotonicity of the provided data and ensures no local extremums are added\n * between the dataset discrete points due to the interpolation.\n * See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation\n */\nexport function splineCurveMonotone(points: SplinePoint[], indexAxis: 'x' | 'y' = 'x') {\n const valueAxis = getValueAxis(indexAxis);\n const pointsLen = points.length;\n const deltaK: number[] = Array(pointsLen).fill(0);\n const mK: number[] = Array(pointsLen);\n\n // Calculate slopes (deltaK) and initialize tangents (mK)\n let i, pointBefore: OptionalSplinePoint, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n\n for (i = 0; i < pointsLen; ++i) {\n pointBefore = pointCurrent;\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent) {\n continue;\n }\n\n if (pointAfter) {\n const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis];\n\n // In the case of two points that appear at the same x pixel, slopeDeltaX is 0\n deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0;\n }\n mK[i] = !pointBefore ? deltaK[i]\n : !pointAfter ? deltaK[i - 1]\n : (sign(deltaK[i - 1]) !== sign(deltaK[i])) ? 0\n : (deltaK[i - 1] + deltaK[i]) / 2;\n }\n\n monotoneAdjust(points, deltaK, mK);\n\n monotoneCompute(points, mK, indexAxis);\n}\n\nfunction capControlPoint(pt: number, min: number, max: number) {\n return Math.max(Math.min(pt, max), min);\n}\n\nfunction capBezierPoints(points: SplinePoint[], area: ChartArea) {\n let i, ilen, point, inArea, inAreaPrev;\n let inAreaNext = _isPointInArea(points[0], area);\n for (i = 0, ilen = points.length; i < ilen; ++i) {\n inAreaPrev = inArea;\n inArea = inAreaNext;\n inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area);\n if (!inArea) {\n continue;\n }\n point = points[i];\n if (inAreaPrev) {\n point.cp1x = capControlPoint(point.cp1x, area.left, area.right);\n point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom);\n }\n if (inAreaNext) {\n point.cp2x = capControlPoint(point.cp2x, area.left, area.right);\n point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom);\n }\n }\n}\n\n/**\n * @private\n */\nexport function _updateBezierControlPoints(\n points: SplinePoint[],\n options,\n area: ChartArea,\n loop: boolean,\n indexAxis: 'x' | 'y'\n) {\n let i: number, ilen: number, point: SplinePoint, controlPoints: ReturnType;\n\n // Only consider points that are drawn in case the spanGaps option is used\n if (options.spanGaps) {\n points = points.filter((pt) => !pt.skip);\n }\n\n if (options.cubicInterpolationMode === 'monotone') {\n splineCurveMonotone(points, indexAxis);\n } else {\n let prev = loop ? points[points.length - 1] : points[0];\n for (i = 0, ilen = points.length; i < ilen; ++i) {\n point = points[i];\n controlPoints = splineCurve(\n prev,\n point,\n points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen],\n options.tension\n );\n point.cp1x = controlPoints.previous.x;\n point.cp1y = controlPoints.previous.y;\n point.cp2x = controlPoints.next.x;\n point.cp2y = controlPoints.next.y;\n prev = point;\n }\n }\n\n if (options.capBezierPoints) {\n capBezierPoints(points, area);\n }\n}\n","import {PI, TAU, HALF_PI} from './helpers.math.js';\n\nconst atEdge = (t: number) => t === 0 || t === 1;\nconst elasticIn = (t: number, s: number, p: number) => -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p));\nconst elasticOut = (t: number, s: number, p: number) => Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1;\n\n/**\n * Easing functions adapted from Robert Penner's easing equations.\n * @namespace Chart.helpers.easing.effects\n * @see http://www.robertpenner.com/easing/\n */\nconst effects = {\n linear: (t: number) => t,\n\n easeInQuad: (t: number) => t * t,\n\n easeOutQuad: (t: number) => -t * (t - 2),\n\n easeInOutQuad: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t\n : -0.5 * ((--t) * (t - 2) - 1),\n\n easeInCubic: (t: number) => t * t * t,\n\n easeOutCubic: (t: number) => (t -= 1) * t * t + 1,\n\n easeInOutCubic: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t\n : 0.5 * ((t -= 2) * t * t + 2),\n\n easeInQuart: (t: number) => t * t * t * t,\n\n easeOutQuart: (t: number) => -((t -= 1) * t * t * t - 1),\n\n easeInOutQuart: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t * t\n : -0.5 * ((t -= 2) * t * t * t - 2),\n\n easeInQuint: (t: number) => t * t * t * t * t,\n\n easeOutQuint: (t: number) => (t -= 1) * t * t * t * t + 1,\n\n easeInOutQuint: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t * t * t\n : 0.5 * ((t -= 2) * t * t * t * t + 2),\n\n easeInSine: (t: number) => -Math.cos(t * HALF_PI) + 1,\n\n easeOutSine: (t: number) => Math.sin(t * HALF_PI),\n\n easeInOutSine: (t: number) => -0.5 * (Math.cos(PI * t) - 1),\n\n easeInExpo: (t: number) => (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)),\n\n easeOutExpo: (t: number) => (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1,\n\n easeInOutExpo: (t: number) => atEdge(t) ? t : t < 0.5\n ? 0.5 * Math.pow(2, 10 * (t * 2 - 1))\n : 0.5 * (-Math.pow(2, -10 * (t * 2 - 1)) + 2),\n\n easeInCirc: (t: number) => (t >= 1) ? t : -(Math.sqrt(1 - t * t) - 1),\n\n easeOutCirc: (t: number) => Math.sqrt(1 - (t -= 1) * t),\n\n easeInOutCirc: (t: number) => ((t /= 0.5) < 1)\n ? -0.5 * (Math.sqrt(1 - t * t) - 1)\n : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1),\n\n easeInElastic: (t: number) => atEdge(t) ? t : elasticIn(t, 0.075, 0.3),\n\n easeOutElastic: (t: number) => atEdge(t) ? t : elasticOut(t, 0.075, 0.3),\n\n easeInOutElastic(t: number) {\n const s = 0.1125;\n const p = 0.45;\n return atEdge(t) ? t :\n t < 0.5\n ? 0.5 * elasticIn(t * 2, s, p)\n : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p);\n },\n\n easeInBack(t: number) {\n const s = 1.70158;\n return t * t * ((s + 1) * t - s);\n },\n\n easeOutBack(t: number) {\n const s = 1.70158;\n return (t -= 1) * t * ((s + 1) * t + s) + 1;\n },\n\n easeInOutBack(t: number) {\n let s = 1.70158;\n if ((t /= 0.5) < 1) {\n return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));\n }\n return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);\n },\n\n easeInBounce: (t: number) => 1 - effects.easeOutBounce(1 - t),\n\n easeOutBounce(t: number) {\n const m = 7.5625;\n const d = 2.75;\n if (t < (1 / d)) {\n return m * t * t;\n }\n if (t < (2 / d)) {\n return m * (t -= (1.5 / d)) * t + 0.75;\n }\n if (t < (2.5 / d)) {\n return m * (t -= (2.25 / d)) * t + 0.9375;\n }\n return m * (t -= (2.625 / d)) * t + 0.984375;\n },\n\n easeInOutBounce: (t: number) => (t < 0.5)\n ? effects.easeInBounce(t * 2) * 0.5\n : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5,\n} as const;\n\nexport type EasingFunction = keyof typeof effects\n\nexport default effects;\n","import type {Point, SplinePoint} from '../types/geometric.js';\n\n/**\n * @private\n */\nexport function _pointInLine(p1: Point, p2: Point, t: number, mode?) { // eslint-disable-line @typescript-eslint/no-unused-vars\n return {\n x: p1.x + t * (p2.x - p1.x),\n y: p1.y + t * (p2.y - p1.y)\n };\n}\n\n/**\n * @private\n */\nexport function _steppedInterpolation(\n p1: Point,\n p2: Point,\n t: number, mode: 'middle' | 'after' | unknown\n) {\n return {\n x: p1.x + t * (p2.x - p1.x),\n y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y\n : mode === 'after' ? t < 1 ? p1.y : p2.y\n : t > 0 ? p2.y : p1.y\n };\n}\n\n/**\n * @private\n */\nexport function _bezierInterpolation(p1: SplinePoint, p2: SplinePoint, t: number, mode?) { // eslint-disable-line @typescript-eslint/no-unused-vars\n const cp1 = {x: p1.cp2x, y: p1.cp2y};\n const cp2 = {x: p2.cp1x, y: p2.cp1y};\n const a = _pointInLine(p1, cp1, t);\n const b = _pointInLine(cp1, cp2, t);\n const c = _pointInLine(cp2, p2, t);\n const d = _pointInLine(a, b, t);\n const e = _pointInLine(b, c, t);\n return _pointInLine(d, e, t);\n}\n","import defaults from '../core/core.defaults.js';\nimport {isArray, isObject, toDimension, valueOrDefault} from './helpers.core.js';\nimport {toFontString} from './helpers.canvas.js';\nimport type {ChartArea, FontSpec, Point} from '../types/index.js';\nimport type {TRBL, TRBLCorners} from '../types/geometric.js';\n\nconst LINE_HEIGHT = /^(normal|(\\d+(?:\\.\\d+)?)(px|em|%)?)$/;\nconst FONT_STYLE = /^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;\n\n/**\n * @alias Chart.helpers.options\n * @namespace\n */\n/**\n * Converts the given line height `value` in pixels for a specific font `size`.\n * @param value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').\n * @param size - The font size (in pixels) used to resolve relative `value`.\n * @returns The effective line height in pixels (size * 1.2 if value is invalid).\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height\n * @since 2.7.0\n */\nexport function toLineHeight(value: number | string, size: number): number {\n const matches = ('' + value).match(LINE_HEIGHT);\n if (!matches || matches[1] === 'normal') {\n return size * 1.2;\n }\n\n value = +matches[2];\n\n switch (matches[3]) {\n case 'px':\n return value;\n case '%':\n value /= 100;\n break;\n default:\n break;\n }\n\n return size * value;\n}\n\nconst numberOrZero = (v: unknown) => +v || 0;\n\n/**\n * @param value\n * @param props\n */\nexport function _readValueToProps(value: number | Record, props: K[]): Record;\nexport function _readValueToProps(value: number | Record, props: Record): Record;\nexport function _readValueToProps(value: number | Record, props: string[] | Record) {\n const ret = {};\n const objProps = isObject(props);\n const keys = objProps ? Object.keys(props) : props;\n const read = isObject(value)\n ? objProps\n ? prop => valueOrDefault(value[prop], value[props[prop]])\n : prop => value[prop]\n : () => value;\n\n for (const prop of keys) {\n ret[prop] = numberOrZero(read(prop));\n }\n return ret;\n}\n\n/**\n * Converts the given value into a TRBL object.\n * @param value - If a number, set the value to all TRBL component,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * x / y are shorthands for same value for left/right and top/bottom.\n * @returns The padding values (top, right, bottom, left)\n * @since 3.0.0\n */\nexport function toTRBL(value: number | TRBL | Point) {\n return _readValueToProps(value, {top: 'y', right: 'x', bottom: 'y', left: 'x'});\n}\n\n/**\n * Converts the given value into a TRBL corners object (similar with css border-radius).\n * @param value - If a number, set the value to all TRBL corner components,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * @returns The TRBL corner values (topLeft, topRight, bottomLeft, bottomRight)\n * @since 3.0.0\n */\nexport function toTRBLCorners(value: number | TRBLCorners) {\n return _readValueToProps(value, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']);\n}\n\n/**\n * Converts the given value into a padding object with pre-computed width/height.\n * @param value - If a number, set the value to all TRBL component,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * x / y are shorthands for same value for left/right and top/bottom.\n * @returns The padding values (top, right, bottom, left, width, height)\n * @since 2.7.0\n */\nexport function toPadding(value?: number | TRBL): ChartArea {\n const obj = toTRBL(value) as ChartArea;\n\n obj.width = obj.left + obj.right;\n obj.height = obj.top + obj.bottom;\n\n return obj;\n}\n\n/**\n * Parses font options and returns the font object.\n * @param options - A object that contains font options to be parsed.\n * @param fallback - A object that contains fallback font options.\n * @return The font object.\n * @private\n */\n\nexport function toFont(options: Partial, fallback?: Partial) {\n options = options || {};\n fallback = fallback || defaults.font as FontSpec;\n\n let size = valueOrDefault(options.size, fallback.size);\n\n if (typeof size === 'string') {\n size = parseInt(size, 10);\n }\n let style = valueOrDefault(options.style, fallback.style);\n if (style && !('' + style).match(FONT_STYLE)) {\n console.warn('Invalid font style specified: \"' + style + '\"');\n style = undefined;\n }\n\n const font = {\n family: valueOrDefault(options.family, fallback.family),\n lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size),\n size,\n style,\n weight: valueOrDefault(options.weight, fallback.weight),\n string: ''\n };\n\n font.string = toFontString(font);\n return font;\n}\n\n/**\n * Evaluates the given `inputs` sequentially and returns the first defined value.\n * @param inputs - An array of values, falling back to the last value.\n * @param context - If defined and the current value is a function, the value\n * is called with `context` as first argument and the result becomes the new input.\n * @param index - If defined and the current value is an array, the value\n * at `index` become the new input.\n * @param info - object to return information about resolution in\n * @param info.cacheable - Will be set to `false` if option is not cacheable.\n * @since 2.7.0\n */\nexport function resolve(inputs: Array, context?: object, index?: number, info?: { cacheable: boolean }) {\n let cacheable = true;\n let i: number, ilen: number, value: unknown;\n\n for (i = 0, ilen = inputs.length; i < ilen; ++i) {\n value = inputs[i];\n if (value === undefined) {\n continue;\n }\n if (context !== undefined && typeof value === 'function') {\n value = value(context);\n cacheable = false;\n }\n if (index !== undefined && isArray(value)) {\n value = value[index % value.length];\n cacheable = false;\n }\n if (value !== undefined) {\n if (info && !cacheable) {\n info.cacheable = false;\n }\n return value;\n }\n }\n}\n\n/**\n * @param minmax\n * @param grace\n * @param beginAtZero\n * @private\n */\nexport function _addGrace(minmax: { min: number; max: number; }, grace: number | string, beginAtZero: boolean) {\n const {min, max} = minmax;\n const change = toDimension(grace, (max - min) / 2);\n const keepZero = (value: number, add: number) => beginAtZero && value === 0 ? 0 : value + add;\n return {\n min: keepZero(min, -Math.abs(change)),\n max: keepZero(max, change)\n };\n}\n\n/**\n * Create a context inheriting parentContext\n * @param parentContext\n * @param context\n * @returns\n */\nexport function createContext(parentContext: null, context: T): T;\nexport function createContext(parentContext: P, context: T): P & T;\nexport function createContext(parentContext: object, context: object) {\n return Object.assign(Object.create(parentContext), context);\n}\n","export interface RTLAdapter {\n x(x: number): number;\n setWidth(w: number): void;\n textAlign(align: 'center' | 'left' | 'right'): 'center' | 'left' | 'right';\n xPlus(x: number, value: number): number;\n leftForLtr(x: number, itemWidth: number): number;\n}\n\nconst getRightToLeftAdapter = function(rectX: number, width: number): RTLAdapter {\n return {\n x(x) {\n return rectX + rectX + width - x;\n },\n setWidth(w) {\n width = w;\n },\n textAlign(align) {\n if (align === 'center') {\n return align;\n }\n return align === 'right' ? 'left' : 'right';\n },\n xPlus(x, value) {\n return x - value;\n },\n leftForLtr(x, itemWidth) {\n return x - itemWidth;\n },\n };\n};\n\nconst getLeftToRightAdapter = function(): RTLAdapter {\n return {\n x(x) {\n return x;\n },\n setWidth(w) { // eslint-disable-line no-unused-vars\n },\n textAlign(align) {\n return align;\n },\n xPlus(x, value) {\n return x + value;\n },\n leftForLtr(x, _itemWidth) { // eslint-disable-line @typescript-eslint/no-unused-vars\n return x;\n },\n };\n};\n\nexport function getRtlAdapter(rtl: boolean, rectX: number, width: number) {\n return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter();\n}\n\nexport function overrideTextDirection(ctx: CanvasRenderingContext2D, direction: 'ltr' | 'rtl') {\n let style: CSSStyleDeclaration, original: [string, string];\n if (direction === 'ltr' || direction === 'rtl') {\n style = ctx.canvas.style;\n original = [\n style.getPropertyValue('direction'),\n style.getPropertyPriority('direction'),\n ];\n\n style.setProperty('direction', direction, 'important');\n (ctx as { prevTextDirection?: [string, string] }).prevTextDirection = original;\n }\n}\n\nexport function restoreTextDirection(ctx: CanvasRenderingContext2D, original?: [string, string]) {\n if (original !== undefined) {\n delete (ctx as { prevTextDirection?: [string, string] }).prevTextDirection;\n ctx.canvas.style.setProperty('direction', original[0], original[1]);\n }\n}\n","import {_angleBetween, _angleDiff, _isBetween, _normalizeAngle} from './helpers.math.js';\nimport {createContext} from './helpers.options.js';\nimport {isPatternOrGradient} from './helpers.color.js';\n\n/**\n * @typedef { import('../elements/element.line.js').default } LineElement\n * @typedef { import('../elements/element.point.js').default } PointElement\n * @typedef {{start: number, end: number, loop: boolean, style?: any}} Segment\n */\n\nfunction propertyFn(property) {\n if (property === 'angle') {\n return {\n between: _angleBetween,\n compare: _angleDiff,\n normalize: _normalizeAngle,\n };\n }\n return {\n between: _isBetween,\n compare: (a, b) => a - b,\n normalize: x => x\n };\n}\n\nfunction normalizeSegment({start, end, count, loop, style}) {\n return {\n start: start % count,\n end: end % count,\n loop: loop && (end - start + 1) % count === 0,\n style\n };\n}\n\nfunction getSegment(segment, points, bounds) {\n const {property, start: startBound, end: endBound} = bounds;\n const {between, normalize} = propertyFn(property);\n const count = points.length;\n // eslint-disable-next-line prefer-const\n let {start, end, loop} = segment;\n let i, ilen;\n\n if (loop) {\n start += count;\n end += count;\n for (i = 0, ilen = count; i < ilen; ++i) {\n if (!between(normalize(points[start % count][property]), startBound, endBound)) {\n break;\n }\n start--;\n end--;\n }\n start %= count;\n end %= count;\n }\n\n if (end < start) {\n end += count;\n }\n return {start, end, loop, style: segment.style};\n}\n\n/**\n * Returns the sub-segment(s) of a line segment that fall in the given bounds\n * @param {object} segment\n * @param {number} segment.start - start index of the segment, referring the points array\n * @param {number} segment.end - end index of the segment, referring the points array\n * @param {boolean} segment.loop - indicates that the segment is a loop\n * @param {object} [segment.style] - segment style\n * @param {PointElement[]} points - the points that this segment refers to\n * @param {object} [bounds]\n * @param {string} bounds.property - the property of a `PointElement` we are bounding. `x`, `y` or `angle`.\n * @param {number} bounds.start - start value of the property\n * @param {number} bounds.end - end value of the property\n * @private\n **/\nexport function _boundSegment(segment, points, bounds) {\n if (!bounds) {\n return [segment];\n }\n\n const {property, start: startBound, end: endBound} = bounds;\n const count = points.length;\n const {compare, between, normalize} = propertyFn(property);\n const {start, end, loop, style} = getSegment(segment, points, bounds);\n\n const result = [];\n let inside = false;\n let subStart = null;\n let value, point, prevValue;\n\n const startIsBefore = () => between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0;\n const endIsBefore = () => compare(endBound, value) === 0 || between(endBound, prevValue, value);\n const shouldStart = () => inside || startIsBefore();\n const shouldStop = () => !inside || endIsBefore();\n\n for (let i = start, prev = start; i <= end; ++i) {\n point = points[i % count];\n\n if (point.skip) {\n continue;\n }\n\n value = normalize(point[property]);\n\n if (value === prevValue) {\n continue;\n }\n\n inside = between(value, startBound, endBound);\n\n if (subStart === null && shouldStart()) {\n subStart = compare(value, startBound) === 0 ? i : prev;\n }\n\n if (subStart !== null && shouldStop()) {\n result.push(normalizeSegment({start: subStart, end: i, loop, count, style}));\n subStart = null;\n }\n prev = i;\n prevValue = value;\n }\n\n if (subStart !== null) {\n result.push(normalizeSegment({start: subStart, end, loop, count, style}));\n }\n\n return result;\n}\n\n\n/**\n * Returns the segments of the line that are inside given bounds\n * @param {LineElement} line\n * @param {object} [bounds]\n * @param {string} bounds.property - the property we are bounding with. `x`, `y` or `angle`.\n * @param {number} bounds.start - start value of the `property`\n * @param {number} bounds.end - end value of the `property`\n * @private\n */\nexport function _boundSegments(line, bounds) {\n const result = [];\n const segments = line.segments;\n\n for (let i = 0; i < segments.length; i++) {\n const sub = _boundSegment(segments[i], line.points, bounds);\n if (sub.length) {\n result.push(...sub);\n }\n }\n return result;\n}\n\n/**\n * Find start and end index of a line.\n */\nfunction findStartAndEnd(points, count, loop, spanGaps) {\n let start = 0;\n let end = count - 1;\n\n if (loop && !spanGaps) {\n // loop and not spanning gaps, first find a gap to start from\n while (start < count && !points[start].skip) {\n start++;\n }\n }\n\n // find first non skipped point (after the first gap possibly)\n while (start < count && points[start].skip) {\n start++;\n }\n\n // if we looped to count, start needs to be 0\n start %= count;\n\n if (loop) {\n // loop will go past count, if start > 0\n end += start;\n }\n\n while (end > start && points[end % count].skip) {\n end--;\n }\n\n // end could be more than count, normalize\n end %= count;\n\n return {start, end};\n}\n\n/**\n * Compute solid segments from Points, when spanGaps === false\n * @param {PointElement[]} points - the points\n * @param {number} start - start index\n * @param {number} max - max index (can go past count on a loop)\n * @param {boolean} loop - boolean indicating that this would be a loop if no gaps are found\n */\nfunction solidSegments(points, start, max, loop) {\n const count = points.length;\n const result = [];\n let last = start;\n let prev = points[start];\n let end;\n\n for (end = start + 1; end <= max; ++end) {\n const cur = points[end % count];\n if (cur.skip || cur.stop) {\n if (!prev.skip) {\n loop = false;\n result.push({start: start % count, end: (end - 1) % count, loop});\n // @ts-ignore\n start = last = cur.stop ? end : null;\n }\n } else {\n last = end;\n if (prev.skip) {\n start = end;\n }\n }\n prev = cur;\n }\n\n if (last !== null) {\n result.push({start: start % count, end: last % count, loop});\n }\n\n return result;\n}\n\n/**\n * Compute the continuous segments that define the whole line\n * There can be skipped points within a segment, if spanGaps is true.\n * @param {LineElement} line\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n * @private\n */\nexport function _computeSegments(line, segmentOptions) {\n const points = line.points;\n const spanGaps = line.options.spanGaps;\n const count = points.length;\n\n if (!count) {\n return [];\n }\n\n const loop = !!line._loop;\n const {start, end} = findStartAndEnd(points, count, loop, spanGaps);\n\n if (spanGaps === true) {\n return splitByStyles(line, [{start, end, loop}], points, segmentOptions);\n }\n\n const max = end < start ? end + count : end;\n const completeLoop = !!line._fullLoop && start === 0 && end === count - 1;\n return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions);\n}\n\n/**\n * @param {Segment[]} segments\n * @param {PointElement[]} points\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n */\nfunction splitByStyles(line, segments, points, segmentOptions) {\n if (!segmentOptions || !segmentOptions.setContext || !points) {\n return segments;\n }\n return doSplitByStyles(line, segments, points, segmentOptions);\n}\n\n/**\n * @param {LineElement} line\n * @param {Segment[]} segments\n * @param {PointElement[]} points\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n */\nfunction doSplitByStyles(line, segments, points, segmentOptions) {\n const chartContext = line._chart.getContext();\n const baseStyle = readStyle(line.options);\n const {_datasetIndex: datasetIndex, options: {spanGaps}} = line;\n const count = points.length;\n const result = [];\n let prevStyle = baseStyle;\n let start = segments[0].start;\n let i = start;\n\n function addStyle(s, e, l, st) {\n const dir = spanGaps ? -1 : 1;\n if (s === e) {\n return;\n }\n // Style can not start/end on a skipped point, adjust indices accordingly\n s += count;\n while (points[s % count].skip) {\n s -= dir;\n }\n while (points[e % count].skip) {\n e += dir;\n }\n if (s % count !== e % count) {\n result.push({start: s % count, end: e % count, loop: l, style: st});\n prevStyle = st;\n start = e % count;\n }\n }\n\n for (const segment of segments) {\n start = spanGaps ? start : segment.start;\n let prev = points[start % count];\n let style;\n for (i = start + 1; i <= segment.end; i++) {\n const pt = points[i % count];\n style = readStyle(segmentOptions.setContext(createContext(chartContext, {\n type: 'segment',\n p0: prev,\n p1: pt,\n p0DataIndex: (i - 1) % count,\n p1DataIndex: i % count,\n datasetIndex\n })));\n if (styleChanged(style, prevStyle)) {\n addStyle(start, i - 1, segment.loop, prevStyle);\n }\n prev = pt;\n prevStyle = style;\n }\n if (start < i - 1) {\n addStyle(start, i - 1, segment.loop, prevStyle);\n }\n }\n\n return result;\n}\n\nfunction readStyle(options) {\n return {\n backgroundColor: options.backgroundColor,\n borderCapStyle: options.borderCapStyle,\n borderDash: options.borderDash,\n borderDashOffset: options.borderDashOffset,\n borderJoinStyle: options.borderJoinStyle,\n borderWidth: options.borderWidth,\n borderColor: options.borderColor\n };\n}\n\nfunction styleChanged(style, prevStyle) {\n if (!prevStyle) {\n return false;\n }\n const cache = [];\n const replacer = function(key, value) {\n if (!isPatternOrGradient(value)) {\n return value;\n }\n if (!cache.includes(value)) {\n cache.push(value);\n }\n return cache.indexOf(value);\n };\n return JSON.stringify(style, replacer) !== JSON.stringify(prevStyle, replacer);\n}\n","import {_lookupByKey, _rlookupByKey} from '../helpers/helpers.collection.js';\nimport {getRelativePosition} from '../helpers/helpers.dom.js';\nimport {_angleBetween, getAngleFromPoint} from '../helpers/helpers.math.js';\nimport {_isPointInArea} from '../helpers/index.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n * @typedef {{axis?: string, intersect?: boolean, includeInvisible?: boolean}} InteractionOptions\n * @typedef {{datasetIndex: number, index: number, element: import('./core.element.js').default}} InteractionItem\n * @typedef { import('../types/index.js').Point } Point\n */\n\n/**\n * Helper function to do binary search when possible\n * @param {object} metaset - the dataset meta\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {number} value - the value to find\n * @param {boolean} [intersect] - should the element intersect\n * @returns {{lo:number, hi:number}} indices to search data array between\n */\nfunction binarySearch(metaset, axis, value, intersect) {\n const {controller, data, _sorted} = metaset;\n const iScale = controller._cachedMeta.iScale;\n if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) {\n const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;\n if (!intersect) {\n return lookupMethod(data, axis, value);\n } else if (controller._sharedOptions) {\n // _sharedOptions indicates that each element has equal options -> equal proportions\n // So we can do a ranged binary search based on the range of first element and\n // be confident to get the full range of indices that can intersect with the value.\n const el = data[0];\n const range = typeof el.getRange === 'function' && el.getRange(axis);\n if (range) {\n const start = lookupMethod(data, axis, value - range);\n const end = lookupMethod(data, axis, value + range);\n return {lo: start.lo, hi: end.hi};\n }\n }\n }\n // Default to all elements, when binary search can not be used.\n return {lo: 0, hi: data.length - 1};\n}\n\n/**\n * Helper function to select candidate elements for interaction\n * @param {Chart} chart - the chart\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {function} handler - the callback to execute for each visible item\n * @param {boolean} [intersect] - consider intersecting items\n */\nfunction evaluateInteractionItems(chart, axis, position, handler, intersect) {\n const metasets = chart.getSortedVisibleDatasetMetas();\n const value = position[axis];\n for (let i = 0, ilen = metasets.length; i < ilen; ++i) {\n const {index, data} = metasets[i];\n const {lo, hi} = binarySearch(metasets[i], axis, value, intersect);\n for (let j = lo; j <= hi; ++j) {\n const element = data[j];\n if (!element.skip) {\n handler(element, index, j);\n }\n }\n }\n}\n\n/**\n * Get a distance metric function for two points based on the\n * axis mode setting\n * @param {string} axis - the axis mode. x|y|xy|r\n */\nfunction getDistanceMetricForAxis(axis) {\n const useX = axis.indexOf('x') !== -1;\n const useY = axis.indexOf('y') !== -1;\n\n return function(pt1, pt2) {\n const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;\n const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;\n return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));\n };\n}\n\n/**\n * Helper function to get the items that intersect the event position\n * @param {Chart} chart - the chart\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) {\n const items = [];\n\n if (!includeInvisible && !chart.isPointInArea(position)) {\n return items;\n }\n\n const evaluationFunc = function(element, datasetIndex, index) {\n if (!includeInvisible && !_isPointInArea(element, chart.chartArea, 0)) {\n return;\n }\n if (element.inRange(position.x, position.y, useFinalPosition)) {\n items.push({element, datasetIndex, index});\n }\n };\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc, true);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position for a radial chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestRadialItems(chart, position, axis, useFinalPosition) {\n let items = [];\n\n function evaluationFunc(element, datasetIndex, index) {\n const {startAngle, endAngle} = element.getProps(['startAngle', 'endAngle'], useFinalPosition);\n const {angle} = getAngleFromPoint(element, {x: position.x, y: position.y});\n\n if (_angleBetween(angle, startAngle, endAngle)) {\n items.push({element, datasetIndex, index});\n }\n }\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position for a cartesian chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {\n let items = [];\n const distanceMetric = getDistanceMetricForAxis(axis);\n let minDistance = Number.POSITIVE_INFINITY;\n\n function evaluationFunc(element, datasetIndex, index) {\n const inRange = element.inRange(position.x, position.y, useFinalPosition);\n if (intersect && !inRange) {\n return;\n }\n\n const center = element.getCenterPoint(useFinalPosition);\n const pointInArea = !!includeInvisible || chart.isPointInArea(center);\n if (!pointInArea && !inRange) {\n return;\n }\n\n const distance = distanceMetric(position, center);\n if (distance < minDistance) {\n items = [{element, datasetIndex, index}];\n minDistance = distance;\n } else if (distance === minDistance) {\n // Can have multiple items at the same distance in which case we sort by size\n items.push({element, datasetIndex, index});\n }\n }\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position considering all visible items in the chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {\n if (!includeInvisible && !chart.isPointInArea(position)) {\n return [];\n }\n\n return axis === 'r' && !intersect\n ? getNearestRadialItems(chart, position, axis, useFinalPosition)\n : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible);\n}\n\n/**\n * Helper function to get the items matching along the given X or Y axis\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axis to match\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @return {InteractionItem[]} the nearest items\n */\nfunction getAxisItems(chart, position, axis, intersect, useFinalPosition) {\n const items = [];\n const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';\n let intersectsItem = false;\n\n evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index) => {\n if (element[rangeMethod](position[axis], useFinalPosition)) {\n items.push({element, datasetIndex, index});\n intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition);\n }\n });\n\n // If we want to trigger on an intersect and we don't have any items\n // that intersect the position, return nothing\n if (intersect && !intersectsItem) {\n return [];\n }\n return items;\n}\n\n/**\n * Contains interaction related functions\n * @namespace Chart.Interaction\n */\nexport default {\n // Part of the public API to facilitate developers creating their own modes\n evaluateInteractionItems,\n\n // Helper function for different modes\n modes: {\n /**\n\t\t * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something\n\t\t * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item\n\t\t * @function Chart.Interaction.modes.index\n\t\t * @since v2.4.0\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n index(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n // Default axis for index mode is 'x' to match old behaviour\n const axis = options.axis || 'x';\n const includeInvisible = options.includeInvisible || false;\n const items = options.intersect\n ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible)\n : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);\n const elements = [];\n\n if (!items.length) {\n return [];\n }\n\n chart.getSortedVisibleDatasetMetas().forEach((meta) => {\n const index = items[0].index;\n const element = meta.data[index];\n\n // don't count items that are skipped (null data)\n if (element && !element.skip) {\n elements.push({element, datasetIndex: meta.index, index});\n }\n });\n\n return elements;\n },\n\n /**\n\t\t * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something\n\t\t * If the options.intersect is false, we find the nearest item and return the items in that dataset\n\t\t * @function Chart.Interaction.modes.dataset\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n dataset(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n let items = options.intersect\n ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) :\n getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);\n\n if (items.length > 0) {\n const datasetIndex = items[0].datasetIndex;\n const data = chart.getDatasetMeta(datasetIndex).data;\n items = [];\n for (let i = 0; i < data.length; ++i) {\n items.push({element: data[i], datasetIndex, index: i});\n }\n }\n\n return items;\n },\n\n /**\n\t\t * Point mode returns all elements that hit test based on the event position\n\t\t * of the event\n\t\t * @function Chart.Interaction.modes.intersect\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n point(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible);\n },\n\n /**\n\t\t * nearest mode returns the element closest to the point\n\t\t * @function Chart.Interaction.modes.intersect\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n nearest(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible);\n },\n\n /**\n\t\t * x mode returns the elements that hit-test at the current x coordinate\n\t\t * @function Chart.Interaction.modes.x\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n x(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition);\n },\n\n /**\n\t\t * y mode returns the elements that hit-test at the current y coordinate\n\t\t * @function Chart.Interaction.modes.y\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n y(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition);\n }\n }\n};\n","import {defined, each, isObject} from '../helpers/helpers.core.js';\nimport {toPadding} from '../helpers/helpers.options.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n */\n\nconst STATIC_POSITIONS = ['left', 'top', 'right', 'bottom'];\n\nfunction filterByPosition(array, position) {\n return array.filter(v => v.pos === position);\n}\n\nfunction filterDynamicPositionByAxis(array, axis) {\n return array.filter(v => STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);\n}\n\nfunction sortByWeight(array, reverse) {\n return array.sort((a, b) => {\n const v0 = reverse ? b : a;\n const v1 = reverse ? a : b;\n return v0.weight === v1.weight ?\n v0.index - v1.index :\n v0.weight - v1.weight;\n });\n}\n\nfunction wrapBoxes(boxes) {\n const layoutBoxes = [];\n let i, ilen, box, pos, stack, stackWeight;\n\n for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {\n box = boxes[i];\n ({position: pos, options: {stack, stackWeight = 1}} = box);\n layoutBoxes.push({\n index: i,\n box,\n pos,\n horizontal: box.isHorizontal(),\n weight: box.weight,\n stack: stack && (pos + stack),\n stackWeight\n });\n }\n return layoutBoxes;\n}\n\nfunction buildStacks(layouts) {\n const stacks = {};\n for (const wrap of layouts) {\n const {stack, pos, stackWeight} = wrap;\n if (!stack || !STATIC_POSITIONS.includes(pos)) {\n continue;\n }\n const _stack = stacks[stack] || (stacks[stack] = {count: 0, placed: 0, weight: 0, size: 0});\n _stack.count++;\n _stack.weight += stackWeight;\n }\n return stacks;\n}\n\n/**\n * store dimensions used instead of available chartArea in fitBoxes\n **/\nfunction setLayoutDims(layouts, params) {\n const stacks = buildStacks(layouts);\n const {vBoxMaxWidth, hBoxMaxHeight} = params;\n let i, ilen, layout;\n for (i = 0, ilen = layouts.length; i < ilen; ++i) {\n layout = layouts[i];\n const {fullSize} = layout.box;\n const stack = stacks[layout.stack];\n const factor = stack && layout.stackWeight / stack.weight;\n if (layout.horizontal) {\n layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;\n layout.height = hBoxMaxHeight;\n } else {\n layout.width = vBoxMaxWidth;\n layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;\n }\n }\n return stacks;\n}\n\nfunction buildLayoutBoxes(boxes) {\n const layoutBoxes = wrapBoxes(boxes);\n const fullSize = sortByWeight(layoutBoxes.filter(wrap => wrap.box.fullSize), true);\n const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);\n const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));\n const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);\n const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));\n const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');\n const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');\n\n return {\n fullSize,\n leftAndTop: left.concat(top),\n rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),\n chartArea: filterByPosition(layoutBoxes, 'chartArea'),\n vertical: left.concat(right).concat(centerVertical),\n horizontal: top.concat(bottom).concat(centerHorizontal)\n };\n}\n\nfunction getCombinedMax(maxPadding, chartArea, a, b) {\n return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);\n}\n\nfunction updateMaxPadding(maxPadding, boxPadding) {\n maxPadding.top = Math.max(maxPadding.top, boxPadding.top);\n maxPadding.left = Math.max(maxPadding.left, boxPadding.left);\n maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);\n maxPadding.right = Math.max(maxPadding.right, boxPadding.right);\n}\n\nfunction updateDims(chartArea, params, layout, stacks) {\n const {pos, box} = layout;\n const maxPadding = chartArea.maxPadding;\n\n // dynamically placed boxes size is not considered\n if (!isObject(pos)) {\n if (layout.size) {\n // this layout was already counted for, lets first reduce old size\n chartArea[pos] -= layout.size;\n }\n const stack = stacks[layout.stack] || {size: 0, count: 1};\n stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);\n layout.size = stack.size / stack.count;\n chartArea[pos] += layout.size;\n }\n\n if (box.getPadding) {\n updateMaxPadding(maxPadding, box.getPadding());\n }\n\n const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));\n const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));\n const widthChanged = newWidth !== chartArea.w;\n const heightChanged = newHeight !== chartArea.h;\n chartArea.w = newWidth;\n chartArea.h = newHeight;\n\n // return booleans on the changes per direction\n return layout.horizontal\n ? {same: widthChanged, other: heightChanged}\n : {same: heightChanged, other: widthChanged};\n}\n\nfunction handleMaxPadding(chartArea) {\n const maxPadding = chartArea.maxPadding;\n\n function updatePos(pos) {\n const change = Math.max(maxPadding[pos] - chartArea[pos], 0);\n chartArea[pos] += change;\n return change;\n }\n chartArea.y += updatePos('top');\n chartArea.x += updatePos('left');\n updatePos('right');\n updatePos('bottom');\n}\n\nfunction getMargins(horizontal, chartArea) {\n const maxPadding = chartArea.maxPadding;\n\n function marginForPositions(positions) {\n const margin = {left: 0, top: 0, right: 0, bottom: 0};\n positions.forEach((pos) => {\n margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);\n });\n return margin;\n }\n\n return horizontal\n ? marginForPositions(['left', 'right'])\n : marginForPositions(['top', 'bottom']);\n}\n\nfunction fitBoxes(boxes, chartArea, params, stacks) {\n const refitBoxes = [];\n let i, ilen, layout, box, refit, changed;\n\n for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) {\n layout = boxes[i];\n box = layout.box;\n\n box.update(\n layout.width || chartArea.w,\n layout.height || chartArea.h,\n getMargins(layout.horizontal, chartArea)\n );\n const {same, other} = updateDims(chartArea, params, layout, stacks);\n\n // Dimensions changed and there were non full width boxes before this\n // -> we have to refit those\n refit |= same && refitBoxes.length;\n\n // Chart area changed in the opposite direction\n changed = changed || other;\n\n if (!box.fullSize) { // fullSize boxes don't need to be re-fitted in any case\n refitBoxes.push(layout);\n }\n }\n\n return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;\n}\n\nfunction setBoxDims(box, left, top, width, height) {\n box.top = top;\n box.left = left;\n box.right = left + width;\n box.bottom = top + height;\n box.width = width;\n box.height = height;\n}\n\nfunction placeBoxes(boxes, chartArea, params, stacks) {\n const userPadding = params.padding;\n let {x, y} = chartArea;\n\n for (const layout of boxes) {\n const box = layout.box;\n const stack = stacks[layout.stack] || {count: 1, placed: 0, weight: 1};\n const weight = (layout.stackWeight / stack.weight) || 1;\n if (layout.horizontal) {\n const width = chartArea.w * weight;\n const height = stack.size || box.height;\n if (defined(stack.start)) {\n y = stack.start;\n }\n if (box.fullSize) {\n setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);\n } else {\n setBoxDims(box, chartArea.left + stack.placed, y, width, height);\n }\n stack.start = y;\n stack.placed += width;\n y = box.bottom;\n } else {\n const height = chartArea.h * weight;\n const width = stack.size || box.width;\n if (defined(stack.start)) {\n x = stack.start;\n }\n if (box.fullSize) {\n setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);\n } else {\n setBoxDims(box, x, chartArea.top + stack.placed, width, height);\n }\n stack.start = x;\n stack.placed += height;\n x = box.right;\n }\n }\n\n chartArea.x = x;\n chartArea.y = y;\n}\n\n/**\n * @interface LayoutItem\n * @typedef {object} LayoutItem\n * @prop {string} position - The position of the item in the chart layout. Possible values are\n * 'left', 'top', 'right', 'bottom', and 'chartArea'\n * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area\n * @prop {boolean} fullSize - if true, and the item is horizontal, then push vertical boxes down\n * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)\n * @prop {function} update - Takes two parameters: width and height. Returns size of item\n * @prop {function} draw - Draws the element\n * @prop {function} [getPadding] - Returns an object with padding on the edges\n * @prop {number} width - Width of item. Must be valid after update()\n * @prop {number} height - Height of item. Must be valid after update()\n * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update\n * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update\n * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update\n * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update\n */\n\n// The layout service is very self explanatory. It's responsible for the layout within a chart.\n// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need\n// It is this service's responsibility of carrying out that layout.\nexport default {\n\n /**\n\t * Register a box to a chart.\n\t * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.\n\t * @param {Chart} chart - the chart to use\n\t * @param {LayoutItem} item - the item to add to be laid out\n\t */\n addBox(chart, item) {\n if (!chart.boxes) {\n chart.boxes = [];\n }\n\n // initialize item with default values\n item.fullSize = item.fullSize || false;\n item.position = item.position || 'top';\n item.weight = item.weight || 0;\n // @ts-ignore\n item._layers = item._layers || function() {\n return [{\n z: 0,\n draw(chartArea) {\n item.draw(chartArea);\n }\n }];\n };\n\n chart.boxes.push(item);\n },\n\n /**\n\t * Remove a layoutItem from a chart\n\t * @param {Chart} chart - the chart to remove the box from\n\t * @param {LayoutItem} layoutItem - the item to remove from the layout\n\t */\n removeBox(chart, layoutItem) {\n const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;\n if (index !== -1) {\n chart.boxes.splice(index, 1);\n }\n },\n\n /**\n\t * Sets (or updates) options on the given `item`.\n\t * @param {Chart} chart - the chart in which the item lives (or will be added to)\n\t * @param {LayoutItem} item - the item to configure with the given options\n\t * @param {object} options - the new item options.\n\t */\n configure(chart, item, options) {\n item.fullSize = options.fullSize;\n item.position = options.position;\n item.weight = options.weight;\n },\n\n /**\n\t * Fits boxes of the given chart into the given size by having each box measure itself\n\t * then running a fitting algorithm\n\t * @param {Chart} chart - the chart\n\t * @param {number} width - the width to fit into\n\t * @param {number} height - the height to fit into\n * @param {number} minPadding - minimum padding required for each side of chart area\n\t */\n update(chart, width, height, minPadding) {\n if (!chart) {\n return;\n }\n\n const padding = toPadding(chart.options.layout.padding);\n const availableWidth = Math.max(width - padding.width, 0);\n const availableHeight = Math.max(height - padding.height, 0);\n const boxes = buildLayoutBoxes(chart.boxes);\n const verticalBoxes = boxes.vertical;\n const horizontalBoxes = boxes.horizontal;\n\n // Before any changes are made, notify boxes that an update is about to being\n // This is used to clear any cached data (e.g. scale limits)\n each(chart.boxes, box => {\n if (typeof box.beforeLayout === 'function') {\n box.beforeLayout();\n }\n });\n\n // Essentially we now have any number of boxes on each of the 4 sides.\n // Our canvas looks like the following.\n // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and\n // B1 is the bottom axis\n // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays\n // These locations are single-box locations only, when trying to register a chartArea location that is already taken,\n // an error will be thrown.\n //\n // |----------------------------------------------------|\n // | T1 (Full Width) |\n // |----------------------------------------------------|\n // | | | T2 | |\n // | |----|-------------------------------------|----|\n // | | | C1 | | C2 | |\n // | | |----| |----| |\n // | | | | |\n // | L1 | L2 | ChartArea (C0) | R1 |\n // | | | | |\n // | | |----| |----| |\n // | | | C3 | | C4 | |\n // | |----|-------------------------------------|----|\n // | | | B1 | |\n // |----------------------------------------------------|\n // | B2 (Full Width) |\n // |----------------------------------------------------|\n //\n\n const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) =>\n wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;\n\n const params = Object.freeze({\n outerWidth: width,\n outerHeight: height,\n padding,\n availableWidth,\n availableHeight,\n vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,\n hBoxMaxHeight: availableHeight / 2\n });\n const maxPadding = Object.assign({}, padding);\n updateMaxPadding(maxPadding, toPadding(minPadding));\n const chartArea = Object.assign({\n maxPadding,\n w: availableWidth,\n h: availableHeight,\n x: padding.left,\n y: padding.top\n }, padding);\n\n const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);\n\n // First fit the fullSize boxes, to reduce probability of re-fitting.\n fitBoxes(boxes.fullSize, chartArea, params, stacks);\n\n // Then fit vertical boxes\n fitBoxes(verticalBoxes, chartArea, params, stacks);\n\n // Then fit horizontal boxes\n if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {\n // if the area changed, re-fit vertical boxes\n fitBoxes(verticalBoxes, chartArea, params, stacks);\n }\n\n handleMaxPadding(chartArea);\n\n // Finally place the boxes to correct coordinates\n placeBoxes(boxes.leftAndTop, chartArea, params, stacks);\n\n // Move to opposite side of chart\n chartArea.x += chartArea.w;\n chartArea.y += chartArea.h;\n\n placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);\n\n chart.chartArea = {\n left: chartArea.left,\n top: chartArea.top,\n right: chartArea.left + chartArea.w,\n bottom: chartArea.top + chartArea.h,\n height: chartArea.h,\n width: chartArea.w,\n };\n\n // Finally update boxes in chartArea (radial scale for example)\n each(boxes.chartArea, (layout) => {\n const box = layout.box;\n Object.assign(box, chart.chartArea);\n box.update(chartArea.w, chartArea.h, {left: 0, top: 0, right: 0, bottom: 0});\n });\n }\n};\n","\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\n/**\n * Abstract class that allows abstracting platform dependencies away from the chart.\n */\nexport default class BasePlatform {\n /**\n\t * Called at chart construction time, returns a context2d instance implementing\n\t * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.\n\t * @param {HTMLCanvasElement} canvas - The canvas from which to acquire context (platform specific)\n\t * @param {number} [aspectRatio] - The chart options\n\t */\n acquireContext(canvas, aspectRatio) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * Called at chart destruction time, releases any resources associated to the context\n\t * previously returned by the acquireContext() method.\n\t * @param {CanvasRenderingContext2D} context - The context2d instance\n\t * @returns {boolean} true if the method succeeded, else false\n\t */\n releaseContext(context) { // eslint-disable-line no-unused-vars\n return false;\n }\n\n /**\n\t * Registers the specified listener on the given chart.\n\t * @param {Chart} chart - Chart from which to listen for event\n\t * @param {string} type - The ({@link ChartEvent}) type to listen for\n\t * @param {function} listener - Receives a notification (an object that implements\n\t * the {@link ChartEvent} interface) when an event of the specified type occurs.\n\t */\n addEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * Removes the specified listener previously registered with addEventListener.\n\t * @param {Chart} chart - Chart from which to remove the listener\n\t * @param {string} type - The ({@link ChartEvent}) type to remove\n\t * @param {function} listener - The listener function to remove from the event target.\n\t */\n removeEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * @returns {number} the current devicePixelRatio of the device this platform is connected to.\n\t */\n getDevicePixelRatio() {\n return 1;\n }\n\n /**\n\t * Returns the maximum size in pixels of given canvas element.\n\t * @param {HTMLCanvasElement} element\n\t * @param {number} [width] - content width of parent element\n\t * @param {number} [height] - content height of parent element\n\t * @param {number} [aspectRatio] - aspect ratio to maintain\n\t */\n getMaximumSize(element, width, height, aspectRatio) {\n width = Math.max(0, width || element.width);\n height = height || element.height;\n return {\n width,\n height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)\n };\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @returns {boolean} true if the canvas is attached to the platform, false if not.\n\t */\n isAttached(canvas) { // eslint-disable-line no-unused-vars\n return true;\n }\n\n /**\n * Updates config with platform specific requirements\n * @param {import('../core/core.config.js').default} config\n */\n updateConfig(config) { // eslint-disable-line no-unused-vars\n // no-op\n }\n}\n","/**\n * Platform fallback implementation (minimal).\n * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939\n */\n\nimport BasePlatform from './platform.base.js';\n\n/**\n * Platform class for charts without access to the DOM or to many element properties\n * This platform is used by default for any chart passed an OffscreenCanvas.\n * @extends BasePlatform\n */\nexport default class BasicPlatform extends BasePlatform {\n acquireContext(item) {\n // To prevent canvas fingerprinting, some add-ons undefine the getContext\n // method, for example: https://github.com/kkapsner/CanvasBlocker\n // https://github.com/chartjs/Chart.js/issues/2807\n return item && item.getContext && item.getContext('2d') || null;\n }\n updateConfig(config) {\n config.options.animation = false;\n }\n}\n","/**\n * Chart.Platform implementation for targeting a web browser\n */\n\nimport BasePlatform from './platform.base.js';\nimport {_getParentNode, getRelativePosition, supportsEventListenerOptions, readUsedSize, getMaximumSize} from '../helpers/helpers.dom.js';\nimport {throttled} from '../helpers/helpers.extras.js';\nimport {isNullOrUndef} from '../helpers/helpers.core.js';\n\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\nconst EXPANDO_KEY = '$chartjs';\n\n/**\n * DOM event types -> Chart.js event types.\n * Note: only events with different types are mapped.\n * @see https://developer.mozilla.org/en-US/docs/Web/Events\n */\nconst EVENT_TYPES = {\n touchstart: 'mousedown',\n touchmove: 'mousemove',\n touchend: 'mouseup',\n pointerenter: 'mouseenter',\n pointerdown: 'mousedown',\n pointermove: 'mousemove',\n pointerup: 'mouseup',\n pointerleave: 'mouseout',\n pointerout: 'mouseout'\n};\n\nconst isNullOrEmpty = value => value === null || value === '';\n/**\n * Initializes the canvas style and render size without modifying the canvas display size,\n * since responsiveness is handled by the controller.resize() method. The config is used\n * to determine the aspect ratio to apply in case no explicit height has been specified.\n * @param {HTMLCanvasElement} canvas\n * @param {number} [aspectRatio]\n */\nfunction initCanvas(canvas, aspectRatio) {\n const style = canvas.style;\n\n // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it\n // returns null or '' if no explicit value has been set to the canvas attribute.\n const renderHeight = canvas.getAttribute('height');\n const renderWidth = canvas.getAttribute('width');\n\n // Chart.js modifies some canvas values that we want to restore on destroy\n canvas[EXPANDO_KEY] = {\n initial: {\n height: renderHeight,\n width: renderWidth,\n style: {\n display: style.display,\n height: style.height,\n width: style.width\n }\n }\n };\n\n // Force canvas to display as block to avoid extra space caused by inline\n // elements, which would interfere with the responsive resize process.\n // https://github.com/chartjs/Chart.js/issues/2538\n style.display = style.display || 'block';\n // Include possible borders in the size\n style.boxSizing = style.boxSizing || 'border-box';\n\n if (isNullOrEmpty(renderWidth)) {\n const displayWidth = readUsedSize(canvas, 'width');\n if (displayWidth !== undefined) {\n canvas.width = displayWidth;\n }\n }\n\n if (isNullOrEmpty(renderHeight)) {\n if (canvas.style.height === '') {\n // If no explicit render height and style height, let's apply the aspect ratio,\n // which one can be specified by the user but also by charts as default option\n // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.\n canvas.height = canvas.width / (aspectRatio || 2);\n } else {\n const displayHeight = readUsedSize(canvas, 'height');\n if (displayHeight !== undefined) {\n canvas.height = displayHeight;\n }\n }\n }\n\n return canvas;\n}\n\n// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.\n// https://github.com/chartjs/Chart.js/issues/4287\nconst eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;\n\nfunction addListener(node, type, listener) {\n node.addEventListener(type, listener, eventListenerOptions);\n}\n\nfunction removeListener(chart, type, listener) {\n chart.canvas.removeEventListener(type, listener, eventListenerOptions);\n}\n\nfunction fromNativeEvent(event, chart) {\n const type = EVENT_TYPES[event.type] || event.type;\n const {x, y} = getRelativePosition(event, chart);\n return {\n type,\n chart,\n native: event,\n x: x !== undefined ? x : null,\n y: y !== undefined ? y : null,\n };\n}\n\nfunction nodeListContains(nodeList, canvas) {\n for (const node of nodeList) {\n if (node === canvas || node.contains(canvas)) {\n return true;\n }\n }\n}\n\nfunction createAttachObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const observer = new MutationObserver(entries => {\n let trigger = false;\n for (const entry of entries) {\n trigger = trigger || nodeListContains(entry.addedNodes, canvas);\n trigger = trigger && !nodeListContains(entry.removedNodes, canvas);\n }\n if (trigger) {\n listener();\n }\n });\n observer.observe(document, {childList: true, subtree: true});\n return observer;\n}\n\nfunction createDetachObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const observer = new MutationObserver(entries => {\n let trigger = false;\n for (const entry of entries) {\n trigger = trigger || nodeListContains(entry.removedNodes, canvas);\n trigger = trigger && !nodeListContains(entry.addedNodes, canvas);\n }\n if (trigger) {\n listener();\n }\n });\n observer.observe(document, {childList: true, subtree: true});\n return observer;\n}\n\nconst drpListeningCharts = new Map();\nlet oldDevicePixelRatio = 0;\n\nfunction onWindowResize() {\n const dpr = window.devicePixelRatio;\n if (dpr === oldDevicePixelRatio) {\n return;\n }\n oldDevicePixelRatio = dpr;\n drpListeningCharts.forEach((resize, chart) => {\n if (chart.currentDevicePixelRatio !== dpr) {\n resize();\n }\n });\n}\n\nfunction listenDevicePixelRatioChanges(chart, resize) {\n if (!drpListeningCharts.size) {\n window.addEventListener('resize', onWindowResize);\n }\n drpListeningCharts.set(chart, resize);\n}\n\nfunction unlistenDevicePixelRatioChanges(chart) {\n drpListeningCharts.delete(chart);\n if (!drpListeningCharts.size) {\n window.removeEventListener('resize', onWindowResize);\n }\n}\n\nfunction createResizeObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const container = canvas && _getParentNode(canvas);\n if (!container) {\n return;\n }\n const resize = throttled((width, height) => {\n const w = container.clientWidth;\n listener(width, height);\n if (w < container.clientWidth) {\n // If the container size shrank during chart resize, let's assume\n // scrollbar appeared. So we resize again with the scrollbar visible -\n // effectively making chart smaller and the scrollbar hidden again.\n // Because we are inside `throttled`, and currently `ticking`, scroll\n // events are ignored during this whole 2 resize process.\n // If we assumed wrong and something else happened, we are resizing\n // twice in a frame (potential performance issue)\n listener();\n }\n }, window);\n\n // @ts-ignore until https://github.com/microsoft/TypeScript/issues/37861 implemented\n const observer = new ResizeObserver(entries => {\n const entry = entries[0];\n const width = entry.contentRect.width;\n const height = entry.contentRect.height;\n // When its container's display is set to 'none' the callback will be called with a\n // size of (0, 0), which will cause the chart to lose its original height, so skip\n // resizing in such case.\n if (width === 0 && height === 0) {\n return;\n }\n resize(width, height);\n });\n observer.observe(container);\n listenDevicePixelRatioChanges(chart, resize);\n\n return observer;\n}\n\nfunction releaseObserver(chart, type, observer) {\n if (observer) {\n observer.disconnect();\n }\n if (type === 'resize') {\n unlistenDevicePixelRatioChanges(chart);\n }\n}\n\nfunction createProxyAndListen(chart, type, listener) {\n const canvas = chart.canvas;\n const proxy = throttled((event) => {\n // This case can occur if the chart is destroyed while waiting\n // for the throttled function to occur. We prevent crashes by checking\n // for a destroyed chart\n if (chart.ctx !== null) {\n listener(fromNativeEvent(event, chart));\n }\n }, chart);\n\n addListener(canvas, type, proxy);\n\n return proxy;\n}\n\n/**\n * Platform class for charts that can access the DOM and global window/document properties\n * @extends BasePlatform\n */\nexport default class DomPlatform extends BasePlatform {\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @param {number} [aspectRatio]\n\t * @return {CanvasRenderingContext2D|null}\n\t */\n acquireContext(canvas, aspectRatio) {\n // To prevent canvas fingerprinting, some add-ons undefine the getContext\n // method, for example: https://github.com/kkapsner/CanvasBlocker\n // https://github.com/chartjs/Chart.js/issues/2807\n const context = canvas && canvas.getContext && canvas.getContext('2d');\n\n // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the canvas is\n // inside an iframe or when running in a protected environment. We could guess the\n // types from their toString() value but let's keep things flexible and assume it's\n // a sufficient condition if the canvas has a context2D which has canvas as `canvas`.\n // https://github.com/chartjs/Chart.js/issues/3887\n // https://github.com/chartjs/Chart.js/issues/4102\n // https://github.com/chartjs/Chart.js/issues/4152\n if (context && context.canvas === canvas) {\n // Load platform resources on first chart creation, to make it possible to\n // import the library before setting platform options.\n initCanvas(canvas, aspectRatio);\n return context;\n }\n\n return null;\n }\n\n /**\n\t * @param {CanvasRenderingContext2D} context\n\t */\n releaseContext(context) {\n const canvas = context.canvas;\n if (!canvas[EXPANDO_KEY]) {\n return false;\n }\n\n const initial = canvas[EXPANDO_KEY].initial;\n ['height', 'width'].forEach((prop) => {\n const value = initial[prop];\n if (isNullOrUndef(value)) {\n canvas.removeAttribute(prop);\n } else {\n canvas.setAttribute(prop, value);\n }\n });\n\n const style = initial.style || {};\n Object.keys(style).forEach((key) => {\n canvas.style[key] = style[key];\n });\n\n // The canvas render size might have been changed (and thus the state stack discarded),\n // we can't use save() and restore() to restore the initial state. So make sure that at\n // least the canvas context is reset to the default state by setting the canvas width.\n // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html\n // eslint-disable-next-line no-self-assign\n canvas.width = canvas.width;\n\n delete canvas[EXPANDO_KEY];\n return true;\n }\n\n /**\n\t *\n\t * @param {Chart} chart\n\t * @param {string} type\n\t * @param {function} listener\n\t */\n addEventListener(chart, type, listener) {\n // Can have only one listener per type, so make sure previous is removed\n this.removeEventListener(chart, type);\n\n const proxies = chart.$proxies || (chart.$proxies = {});\n const handlers = {\n attach: createAttachObserver,\n detach: createDetachObserver,\n resize: createResizeObserver\n };\n const handler = handlers[type] || createProxyAndListen;\n proxies[type] = handler(chart, type, listener);\n }\n\n\n /**\n\t * @param {Chart} chart\n\t * @param {string} type\n\t */\n removeEventListener(chart, type) {\n const proxies = chart.$proxies || (chart.$proxies = {});\n const proxy = proxies[type];\n\n if (!proxy) {\n return;\n }\n\n const handlers = {\n attach: releaseObserver,\n detach: releaseObserver,\n resize: releaseObserver\n };\n const handler = handlers[type] || removeListener;\n handler(chart, type, proxy);\n proxies[type] = undefined;\n }\n\n getDevicePixelRatio() {\n return window.devicePixelRatio;\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @param {number} [width] - content width of parent element\n\t * @param {number} [height] - content height of parent element\n\t * @param {number} [aspectRatio] - aspect ratio to maintain\n\t */\n getMaximumSize(canvas, width, height, aspectRatio) {\n return getMaximumSize(canvas, width, height, aspectRatio);\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t */\n isAttached(canvas) {\n const container = _getParentNode(canvas);\n return !!(container && container.isConnected);\n }\n}\n","import {_isDomSupported} from '../helpers/index.js';\nimport BasePlatform from './platform.base.js';\nimport BasicPlatform from './platform.basic.js';\nimport DomPlatform from './platform.dom.js';\n\nexport function _detectPlatform(canvas) {\n if (!_isDomSupported() || (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) {\n return BasicPlatform;\n }\n return DomPlatform;\n}\n\nexport {BasePlatform, BasicPlatform, DomPlatform};\n","import effects from '../helpers/helpers.easing.js';\nimport {resolve} from '../helpers/helpers.options.js';\nimport {color as helpersColor} from '../helpers/helpers.color.js';\n\nconst transparent = 'transparent';\nconst interpolators = {\n boolean(from, to, factor) {\n return factor > 0.5 ? to : from;\n },\n /**\n * @param {string} from\n * @param {string} to\n * @param {number} factor\n */\n color(from, to, factor) {\n const c0 = helpersColor(from || transparent);\n const c1 = c0.valid && helpersColor(to || transparent);\n return c1 && c1.valid\n ? c1.mix(c0, factor).hexString()\n : to;\n },\n number(from, to, factor) {\n return from + (to - from) * factor;\n }\n};\n\nexport default class Animation {\n constructor(cfg, target, prop, to) {\n const currentValue = target[prop];\n\n to = resolve([cfg.to, to, currentValue, cfg.from]);\n const from = resolve([cfg.from, currentValue, to]);\n\n this._active = true;\n this._fn = cfg.fn || interpolators[cfg.type || typeof from];\n this._easing = effects[cfg.easing] || effects.linear;\n this._start = Math.floor(Date.now() + (cfg.delay || 0));\n this._duration = this._total = Math.floor(cfg.duration);\n this._loop = !!cfg.loop;\n this._target = target;\n this._prop = prop;\n this._from = from;\n this._to = to;\n this._promises = undefined;\n }\n\n active() {\n return this._active;\n }\n\n update(cfg, to, date) {\n if (this._active) {\n this._notify(false);\n\n const currentValue = this._target[this._prop];\n const elapsed = date - this._start;\n const remain = this._duration - elapsed;\n this._start = date;\n this._duration = Math.floor(Math.max(remain, cfg.duration));\n this._total += elapsed;\n this._loop = !!cfg.loop;\n this._to = resolve([cfg.to, to, currentValue, cfg.from]);\n this._from = resolve([cfg.from, currentValue, to]);\n }\n }\n\n cancel() {\n if (this._active) {\n // update current evaluated value, for smoother animations\n this.tick(Date.now());\n this._active = false;\n this._notify(false);\n }\n }\n\n tick(date) {\n const elapsed = date - this._start;\n const duration = this._duration;\n const prop = this._prop;\n const from = this._from;\n const loop = this._loop;\n const to = this._to;\n let factor;\n\n this._active = from !== to && (loop || (elapsed < duration));\n\n if (!this._active) {\n this._target[prop] = to;\n this._notify(true);\n return;\n }\n\n if (elapsed < 0) {\n this._target[prop] = from;\n return;\n }\n\n factor = (elapsed / duration) % 2;\n factor = loop && factor > 1 ? 2 - factor : factor;\n factor = this._easing(Math.min(1, Math.max(0, factor)));\n\n this._target[prop] = this._fn(from, to, factor);\n }\n\n wait() {\n const promises = this._promises || (this._promises = []);\n return new Promise((res, rej) => {\n promises.push({res, rej});\n });\n }\n\n _notify(resolved) {\n const method = resolved ? 'res' : 'rej';\n const promises = this._promises || [];\n for (let i = 0; i < promises.length; i++) {\n promises[i][method]();\n }\n }\n}\n","import animator from './core.animator.js';\nimport Animation from './core.animation.js';\nimport defaults from './core.defaults.js';\nimport {isArray, isObject} from '../helpers/helpers.core.js';\n\nexport default class Animations {\n constructor(chart, config) {\n this._chart = chart;\n this._properties = new Map();\n this.configure(config);\n }\n\n configure(config) {\n if (!isObject(config)) {\n return;\n }\n\n const animationOptions = Object.keys(defaults.animation);\n const animatedProps = this._properties;\n\n Object.getOwnPropertyNames(config).forEach(key => {\n const cfg = config[key];\n if (!isObject(cfg)) {\n return;\n }\n const resolved = {};\n for (const option of animationOptions) {\n resolved[option] = cfg[option];\n }\n\n (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => {\n if (prop === key || !animatedProps.has(prop)) {\n animatedProps.set(prop, resolved);\n }\n });\n });\n }\n\n /**\n\t * Utility to handle animation of `options`.\n\t * @private\n\t */\n _animateOptions(target, values) {\n const newOptions = values.options;\n const options = resolveTargetOptions(target, newOptions);\n if (!options) {\n return [];\n }\n\n const animations = this._createAnimations(options, newOptions);\n if (newOptions.$shared) {\n // Going to shared options:\n // After all animations are done, assign the shared options object to the element\n // So any new updates to the shared options are observed\n awaitAll(target.options.$animations, newOptions).then(() => {\n target.options = newOptions;\n }, () => {\n // rejected, noop\n });\n }\n\n return animations;\n }\n\n /**\n\t * @private\n\t */\n _createAnimations(target, values) {\n const animatedProps = this._properties;\n const animations = [];\n const running = target.$animations || (target.$animations = {});\n const props = Object.keys(values);\n const date = Date.now();\n let i;\n\n for (i = props.length - 1; i >= 0; --i) {\n const prop = props[i];\n if (prop.charAt(0) === '$') {\n continue;\n }\n\n if (prop === 'options') {\n animations.push(...this._animateOptions(target, values));\n continue;\n }\n const value = values[prop];\n let animation = running[prop];\n const cfg = animatedProps.get(prop);\n\n if (animation) {\n if (cfg && animation.active()) {\n // There is an existing active animation, let's update that\n animation.update(cfg, value, date);\n continue;\n } else {\n animation.cancel();\n }\n }\n if (!cfg || !cfg.duration) {\n // not animated, set directly to new value\n target[prop] = value;\n continue;\n }\n\n running[prop] = animation = new Animation(cfg, target, prop, value);\n animations.push(animation);\n }\n return animations;\n }\n\n\n /**\n\t * Update `target` properties to new values, using configured animations\n\t * @param {object} target - object to update\n\t * @param {object} values - new target properties\n\t * @returns {boolean|undefined} - `true` if animations were started\n\t **/\n update(target, values) {\n if (this._properties.size === 0) {\n // Nothing is animated, just apply the new values.\n Object.assign(target, values);\n return;\n }\n\n const animations = this._createAnimations(target, values);\n\n if (animations.length) {\n animator.add(this._chart, animations);\n return true;\n }\n }\n}\n\nfunction awaitAll(animations, properties) {\n const running = [];\n const keys = Object.keys(properties);\n for (let i = 0; i < keys.length; i++) {\n const anim = animations[keys[i]];\n if (anim && anim.active()) {\n running.push(anim.wait());\n }\n }\n // @ts-ignore\n return Promise.all(running);\n}\n\nfunction resolveTargetOptions(target, newOptions) {\n if (!newOptions) {\n return;\n }\n let options = target.options;\n if (!options) {\n target.options = newOptions;\n return;\n }\n if (options.$shared) {\n // Going from shared options to distinct one:\n // Create new options object containing the old shared values and start updating that.\n target.options = options = Object.assign({}, options, {$shared: false, $animations: {}});\n }\n return options;\n}\n","import Animations from './core.animations.js';\nimport defaults from './core.defaults.js';\nimport {isArray, isFinite, isObject, valueOrDefault, resolveObjectKey, defined} from '../helpers/helpers.core.js';\nimport {listenArrayEvents, unlistenArrayEvents} from '../helpers/helpers.collection.js';\nimport {createContext, sign} from '../helpers/index.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef { import('./core.scale.js').default } Scale\n */\n\nfunction scaleClip(scale, allowedOverflow) {\n const opts = scale && scale.options || {};\n const reverse = opts.reverse;\n const min = opts.min === undefined ? allowedOverflow : 0;\n const max = opts.max === undefined ? allowedOverflow : 0;\n return {\n start: reverse ? max : min,\n end: reverse ? min : max\n };\n}\n\nfunction defaultClip(xScale, yScale, allowedOverflow) {\n if (allowedOverflow === false) {\n return false;\n }\n const x = scaleClip(xScale, allowedOverflow);\n const y = scaleClip(yScale, allowedOverflow);\n\n return {\n top: y.end,\n right: x.end,\n bottom: y.start,\n left: x.start\n };\n}\n\nfunction toClip(value) {\n let t, r, b, l;\n\n if (isObject(value)) {\n t = value.top;\n r = value.right;\n b = value.bottom;\n l = value.left;\n } else {\n t = r = b = l = value;\n }\n\n return {\n top: t,\n right: r,\n bottom: b,\n left: l,\n disabled: value === false\n };\n}\n\nfunction getSortedDatasetIndices(chart, filterVisible) {\n const keys = [];\n const metasets = chart._getSortedDatasetMetas(filterVisible);\n let i, ilen;\n\n for (i = 0, ilen = metasets.length; i < ilen; ++i) {\n keys.push(metasets[i].index);\n }\n return keys;\n}\n\nfunction applyStack(stack, value, dsIndex, options = {}) {\n const keys = stack.keys;\n const singleMode = options.mode === 'single';\n let i, ilen, datasetIndex, otherValue;\n\n if (value === null) {\n return;\n }\n\n for (i = 0, ilen = keys.length; i < ilen; ++i) {\n datasetIndex = +keys[i];\n if (datasetIndex === dsIndex) {\n if (options.all) {\n continue;\n }\n break;\n }\n otherValue = stack.values[datasetIndex];\n if (isFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) {\n value += otherValue;\n }\n }\n return value;\n}\n\nfunction convertObjectDataToArray(data) {\n const keys = Object.keys(data);\n const adata = new Array(keys.length);\n let i, ilen, key;\n for (i = 0, ilen = keys.length; i < ilen; ++i) {\n key = keys[i];\n adata[i] = {\n x: key,\n y: data[key]\n };\n }\n return adata;\n}\n\nfunction isStacked(scale, meta) {\n const stacked = scale && scale.options.stacked;\n return stacked || (stacked === undefined && meta.stack !== undefined);\n}\n\nfunction getStackKey(indexScale, valueScale, meta) {\n return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;\n}\n\nfunction getUserBounds(scale) {\n const {min, max, minDefined, maxDefined} = scale.getUserBounds();\n return {\n min: minDefined ? min : Number.NEGATIVE_INFINITY,\n max: maxDefined ? max : Number.POSITIVE_INFINITY\n };\n}\n\nfunction getOrCreateStack(stacks, stackKey, indexValue) {\n const subStack = stacks[stackKey] || (stacks[stackKey] = {});\n return subStack[indexValue] || (subStack[indexValue] = {});\n}\n\nfunction getLastIndexInStack(stack, vScale, positive, type) {\n for (const meta of vScale.getMatchingVisibleMetas(type).reverse()) {\n const value = stack[meta.index];\n if ((positive && value > 0) || (!positive && value < 0)) {\n return meta.index;\n }\n }\n\n return null;\n}\n\nfunction updateStacks(controller, parsed) {\n const {chart, _cachedMeta: meta} = controller;\n const stacks = chart._stacks || (chart._stacks = {}); // map structure is {stackKey: {datasetIndex: value}}\n const {iScale, vScale, index: datasetIndex} = meta;\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const key = getStackKey(iScale, vScale, meta);\n const ilen = parsed.length;\n let stack;\n\n for (let i = 0; i < ilen; ++i) {\n const item = parsed[i];\n const {[iAxis]: index, [vAxis]: value} = item;\n const itemStacks = item._stacks || (item._stacks = {});\n stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);\n stack[datasetIndex] = value;\n\n stack._top = getLastIndexInStack(stack, vScale, true, meta.type);\n stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type);\n\n const visualValues = stack._visualValues || (stack._visualValues = {});\n visualValues[datasetIndex] = value;\n }\n}\n\nfunction getFirstScaleId(chart, axis) {\n const scales = chart.scales;\n return Object.keys(scales).filter(key => scales[key].axis === axis).shift();\n}\n\nfunction createDatasetContext(parent, index) {\n return createContext(parent,\n {\n active: false,\n dataset: undefined,\n datasetIndex: index,\n index,\n mode: 'default',\n type: 'dataset'\n }\n );\n}\n\nfunction createDataContext(parent, index, element) {\n return createContext(parent, {\n active: false,\n dataIndex: index,\n parsed: undefined,\n raw: undefined,\n element,\n index,\n mode: 'default',\n type: 'data'\n });\n}\n\nfunction clearStacks(meta, items) {\n // Not using meta.index here, because it might be already updated if the dataset changed location\n const datasetIndex = meta.controller.index;\n const axis = meta.vScale && meta.vScale.axis;\n if (!axis) {\n return;\n }\n\n items = items || meta._parsed;\n for (const parsed of items) {\n const stacks = parsed._stacks;\n if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {\n return;\n }\n delete stacks[axis][datasetIndex];\n if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) {\n delete stacks[axis]._visualValues[datasetIndex];\n }\n }\n}\n\nconst isDirectUpdateMode = (mode) => mode === 'reset' || mode === 'none';\nconst cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached);\nconst createStack = (canStack, meta, chart) => canStack && !meta.hidden && meta._stacked\n && {keys: getSortedDatasetIndices(chart, true), values: null};\n\nexport default class DatasetController {\n\n /**\n * @type {any}\n */\n static defaults = {};\n\n /**\n * Element type used to generate a meta dataset (e.g. Chart.element.LineElement).\n */\n static datasetElementType = null;\n\n /**\n * Element type used to generate a meta data (e.g. Chart.element.PointElement).\n */\n static dataElementType = null;\n\n /**\n\t * @param {Chart} chart\n\t * @param {number} datasetIndex\n\t */\n constructor(chart, datasetIndex) {\n this.chart = chart;\n this._ctx = chart.ctx;\n this.index = datasetIndex;\n this._cachedDataOpts = {};\n this._cachedMeta = this.getMeta();\n this._type = this._cachedMeta.type;\n this.options = undefined;\n /** @type {boolean | object} */\n this._parsing = false;\n this._data = undefined;\n this._objectData = undefined;\n this._sharedOptions = undefined;\n this._drawStart = undefined;\n this._drawCount = undefined;\n this.enableOptionSharing = false;\n this.supportsDecimation = false;\n this.$context = undefined;\n this._syncList = [];\n this.datasetElementType = new.target.datasetElementType;\n this.dataElementType = new.target.dataElementType;\n\n this.initialize();\n }\n\n initialize() {\n const meta = this._cachedMeta;\n this.configure();\n this.linkScales();\n meta._stacked = isStacked(meta.vScale, meta);\n this.addElements();\n\n if (this.options.fill && !this.chart.isPluginEnabled('filler')) {\n console.warn(\"Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options\");\n }\n }\n\n updateIndex(datasetIndex) {\n if (this.index !== datasetIndex) {\n clearStacks(this._cachedMeta);\n }\n this.index = datasetIndex;\n }\n\n linkScales() {\n const chart = this.chart;\n const meta = this._cachedMeta;\n const dataset = this.getDataset();\n\n const chooseId = (axis, x, y, r) => axis === 'x' ? x : axis === 'r' ? r : y;\n\n const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));\n const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));\n const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));\n const indexAxis = meta.indexAxis;\n const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);\n const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);\n meta.xScale = this.getScaleForId(xid);\n meta.yScale = this.getScaleForId(yid);\n meta.rScale = this.getScaleForId(rid);\n meta.iScale = this.getScaleForId(iid);\n meta.vScale = this.getScaleForId(vid);\n }\n\n getDataset() {\n return this.chart.data.datasets[this.index];\n }\n\n getMeta() {\n return this.chart.getDatasetMeta(this.index);\n }\n\n /**\n\t * @param {string} scaleID\n\t * @return {Scale}\n\t */\n getScaleForId(scaleID) {\n return this.chart.scales[scaleID];\n }\n\n /**\n\t * @private\n\t */\n _getOtherScale(scale) {\n const meta = this._cachedMeta;\n return scale === meta.iScale\n ? meta.vScale\n : meta.iScale;\n }\n\n reset() {\n this._update('reset');\n }\n\n /**\n\t * @private\n\t */\n _destroy() {\n const meta = this._cachedMeta;\n if (this._data) {\n unlistenArrayEvents(this._data, this);\n }\n if (meta._stacked) {\n clearStacks(meta);\n }\n }\n\n /**\n\t * @private\n\t */\n _dataCheck() {\n const dataset = this.getDataset();\n const data = dataset.data || (dataset.data = []);\n const _data = this._data;\n\n // In order to correctly handle data addition/deletion animation (and thus simulate\n // real-time charts), we need to monitor these data modifications and synchronize\n // the internal metadata accordingly.\n\n if (isObject(data)) {\n this._data = convertObjectDataToArray(data);\n } else if (_data !== data) {\n if (_data) {\n // This case happens when the user replaced the data array instance.\n unlistenArrayEvents(_data, this);\n // Discard old parsed data and stacks\n const meta = this._cachedMeta;\n clearStacks(meta);\n meta._parsed = [];\n }\n if (data && Object.isExtensible(data)) {\n listenArrayEvents(data, this);\n }\n this._syncList = [];\n this._data = data;\n }\n }\n\n addElements() {\n const meta = this._cachedMeta;\n\n this._dataCheck();\n\n if (this.datasetElementType) {\n meta.dataset = new this.datasetElementType();\n }\n }\n\n buildOrUpdateElements(resetNewElements) {\n const meta = this._cachedMeta;\n const dataset = this.getDataset();\n let stackChanged = false;\n\n this._dataCheck();\n\n // make sure cached _stacked status is current\n const oldStacked = meta._stacked;\n meta._stacked = isStacked(meta.vScale, meta);\n\n // detect change in stack option\n if (meta.stack !== dataset.stack) {\n stackChanged = true;\n // remove values from old stack\n clearStacks(meta);\n meta.stack = dataset.stack;\n }\n\n // Re-sync meta data in case the user replaced the data array or if we missed\n // any updates and so make sure that we handle number of datapoints changing.\n this._resyncElements(resetNewElements);\n\n // if stack changed, update stack values for the whole dataset\n if (stackChanged || oldStacked !== meta._stacked) {\n updateStacks(this, meta._parsed);\n }\n }\n\n /**\n\t * Merges user-supplied and default dataset-level options\n\t * @private\n\t */\n configure() {\n const config = this.chart.config;\n const scopeKeys = config.datasetScopeKeys(this._type);\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true);\n this.options = config.createResolver(scopes, this.getContext());\n this._parsing = this.options.parsing;\n this._cachedDataOpts = {};\n }\n\n /**\n\t * @param {number} start\n\t * @param {number} count\n\t */\n parse(start, count) {\n const {_cachedMeta: meta, _data: data} = this;\n const {iScale, _stacked} = meta;\n const iAxis = iScale.axis;\n\n let sorted = start === 0 && count === data.length ? true : meta._sorted;\n let prev = start > 0 && meta._parsed[start - 1];\n let i, cur, parsed;\n\n if (this._parsing === false) {\n meta._parsed = data;\n meta._sorted = true;\n parsed = data;\n } else {\n if (isArray(data[start])) {\n parsed = this.parseArrayData(meta, data, start, count);\n } else if (isObject(data[start])) {\n parsed = this.parseObjectData(meta, data, start, count);\n } else {\n parsed = this.parsePrimitiveData(meta, data, start, count);\n }\n\n const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]);\n for (i = 0; i < count; ++i) {\n meta._parsed[i + start] = cur = parsed[i];\n if (sorted) {\n if (isNotInOrderComparedToPrev()) {\n sorted = false;\n }\n prev = cur;\n }\n }\n meta._sorted = sorted;\n }\n\n if (_stacked) {\n updateStacks(this, parsed);\n }\n }\n\n /**\n\t * Parse array of primitive values\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [1,3,4]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id.\n\t * Example: {xScale0: 0, yScale0: 1}\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n const {iScale, vScale} = meta;\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const labels = iScale.getLabels();\n const singleScale = iScale === vScale;\n const parsed = new Array(count);\n let i, ilen, index;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n parsed[i] = {\n [iAxis]: singleScale || iScale.parse(labels[index], index),\n [vAxis]: vScale.parse(data[index], index)\n };\n }\n return parsed;\n }\n\n /**\n\t * Parse array of arrays\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [[1,2],[3,4]]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id.\n\t * Example: {x: 0, y: 1}\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n const {xScale, yScale} = meta;\n const parsed = new Array(count);\n let i, ilen, index, item;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n x: xScale.parse(item[0], index),\n y: yScale.parse(item[1], index)\n };\n }\n return parsed;\n }\n\n /**\n\t * Parse array of objects\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [{x:1, y:5}, {x:2, y:10}]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id. _custom is optional\n\t * Example: {xScale0: 0, yScale0: 1, _custom: {r: 10, foo: 'bar'}}\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const {xScale, yScale} = meta;\n const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;\n const parsed = new Array(count);\n let i, ilen, index, item;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n x: xScale.parse(resolveObjectKey(item, xAxisKey), index),\n y: yScale.parse(resolveObjectKey(item, yAxisKey), index)\n };\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n getParsed(index) {\n return this._cachedMeta._parsed[index];\n }\n\n /**\n\t * @protected\n\t */\n getDataElement(index) {\n return this._cachedMeta.data[index];\n }\n\n /**\n\t * @protected\n\t */\n applyStack(scale, parsed, mode) {\n const chart = this.chart;\n const meta = this._cachedMeta;\n const value = parsed[scale.axis];\n const stack = {\n keys: getSortedDatasetIndices(chart, true),\n values: parsed._stacks[scale.axis]._visualValues\n };\n return applyStack(stack, value, meta.index, {mode});\n }\n\n /**\n\t * @protected\n\t */\n updateRangeFromParsed(range, scale, parsed, stack) {\n const parsedValue = parsed[scale.axis];\n let value = parsedValue === null ? NaN : parsedValue;\n const values = stack && parsed._stacks[scale.axis];\n if (stack && values) {\n stack.values = values;\n value = applyStack(stack, parsedValue, this._cachedMeta.index);\n }\n range.min = Math.min(range.min, value);\n range.max = Math.max(range.max, value);\n }\n\n /**\n\t * @protected\n\t */\n getMinMax(scale, canStack) {\n const meta = this._cachedMeta;\n const _parsed = meta._parsed;\n const sorted = meta._sorted && scale === meta.iScale;\n const ilen = _parsed.length;\n const otherScale = this._getOtherScale(scale);\n const stack = createStack(canStack, meta, this.chart);\n const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};\n const {min: otherMin, max: otherMax} = getUserBounds(otherScale);\n let i, parsed;\n\n function _skip() {\n parsed = _parsed[i];\n const otherValue = parsed[otherScale.axis];\n return !isFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue;\n }\n\n for (i = 0; i < ilen; ++i) {\n if (_skip()) {\n continue;\n }\n this.updateRangeFromParsed(range, scale, parsed, stack);\n if (sorted) {\n // if the data is sorted, we don't need to check further from this end of array\n break;\n }\n }\n if (sorted) {\n // in the sorted case, find first non-skipped value from other end of array\n for (i = ilen - 1; i >= 0; --i) {\n if (_skip()) {\n continue;\n }\n this.updateRangeFromParsed(range, scale, parsed, stack);\n break;\n }\n }\n return range;\n }\n\n getAllParsedValues(scale) {\n const parsed = this._cachedMeta._parsed;\n const values = [];\n let i, ilen, value;\n\n for (i = 0, ilen = parsed.length; i < ilen; ++i) {\n value = parsed[i][scale.axis];\n if (isFinite(value)) {\n values.push(value);\n }\n }\n return values;\n }\n\n /**\n\t * @return {number|boolean}\n\t * @protected\n\t */\n getMaxOverflow() {\n return false;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const vScale = meta.vScale;\n const parsed = this.getParsed(index);\n return {\n label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',\n value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''\n };\n }\n\n /**\n\t * @private\n\t */\n _update(mode) {\n const meta = this._cachedMeta;\n this.update(mode || 'default');\n meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow())));\n }\n\n /**\n\t * @param {string} mode\n\t */\n update(mode) {} // eslint-disable-line no-unused-vars\n\n draw() {\n const ctx = this._ctx;\n const chart = this.chart;\n const meta = this._cachedMeta;\n const elements = meta.data || [];\n const area = chart.chartArea;\n const active = [];\n const start = this._drawStart || 0;\n const count = this._drawCount || (elements.length - start);\n const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop;\n let i;\n\n if (meta.dataset) {\n meta.dataset.draw(ctx, area, start, count);\n }\n\n for (i = start; i < start + count; ++i) {\n const element = elements[i];\n if (element.hidden) {\n continue;\n }\n if (element.active && drawActiveElementsOnTop) {\n active.push(element);\n } else {\n element.draw(ctx, area);\n }\n }\n\n for (i = 0; i < active.length; ++i) {\n active[i].draw(ctx, area);\n }\n }\n\n /**\n\t * Returns a set of predefined style properties that should be used to represent the dataset\n\t * or the data if the index is specified\n\t * @param {number} index - data index\n\t * @param {boolean} [active] - true if hover\n\t * @return {object} style object\n\t */\n getStyle(index, active) {\n const mode = active ? 'active' : 'default';\n return index === undefined && this._cachedMeta.dataset\n ? this.resolveDatasetElementOptions(mode)\n : this.resolveDataElementOptions(index || 0, mode);\n }\n\n /**\n\t * @protected\n\t */\n getContext(index, active, mode) {\n const dataset = this.getDataset();\n let context;\n if (index >= 0 && index < this._cachedMeta.data.length) {\n const element = this._cachedMeta.data[index];\n context = element.$context ||\n (element.$context = createDataContext(this.getContext(), index, element));\n context.parsed = this.getParsed(index);\n context.raw = dataset.data[index];\n context.index = context.dataIndex = index;\n } else {\n context = this.$context ||\n (this.$context = createDatasetContext(this.chart.getContext(), this.index));\n context.dataset = dataset;\n context.index = context.datasetIndex = this.index;\n }\n\n context.active = !!active;\n context.mode = mode;\n return context;\n }\n\n /**\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDatasetElementOptions(mode) {\n return this._resolveElementOptions(this.datasetElementType.id, mode);\n }\n\n /**\n\t * @param {number} index\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDataElementOptions(index, mode) {\n return this._resolveElementOptions(this.dataElementType.id, mode, index);\n }\n\n /**\n\t * @private\n\t */\n _resolveElementOptions(elementType, mode = 'default', index) {\n const active = mode === 'active';\n const cache = this._cachedDataOpts;\n const cacheKey = elementType + '-' + mode;\n const cached = cache[cacheKey];\n const sharing = this.enableOptionSharing && defined(index);\n if (cached) {\n return cloneIfNotShared(cached, sharing);\n }\n const config = this.chart.config;\n const scopeKeys = config.datasetElementScopeKeys(this._type, elementType);\n const prefixes = active ? [`${elementType}Hover`, 'hover', elementType, ''] : [elementType, ''];\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);\n const names = Object.keys(defaults.elements[elementType]);\n // context is provided as a function, and is called only if needed,\n // so we don't create a context for each element if not needed.\n const context = () => this.getContext(index, active, mode);\n const values = config.resolveNamedOptions(scopes, names, context, prefixes);\n\n if (values.$shared) {\n // `$shared` indicates this set of options can be shared between multiple elements.\n // Sharing is used to reduce number of properties to change during animation.\n values.$shared = sharing;\n\n // We cache options by `mode`, which can be 'active' for example. This enables us\n // to have the 'active' element options and 'default' options to switch between\n // when interacting.\n cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));\n }\n\n return values;\n }\n\n\n /**\n\t * @private\n\t */\n _resolveAnimations(index, transition, active) {\n const chart = this.chart;\n const cache = this._cachedDataOpts;\n const cacheKey = `animation-${transition}`;\n const cached = cache[cacheKey];\n if (cached) {\n return cached;\n }\n let options;\n if (chart.options.animation !== false) {\n const config = this.chart.config;\n const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition);\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);\n options = config.createResolver(scopes, this.getContext(index, active, transition));\n }\n const animations = new Animations(chart, options && options.animations);\n if (options && options._cacheable) {\n cache[cacheKey] = Object.freeze(animations);\n }\n return animations;\n }\n\n /**\n\t * Utility for getting the options object shared between elements\n\t * @protected\n\t */\n getSharedOptions(options) {\n if (!options.$shared) {\n return;\n }\n return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));\n }\n\n /**\n\t * Utility for determining if `options` should be included in the updated properties\n\t * @protected\n\t */\n includeOptions(mode, sharedOptions) {\n return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;\n }\n\n /**\n * @todo v4, rename to getSharedOptions and remove excess functions\n */\n _getSharedOptions(start, mode) {\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const previouslySharedOptions = this._sharedOptions;\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions) || (sharedOptions !== previouslySharedOptions);\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n return {sharedOptions, includeOptions};\n }\n\n /**\n\t * Utility for updating an element with new properties, using animations when appropriate.\n\t * @protected\n\t */\n updateElement(element, index, properties, mode) {\n if (isDirectUpdateMode(mode)) {\n Object.assign(element, properties);\n } else {\n this._resolveAnimations(index, mode).update(element, properties);\n }\n }\n\n /**\n\t * Utility to animate the shared options, that are potentially affecting multiple elements.\n\t * @protected\n\t */\n updateSharedOptions(sharedOptions, mode, newOptions) {\n if (sharedOptions && !isDirectUpdateMode(mode)) {\n this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);\n }\n }\n\n /**\n\t * @private\n\t */\n _setStyle(element, index, mode, active) {\n element.active = active;\n const options = this.getStyle(index, active);\n this._resolveAnimations(index, mode, active).update(element, {\n // When going from active to inactive, we need to update to the shared options.\n // This way the once hovered element will end up with the same original shared options instance, after animation.\n options: (!active && this.getSharedOptions(options)) || options\n });\n }\n\n removeHoverStyle(element, datasetIndex, index) {\n this._setStyle(element, index, 'active', false);\n }\n\n setHoverStyle(element, datasetIndex, index) {\n this._setStyle(element, index, 'active', true);\n }\n\n /**\n\t * @private\n\t */\n _removeDatasetHoverStyle() {\n const element = this._cachedMeta.dataset;\n\n if (element) {\n this._setStyle(element, undefined, 'active', false);\n }\n }\n\n /**\n\t * @private\n\t */\n _setDatasetHoverStyle() {\n const element = this._cachedMeta.dataset;\n\n if (element) {\n this._setStyle(element, undefined, 'active', true);\n }\n }\n\n /**\n\t * @private\n\t */\n _resyncElements(resetNewElements) {\n const data = this._data;\n const elements = this._cachedMeta.data;\n\n // Apply changes detected through array listeners\n for (const [method, arg1, arg2] of this._syncList) {\n this[method](arg1, arg2);\n }\n this._syncList = [];\n\n const numMeta = elements.length;\n const numData = data.length;\n const count = Math.min(numData, numMeta);\n\n if (count) {\n // TODO: It is not optimal to always parse the old data\n // This is done because we are not detecting direct assignments:\n // chart.data.datasets[0].data[5] = 10;\n // chart.data.datasets[0].data[5].y = 10;\n this.parse(0, count);\n }\n\n if (numData > numMeta) {\n this._insertElements(numMeta, numData - numMeta, resetNewElements);\n } else if (numData < numMeta) {\n this._removeElements(numData, numMeta - numData);\n }\n }\n\n /**\n\t * @private\n\t */\n _insertElements(start, count, resetNewElements = true) {\n const meta = this._cachedMeta;\n const data = meta.data;\n const end = start + count;\n let i;\n\n const move = (arr) => {\n arr.length += count;\n for (i = arr.length - 1; i >= end; i--) {\n arr[i] = arr[i - count];\n }\n };\n move(data);\n\n for (i = start; i < end; ++i) {\n data[i] = new this.dataElementType();\n }\n\n if (this._parsing) {\n move(meta._parsed);\n }\n this.parse(start, count);\n\n if (resetNewElements) {\n this.updateElements(data, start, count, 'reset');\n }\n }\n\n updateElements(element, start, count, mode) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * @private\n\t */\n _removeElements(start, count) {\n const meta = this._cachedMeta;\n if (this._parsing) {\n const removed = meta._parsed.splice(start, count);\n if (meta._stacked) {\n clearStacks(meta, removed);\n }\n }\n meta.data.splice(start, count);\n }\n\n /**\n\t * @private\n */\n _sync(args) {\n if (this._parsing) {\n this._syncList.push(args);\n } else {\n const [method, arg1, arg2] = args;\n this[method](arg1, arg2);\n }\n this.chart._dataChanges.push([this.index, ...args]);\n }\n\n _onDataPush() {\n const count = arguments.length;\n this._sync(['_insertElements', this.getDataset().data.length - count, count]);\n }\n\n _onDataPop() {\n this._sync(['_removeElements', this._cachedMeta.data.length - 1, 1]);\n }\n\n _onDataShift() {\n this._sync(['_removeElements', 0, 1]);\n }\n\n _onDataSplice(start, count) {\n if (count) {\n this._sync(['_removeElements', start, count]);\n }\n const newCount = arguments.length - 2;\n if (newCount) {\n this._sync(['_insertElements', start, newCount]);\n }\n }\n\n _onDataUnshift() {\n this._sync(['_insertElements', 0, arguments.length]);\n }\n}\n","import type {AnyObject} from '../types/basic.js';\nimport type {Point} from '../types/geometric.js';\nimport type {Animation} from '../types/animation.js';\nimport {isNumber} from '../helpers/helpers.math.js';\n\nexport default class Element {\n\n static defaults = {};\n static defaultRoutes = undefined;\n\n x: number;\n y: number;\n active = false;\n options: O;\n $animations: Record;\n\n tooltipPosition(useFinalPosition: boolean): Point {\n const {x, y} = this.getProps(['x', 'y'], useFinalPosition);\n return {x, y} as Point;\n }\n\n hasValue() {\n return isNumber(this.x) && isNumber(this.y);\n }\n\n /**\n * Gets the current or final value of each prop. Can return extra properties (whole object).\n * @param props - properties to get\n * @param [final] - get the final value (animation target)\n */\n getProps

(props: P, final?: boolean): Pick;\n getProps

(props: P[], final?: boolean): Partial>;\n getProps(props: string[], final?: boolean): Partial> {\n const anims = this.$animations;\n if (!final || !anims) {\n // let's not create an object, if not needed\n return this as Record;\n }\n const ret: Record = {};\n props.forEach((prop) => {\n ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop as string];\n });\n return ret;\n }\n}\n","import {isNullOrUndef, valueOrDefault} from '../helpers/helpers.core.js';\nimport {_factorize} from '../helpers/helpers.math.js';\n\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef {{value:number | string, label?:string, major?:boolean, $context?:any}} Tick\n */\n\n/**\n * Returns a subset of ticks to be plotted to avoid overlapping labels.\n * @param {import('./core.scale.js').default} scale\n * @param {Tick[]} ticks\n * @return {Tick[]}\n * @private\n */\nexport function autoSkip(scale, ticks) {\n const tickOpts = scale.options.ticks;\n const determinedMaxTicks = determineMaxTicks(scale);\n const ticksLimit = Math.min(tickOpts.maxTicksLimit || determinedMaxTicks, determinedMaxTicks);\n const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];\n const numMajorIndices = majorIndices.length;\n const first = majorIndices[0];\n const last = majorIndices[numMajorIndices - 1];\n const newTicks = [];\n\n // If there are too many major ticks to display them all\n if (numMajorIndices > ticksLimit) {\n skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);\n return newTicks;\n }\n\n const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);\n\n if (numMajorIndices > 0) {\n let i, ilen;\n const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;\n skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);\n for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {\n skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);\n }\n skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);\n return newTicks;\n }\n skip(ticks, newTicks, spacing);\n return newTicks;\n}\n\nfunction determineMaxTicks(scale) {\n const offset = scale.options.offset;\n const tickLength = scale._tickSize();\n const maxScale = scale._length / tickLength + (offset ? 0 : 1);\n const maxChart = scale._maxLength / tickLength;\n return Math.floor(Math.min(maxScale, maxChart));\n}\n\n/**\n * @param {number[]} majorIndices\n * @param {Tick[]} ticks\n * @param {number} ticksLimit\n */\nfunction calculateSpacing(majorIndices, ticks, ticksLimit) {\n const evenMajorSpacing = getEvenSpacing(majorIndices);\n const spacing = ticks.length / ticksLimit;\n\n // If the major ticks are evenly spaced apart, place the minor ticks\n // so that they divide the major ticks into even chunks\n if (!evenMajorSpacing) {\n return Math.max(spacing, 1);\n }\n\n const factors = _factorize(evenMajorSpacing);\n for (let i = 0, ilen = factors.length - 1; i < ilen; i++) {\n const factor = factors[i];\n if (factor > spacing) {\n return factor;\n }\n }\n return Math.max(spacing, 1);\n}\n\n/**\n * @param {Tick[]} ticks\n */\nfunction getMajorIndices(ticks) {\n const result = [];\n let i, ilen;\n for (i = 0, ilen = ticks.length; i < ilen; i++) {\n if (ticks[i].major) {\n result.push(i);\n }\n }\n return result;\n}\n\n/**\n * @param {Tick[]} ticks\n * @param {Tick[]} newTicks\n * @param {number[]} majorIndices\n * @param {number} spacing\n */\nfunction skipMajors(ticks, newTicks, majorIndices, spacing) {\n let count = 0;\n let next = majorIndices[0];\n let i;\n\n spacing = Math.ceil(spacing);\n for (i = 0; i < ticks.length; i++) {\n if (i === next) {\n newTicks.push(ticks[i]);\n count++;\n next = majorIndices[count * spacing];\n }\n }\n}\n\n/**\n * @param {Tick[]} ticks\n * @param {Tick[]} newTicks\n * @param {number} spacing\n * @param {number} [majorStart]\n * @param {number} [majorEnd]\n */\nfunction skip(ticks, newTicks, spacing, majorStart, majorEnd) {\n const start = valueOrDefault(majorStart, 0);\n const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);\n let count = 0;\n let length, i, next;\n\n spacing = Math.ceil(spacing);\n if (majorEnd) {\n length = majorEnd - majorStart;\n spacing = length / Math.floor(length / spacing);\n }\n\n next = start;\n\n while (next < 0) {\n count++;\n next = Math.round(start + count * spacing);\n }\n\n for (i = Math.max(start, 0); i < end; i++) {\n if (i === next) {\n newTicks.push(ticks[i]);\n count++;\n next = Math.round(start + count * spacing);\n }\n }\n}\n\n\n/**\n * @param {number[]} arr\n */\nfunction getEvenSpacing(arr) {\n const len = arr.length;\n let i, diff;\n\n if (len < 2) {\n return false;\n }\n\n for (diff = arr[0], i = 1; i < len; ++i) {\n if (arr[i] - arr[i - 1] !== diff) {\n return false;\n }\n }\n return diff;\n}\n","import Element from './core.element.js';\nimport {_alignPixel, _measureText, renderText, clipArea, unclipArea} from '../helpers/helpers.canvas.js';\nimport {callback as call, each, finiteOrDefault, isArray, isFinite, isNullOrUndef, isObject, valueOrDefault} from '../helpers/helpers.core.js';\nimport {toDegrees, toRadians, _int16Range, _limitValue, HALF_PI} from '../helpers/helpers.math.js';\nimport {_alignStartEnd, _toLeftRightCenter} from '../helpers/helpers.extras.js';\nimport {createContext, toFont, toPadding, _addGrace} from '../helpers/helpers.options.js';\nimport {autoSkip} from './core.scale.autoskip.js';\n\nconst reverseAlign = (align) => align === 'left' ? 'right' : align === 'right' ? 'left' : align;\nconst offsetFromEdge = (scale, edge, offset) => edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;\nconst getTicksLimit = (ticksLength, maxTicksLimit) => Math.min(maxTicksLimit || ticksLength, ticksLength);\n\n/**\n * @typedef { import('../types/index.js').Chart } Chart\n * @typedef {{value:number | string, label?:string, major?:boolean, $context?:any}} Tick\n */\n\n/**\n * Returns a new array containing numItems from arr\n * @param {any[]} arr\n * @param {number} numItems\n */\nfunction sample(arr, numItems) {\n const result = [];\n const increment = arr.length / numItems;\n const len = arr.length;\n let i = 0;\n\n for (; i < len; i += increment) {\n result.push(arr[Math.floor(i)]);\n }\n return result;\n}\n\n/**\n * @param {Scale} scale\n * @param {number} index\n * @param {boolean} offsetGridLines\n */\nfunction getPixelForGridLine(scale, index, offsetGridLines) {\n const length = scale.ticks.length;\n const validIndex = Math.min(index, length - 1);\n const start = scale._startPixel;\n const end = scale._endPixel;\n const epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.\n let lineValue = scale.getPixelForTick(validIndex);\n let offset;\n\n if (offsetGridLines) {\n if (length === 1) {\n offset = Math.max(lineValue - start, end - lineValue);\n } else if (index === 0) {\n offset = (scale.getPixelForTick(1) - lineValue) / 2;\n } else {\n offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;\n }\n lineValue += validIndex < index ? offset : -offset;\n\n // Return undefined if the pixel is out of the range\n if (lineValue < start - epsilon || lineValue > end + epsilon) {\n return;\n }\n }\n return lineValue;\n}\n\n/**\n * @param {object} caches\n * @param {number} length\n */\nfunction garbageCollect(caches, length) {\n each(caches, (cache) => {\n const gc = cache.gc;\n const gcLen = gc.length / 2;\n let i;\n if (gcLen > length) {\n for (i = 0; i < gcLen; ++i) {\n delete cache.data[gc[i]];\n }\n gc.splice(0, gcLen);\n }\n });\n}\n\n/**\n * @param {object} options\n */\nfunction getTickMarkLength(options) {\n return options.drawTicks ? options.tickLength : 0;\n}\n\n/**\n * @param {object} options\n */\nfunction getTitleHeight(options, fallback) {\n if (!options.display) {\n return 0;\n }\n\n const font = toFont(options.font, fallback);\n const padding = toPadding(options.padding);\n const lines = isArray(options.text) ? options.text.length : 1;\n\n return (lines * font.lineHeight) + padding.height;\n}\n\nfunction createScaleContext(parent, scale) {\n return createContext(parent, {\n scale,\n type: 'scale'\n });\n}\n\nfunction createTickContext(parent, index, tick) {\n return createContext(parent, {\n tick,\n index,\n type: 'tick'\n });\n}\n\nfunction titleAlign(align, position, reverse) {\n /** @type {CanvasTextAlign} */\n let ret = _toLeftRightCenter(align);\n if ((reverse && position !== 'right') || (!reverse && position === 'right')) {\n ret = reverseAlign(ret);\n }\n return ret;\n}\n\nfunction titleArgs(scale, offset, position, align) {\n const {top, left, bottom, right, chart} = scale;\n const {chartArea, scales} = chart;\n let rotation = 0;\n let maxWidth, titleX, titleY;\n const height = bottom - top;\n const width = right - left;\n\n if (scale.isHorizontal()) {\n titleX = _alignStartEnd(align, left, right);\n\n if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n titleY = scales[positionAxisID].getPixelForValue(value) + height - offset;\n } else if (position === 'center') {\n titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset;\n } else {\n titleY = offsetFromEdge(scale, position, offset);\n }\n maxWidth = right - left;\n } else {\n if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n titleX = scales[positionAxisID].getPixelForValue(value) - width + offset;\n } else if (position === 'center') {\n titleX = (chartArea.left + chartArea.right) / 2 - width + offset;\n } else {\n titleX = offsetFromEdge(scale, position, offset);\n }\n titleY = _alignStartEnd(align, bottom, top);\n rotation = position === 'left' ? -HALF_PI : HALF_PI;\n }\n return {titleX, titleY, maxWidth, rotation};\n}\n\nexport default class Scale extends Element {\n\n // eslint-disable-next-line max-statements\n constructor(cfg) {\n super();\n\n /** @type {string} */\n this.id = cfg.id;\n /** @type {string} */\n this.type = cfg.type;\n /** @type {any} */\n this.options = undefined;\n /** @type {CanvasRenderingContext2D} */\n this.ctx = cfg.ctx;\n /** @type {Chart} */\n this.chart = cfg.chart;\n\n // implements box\n /** @type {number} */\n this.top = undefined;\n /** @type {number} */\n this.bottom = undefined;\n /** @type {number} */\n this.left = undefined;\n /** @type {number} */\n this.right = undefined;\n /** @type {number} */\n this.width = undefined;\n /** @type {number} */\n this.height = undefined;\n this._margins = {\n left: 0,\n right: 0,\n top: 0,\n bottom: 0\n };\n /** @type {number} */\n this.maxWidth = undefined;\n /** @type {number} */\n this.maxHeight = undefined;\n /** @type {number} */\n this.paddingTop = undefined;\n /** @type {number} */\n this.paddingBottom = undefined;\n /** @type {number} */\n this.paddingLeft = undefined;\n /** @type {number} */\n this.paddingRight = undefined;\n\n // scale-specific properties\n /** @type {string=} */\n this.axis = undefined;\n /** @type {number=} */\n this.labelRotation = undefined;\n this.min = undefined;\n this.max = undefined;\n this._range = undefined;\n /** @type {Tick[]} */\n this.ticks = [];\n /** @type {object[]|null} */\n this._gridLineItems = null;\n /** @type {object[]|null} */\n this._labelItems = null;\n /** @type {object|null} */\n this._labelSizes = null;\n this._length = 0;\n this._maxLength = 0;\n this._longestTextCache = {};\n /** @type {number} */\n this._startPixel = undefined;\n /** @type {number} */\n this._endPixel = undefined;\n this._reversePixels = false;\n this._userMax = undefined;\n this._userMin = undefined;\n this._suggestedMax = undefined;\n this._suggestedMin = undefined;\n this._ticksLength = 0;\n this._borderValue = 0;\n this._cache = {};\n this._dataLimitsCached = false;\n this.$context = undefined;\n }\n\n /**\n\t * @param {any} options\n\t * @since 3.0\n\t */\n init(options) {\n this.options = options.setContext(this.getContext());\n\n this.axis = options.axis;\n\n // parse min/max value, so we can properly determine min/max for other scales\n this._userMin = this.parse(options.min);\n this._userMax = this.parse(options.max);\n this._suggestedMin = this.parse(options.suggestedMin);\n this._suggestedMax = this.parse(options.suggestedMax);\n }\n\n /**\n\t * Parse a supported input value to internal representation.\n\t * @param {*} raw\n\t * @param {number} [index]\n\t * @since 3.0\n\t */\n parse(raw, index) { // eslint-disable-line no-unused-vars\n return raw;\n }\n\n /**\n\t * @return {{min: number, max: number, minDefined: boolean, maxDefined: boolean}}\n\t * @protected\n\t * @since 3.0\n\t */\n getUserBounds() {\n let {_userMin, _userMax, _suggestedMin, _suggestedMax} = this;\n _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);\n _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);\n _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);\n _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);\n return {\n min: finiteOrDefault(_userMin, _suggestedMin),\n max: finiteOrDefault(_userMax, _suggestedMax),\n minDefined: isFinite(_userMin),\n maxDefined: isFinite(_userMax)\n };\n }\n\n /**\n\t * @param {boolean} canStack\n\t * @return {{min: number, max: number}}\n\t * @protected\n\t * @since 3.0\n\t */\n getMinMax(canStack) {\n // eslint-disable-next-line prefer-const\n let {min, max, minDefined, maxDefined} = this.getUserBounds();\n let range;\n\n if (minDefined && maxDefined) {\n return {min, max};\n }\n\n const metas = this.getMatchingVisibleMetas();\n for (let i = 0, ilen = metas.length; i < ilen; ++i) {\n range = metas[i].controller.getMinMax(this, canStack);\n if (!minDefined) {\n min = Math.min(min, range.min);\n }\n if (!maxDefined) {\n max = Math.max(max, range.max);\n }\n }\n\n // Make sure min <= max when only min or max is defined by user and the data is outside that range\n min = maxDefined && min > max ? max : min;\n max = minDefined && min > max ? min : max;\n\n return {\n min: finiteOrDefault(min, finiteOrDefault(max, min)),\n max: finiteOrDefault(max, finiteOrDefault(min, max))\n };\n }\n\n /**\n\t * Get the padding needed for the scale\n\t * @return {{top: number, left: number, bottom: number, right: number}} the necessary padding\n\t * @private\n\t */\n getPadding() {\n return {\n left: this.paddingLeft || 0,\n top: this.paddingTop || 0,\n right: this.paddingRight || 0,\n bottom: this.paddingBottom || 0\n };\n }\n\n /**\n\t * Returns the scale tick objects\n\t * @return {Tick[]}\n\t * @since 2.7\n\t */\n getTicks() {\n return this.ticks;\n }\n\n /**\n\t * @return {string[]}\n\t */\n getLabels() {\n const data = this.chart.data;\n return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];\n }\n\n /**\n * @return {import('../types.js').LabelItem[]}\n */\n getLabelItems(chartArea = this.chart.chartArea) {\n const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea));\n return items;\n }\n\n // When a new layout is created, reset the data limits cache\n beforeLayout() {\n this._cache = {};\n this._dataLimitsCached = false;\n }\n\n // These methods are ordered by lifecycle. Utilities then follow.\n // Any function defined here is inherited by all scale types.\n // Any function can be extended by the scale type\n\n beforeUpdate() {\n call(this.options.beforeUpdate, [this]);\n }\n\n /**\n\t * @param {number} maxWidth - the max width in pixels\n\t * @param {number} maxHeight - the max height in pixels\n\t * @param {{top: number, left: number, bottom: number, right: number}} margins - the space between the edge of the other scales and edge of the chart\n\t * This space comes from two sources:\n\t * - padding - space that's required to show the labels at the edges of the scale\n\t * - thickness of scales or legends in another orientation\n\t */\n update(maxWidth, maxHeight, margins) {\n const {beginAtZero, grace, ticks: tickOpts} = this.options;\n const sampleSize = tickOpts.sampleSize;\n\n // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)\n this.beforeUpdate();\n\n // Absorb the master measurements\n this.maxWidth = maxWidth;\n this.maxHeight = maxHeight;\n this._margins = margins = Object.assign({\n left: 0,\n right: 0,\n top: 0,\n bottom: 0\n }, margins);\n\n this.ticks = null;\n this._labelSizes = null;\n this._gridLineItems = null;\n this._labelItems = null;\n\n // Dimensions\n this.beforeSetDimensions();\n this.setDimensions();\n this.afterSetDimensions();\n\n this._maxLength = this.isHorizontal()\n ? this.width + margins.left + margins.right\n : this.height + margins.top + margins.bottom;\n\n // Data min/max\n if (!this._dataLimitsCached) {\n this.beforeDataLimits();\n this.determineDataLimits();\n this.afterDataLimits();\n this._range = _addGrace(this, grace, beginAtZero);\n this._dataLimitsCached = true;\n }\n\n this.beforeBuildTicks();\n\n this.ticks = this.buildTicks() || [];\n\n // Allow modification of ticks in callback.\n this.afterBuildTicks();\n\n // Compute tick rotation and fit using a sampled subset of labels\n // We generally don't need to compute the size of every single label for determining scale size\n const samplingEnabled = sampleSize < this.ticks.length;\n this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks);\n\n // configure is called twice, once here, once from core.controller.updateLayout.\n // Here we haven't been positioned yet, but dimensions are correct.\n // Variables set in configure are needed for calculateLabelRotation, and\n // it's ok that coordinates are not correct there, only dimensions matter.\n this.configure();\n\n // Tick Rotation\n this.beforeCalculateLabelRotation();\n this.calculateLabelRotation(); // Preconditions: number of ticks and sizes of largest labels must be calculated beforehand\n this.afterCalculateLabelRotation();\n\n // Auto-skip\n if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {\n this.ticks = autoSkip(this, this.ticks);\n this._labelSizes = null;\n this.afterAutoSkip();\n }\n\n if (samplingEnabled) {\n // Generate labels using all non-skipped ticks\n this._convertTicksToLabels(this.ticks);\n }\n\n this.beforeFit();\n this.fit(); // Preconditions: label rotation and label sizes must be calculated beforehand\n this.afterFit();\n\n // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!\n\n this.afterUpdate();\n }\n\n /**\n\t * @protected\n\t */\n configure() {\n let reversePixels = this.options.reverse;\n let startPixel, endPixel;\n\n if (this.isHorizontal()) {\n startPixel = this.left;\n endPixel = this.right;\n } else {\n startPixel = this.top;\n endPixel = this.bottom;\n // by default vertical scales are from bottom to top, so pixels are reversed\n reversePixels = !reversePixels;\n }\n this._startPixel = startPixel;\n this._endPixel = endPixel;\n this._reversePixels = reversePixels;\n this._length = endPixel - startPixel;\n this._alignToPixels = this.options.alignToPixels;\n }\n\n afterUpdate() {\n call(this.options.afterUpdate, [this]);\n }\n\n //\n\n beforeSetDimensions() {\n call(this.options.beforeSetDimensions, [this]);\n }\n setDimensions() {\n // Set the unconstrained dimension before label rotation\n if (this.isHorizontal()) {\n // Reset position before calculating rotation\n this.width = this.maxWidth;\n this.left = 0;\n this.right = this.width;\n } else {\n this.height = this.maxHeight;\n\n // Reset position before calculating rotation\n this.top = 0;\n this.bottom = this.height;\n }\n\n // Reset padding\n this.paddingLeft = 0;\n this.paddingTop = 0;\n this.paddingRight = 0;\n this.paddingBottom = 0;\n }\n afterSetDimensions() {\n call(this.options.afterSetDimensions, [this]);\n }\n\n _callHooks(name) {\n this.chart.notifyPlugins(name, this.getContext());\n call(this.options[name], [this]);\n }\n\n // Data limits\n beforeDataLimits() {\n this._callHooks('beforeDataLimits');\n }\n determineDataLimits() {}\n afterDataLimits() {\n this._callHooks('afterDataLimits');\n }\n\n //\n beforeBuildTicks() {\n this._callHooks('beforeBuildTicks');\n }\n /**\n\t * @return {object[]} the ticks\n\t */\n buildTicks() {\n return [];\n }\n afterBuildTicks() {\n this._callHooks('afterBuildTicks');\n }\n\n beforeTickToLabelConversion() {\n call(this.options.beforeTickToLabelConversion, [this]);\n }\n /**\n\t * Convert ticks to label strings\n\t * @param {Tick[]} ticks\n\t */\n generateTickLabels(ticks) {\n const tickOpts = this.options.ticks;\n let i, ilen, tick;\n for (i = 0, ilen = ticks.length; i < ilen; i++) {\n tick = ticks[i];\n tick.label = call(tickOpts.callback, [tick.value, i, ticks], this);\n }\n }\n afterTickToLabelConversion() {\n call(this.options.afterTickToLabelConversion, [this]);\n }\n\n //\n\n beforeCalculateLabelRotation() {\n call(this.options.beforeCalculateLabelRotation, [this]);\n }\n calculateLabelRotation() {\n const options = this.options;\n const tickOpts = options.ticks;\n const numTicks = getTicksLimit(this.ticks.length, options.ticks.maxTicksLimit);\n const minRotation = tickOpts.minRotation || 0;\n const maxRotation = tickOpts.maxRotation;\n let labelRotation = minRotation;\n let tickWidth, maxHeight, maxLabelDiagonal;\n\n if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) {\n this.labelRotation = minRotation;\n return;\n }\n\n const labelSizes = this._getLabelSizes();\n const maxLabelWidth = labelSizes.widest.width;\n const maxLabelHeight = labelSizes.highest.height;\n\n // Estimate the width of each grid based on the canvas width, the maximum\n // label width and the number of tick intervals\n const maxWidth = _limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth);\n tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1);\n\n // Allow 3 pixels x2 padding either side for label readability\n if (maxLabelWidth + 6 > tickWidth) {\n tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));\n maxHeight = this.maxHeight - getTickMarkLength(options.grid)\n\t\t\t\t- tickOpts.padding - getTitleHeight(options.title, this.chart.options.font);\n maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);\n labelRotation = toDegrees(Math.min(\n Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)),\n Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))\n ));\n labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));\n }\n\n this.labelRotation = labelRotation;\n }\n afterCalculateLabelRotation() {\n call(this.options.afterCalculateLabelRotation, [this]);\n }\n afterAutoSkip() {}\n\n //\n\n beforeFit() {\n call(this.options.beforeFit, [this]);\n }\n fit() {\n // Reset\n const minSize = {\n width: 0,\n height: 0\n };\n\n const {chart, options: {ticks: tickOpts, title: titleOpts, grid: gridOpts}} = this;\n const display = this._isVisible();\n const isHorizontal = this.isHorizontal();\n\n if (display) {\n const titleHeight = getTitleHeight(titleOpts, chart.options.font);\n if (isHorizontal) {\n minSize.width = this.maxWidth;\n minSize.height = getTickMarkLength(gridOpts) + titleHeight;\n } else {\n minSize.height = this.maxHeight; // fill all the height\n minSize.width = getTickMarkLength(gridOpts) + titleHeight;\n }\n\n // Don't bother fitting the ticks if we are not showing the labels\n if (tickOpts.display && this.ticks.length) {\n const {first, last, widest, highest} = this._getLabelSizes();\n const tickPadding = tickOpts.padding * 2;\n const angleRadians = toRadians(this.labelRotation);\n const cos = Math.cos(angleRadians);\n const sin = Math.sin(angleRadians);\n\n if (isHorizontal) {\n // A horizontal axis is more constrained by the height.\n const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;\n minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding);\n } else {\n // A vertical axis is more constrained by the width. Labels are the\n // dominant factor here, so get that length first and account for padding\n const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;\n\n minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding);\n }\n this._calculatePadding(first, last, sin, cos);\n }\n }\n\n this._handleMargins();\n\n if (isHorizontal) {\n this.width = this._length = chart.width - this._margins.left - this._margins.right;\n this.height = minSize.height;\n } else {\n this.width = minSize.width;\n this.height = this._length = chart.height - this._margins.top - this._margins.bottom;\n }\n }\n\n _calculatePadding(first, last, sin, cos) {\n const {ticks: {align, padding}, position} = this.options;\n const isRotated = this.labelRotation !== 0;\n const labelsBelowTicks = position !== 'top' && this.axis === 'x';\n\n if (this.isHorizontal()) {\n const offsetLeft = this.getPixelForTick(0) - this.left;\n const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1);\n let paddingLeft = 0;\n let paddingRight = 0;\n\n // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned\n // which means that the right padding is dominated by the font height\n if (isRotated) {\n if (labelsBelowTicks) {\n paddingLeft = cos * first.width;\n paddingRight = sin * last.height;\n } else {\n paddingLeft = sin * first.height;\n paddingRight = cos * last.width;\n }\n } else if (align === 'start') {\n paddingRight = last.width;\n } else if (align === 'end') {\n paddingLeft = first.width;\n } else if (align !== 'inner') {\n paddingLeft = first.width / 2;\n paddingRight = last.width / 2;\n }\n\n // Adjust padding taking into account changes in offsets\n this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0);\n this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0);\n } else {\n let paddingTop = last.height / 2;\n let paddingBottom = first.height / 2;\n\n if (align === 'start') {\n paddingTop = 0;\n paddingBottom = first.height;\n } else if (align === 'end') {\n paddingTop = last.height;\n paddingBottom = 0;\n }\n\n this.paddingTop = paddingTop + padding;\n this.paddingBottom = paddingBottom + padding;\n }\n }\n\n /**\n\t * Handle margins and padding interactions\n\t * @private\n\t */\n _handleMargins() {\n if (this._margins) {\n this._margins.left = Math.max(this.paddingLeft, this._margins.left);\n this._margins.top = Math.max(this.paddingTop, this._margins.top);\n this._margins.right = Math.max(this.paddingRight, this._margins.right);\n this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom);\n }\n }\n\n afterFit() {\n call(this.options.afterFit, [this]);\n }\n\n // Shared Methods\n /**\n\t * @return {boolean}\n\t */\n isHorizontal() {\n const {axis, position} = this.options;\n return position === 'top' || position === 'bottom' || axis === 'x';\n }\n /**\n\t * @return {boolean}\n\t */\n isFullSize() {\n return this.options.fullSize;\n }\n\n /**\n\t * @param {Tick[]} ticks\n\t * @private\n\t */\n _convertTicksToLabels(ticks) {\n this.beforeTickToLabelConversion();\n\n this.generateTickLabels(ticks);\n\n // Ticks should be skipped when callback returns null or undef, so lets remove those.\n let i, ilen;\n for (i = 0, ilen = ticks.length; i < ilen; i++) {\n if (isNullOrUndef(ticks[i].label)) {\n ticks.splice(i, 1);\n ilen--;\n i--;\n }\n }\n\n this.afterTickToLabelConversion();\n }\n\n /**\n\t * @return {{ first: object, last: object, widest: object, highest: object, widths: Array, heights: array }}\n\t * @private\n\t */\n _getLabelSizes() {\n let labelSizes = this._labelSizes;\n\n if (!labelSizes) {\n const sampleSize = this.options.ticks.sampleSize;\n let ticks = this.ticks;\n if (sampleSize < ticks.length) {\n ticks = sample(ticks, sampleSize);\n }\n\n this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length, this.options.ticks.maxTicksLimit);\n }\n\n return labelSizes;\n }\n\n /**\n\t * Returns {width, height, offset} objects for the first, last, widest, highest tick\n\t * labels where offset indicates the anchor point offset from the top in pixels.\n\t * @return {{ first: object, last: object, widest: object, highest: object, widths: Array, heights: array }}\n\t * @private\n\t */\n _computeLabelSizes(ticks, length, maxTicksLimit) {\n const {ctx, _longestTextCache: caches} = this;\n const widths = [];\n const heights = [];\n const increment = Math.floor(length / getTicksLimit(length, maxTicksLimit));\n let widestLabelSize = 0;\n let highestLabelSize = 0;\n let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;\n\n for (i = 0; i < length; i += increment) {\n label = ticks[i].label;\n tickFont = this._resolveTickFontOptions(i);\n ctx.font = fontString = tickFont.string;\n cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};\n lineHeight = tickFont.lineHeight;\n width = height = 0;\n // Undefined labels and arrays should not be measured\n if (!isNullOrUndef(label) && !isArray(label)) {\n width = _measureText(ctx, cache.data, cache.gc, width, label);\n height = lineHeight;\n } else if (isArray(label)) {\n // if it is an array let's measure each element\n for (j = 0, jlen = label.length; j < jlen; ++j) {\n nestedLabel = /** @type {string} */ (label[j]);\n // Undefined labels and arrays should not be measured\n if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {\n width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);\n height += lineHeight;\n }\n }\n }\n widths.push(width);\n heights.push(height);\n widestLabelSize = Math.max(width, widestLabelSize);\n highestLabelSize = Math.max(height, highestLabelSize);\n }\n garbageCollect(caches, length);\n\n const widest = widths.indexOf(widestLabelSize);\n const highest = heights.indexOf(highestLabelSize);\n\n const valueAt = (idx) => ({width: widths[idx] || 0, height: heights[idx] || 0});\n\n return {\n first: valueAt(0),\n last: valueAt(length - 1),\n widest: valueAt(widest),\n highest: valueAt(highest),\n widths,\n heights,\n };\n }\n\n /**\n\t * Used to get the label to display in the tooltip for the given value\n\t * @param {*} value\n\t * @return {string}\n\t */\n getLabelForValue(value) {\n return value;\n }\n\n /**\n\t * Returns the location of the given data point. Value can either be an index or a numerical value\n\t * The coordinate (0, 0) is at the upper-left corner of the canvas\n\t * @param {*} value\n\t * @param {number} [index]\n\t * @return {number}\n\t */\n getPixelForValue(value, index) { // eslint-disable-line no-unused-vars\n return NaN;\n }\n\n /**\n\t * Used to get the data value from a given pixel. This is the inverse of getPixelForValue\n\t * The coordinate (0, 0) is at the upper-left corner of the canvas\n\t * @param {number} pixel\n\t * @return {*}\n\t */\n getValueForPixel(pixel) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * Returns the location of the tick at the given index\n\t * The coordinate (0, 0) is at the upper-left corner of the canvas\n\t * @param {number} index\n\t * @return {number}\n\t */\n getPixelForTick(index) {\n const ticks = this.ticks;\n if (index < 0 || index > ticks.length - 1) {\n return null;\n }\n return this.getPixelForValue(ticks[index].value);\n }\n\n /**\n\t * Utility for getting the pixel location of a percentage of scale\n\t * The coordinate (0, 0) is at the upper-left corner of the canvas\n\t * @param {number} decimal\n\t * @return {number}\n\t */\n getPixelForDecimal(decimal) {\n if (this._reversePixels) {\n decimal = 1 - decimal;\n }\n\n const pixel = this._startPixel + decimal * this._length;\n return _int16Range(this._alignToPixels ? _alignPixel(this.chart, pixel, 0) : pixel);\n }\n\n /**\n\t * @param {number} pixel\n\t * @return {number}\n\t */\n getDecimalForPixel(pixel) {\n const decimal = (pixel - this._startPixel) / this._length;\n return this._reversePixels ? 1 - decimal : decimal;\n }\n\n /**\n\t * Returns the pixel for the minimum chart value\n\t * The coordinate (0, 0) is at the upper-left corner of the canvas\n\t * @return {number}\n\t */\n getBasePixel() {\n return this.getPixelForValue(this.getBaseValue());\n }\n\n /**\n\t * @return {number}\n\t */\n getBaseValue() {\n const {min, max} = this;\n\n return min < 0 && max < 0 ? max :\n min > 0 && max > 0 ? min :\n 0;\n }\n\n /**\n\t * @protected\n\t */\n getContext(index) {\n const ticks = this.ticks || [];\n\n if (index >= 0 && index < ticks.length) {\n const tick = ticks[index];\n return tick.$context ||\n\t\t\t\t(tick.$context = createTickContext(this.getContext(), index, tick));\n }\n return this.$context ||\n\t\t\t(this.$context = createScaleContext(this.chart.getContext(), this));\n }\n\n /**\n\t * @return {number}\n\t * @private\n\t */\n _tickSize() {\n const optionTicks = this.options.ticks;\n\n // Calculate space needed by label in axis direction.\n const rot = toRadians(this.labelRotation);\n const cos = Math.abs(Math.cos(rot));\n const sin = Math.abs(Math.sin(rot));\n\n const labelSizes = this._getLabelSizes();\n const padding = optionTicks.autoSkipPadding || 0;\n const w = labelSizes ? labelSizes.widest.width + padding : 0;\n const h = labelSizes ? labelSizes.highest.height + padding : 0;\n\n // Calculate space needed for 1 tick in axis direction.\n return this.isHorizontal()\n ? h * cos > w * sin ? w / cos : h / sin\n : h * sin < w * cos ? h / cos : w / sin;\n }\n\n /**\n\t * @return {boolean}\n\t * @private\n\t */\n _isVisible() {\n const display = this.options.display;\n\n if (display !== 'auto') {\n return !!display;\n }\n\n return this.getMatchingVisibleMetas().length > 0;\n }\n\n /**\n\t * @private\n\t */\n _computeGridLineItems(chartArea) {\n const axis = this.axis;\n const chart = this.chart;\n const options = this.options;\n const {grid, position, border} = options;\n const offset = grid.offset;\n const isHorizontal = this.isHorizontal();\n const ticks = this.ticks;\n const ticksLength = ticks.length + (offset ? 1 : 0);\n const tl = getTickMarkLength(grid);\n const items = [];\n\n const borderOpts = border.setContext(this.getContext());\n const axisWidth = borderOpts.display ? borderOpts.width : 0;\n const axisHalfWidth = axisWidth / 2;\n const alignBorderValue = function(pixel) {\n return _alignPixel(chart, pixel, axisWidth);\n };\n let borderValue, i, lineValue, alignedLineValue;\n let tx1, ty1, tx2, ty2, x1, y1, x2, y2;\n\n if (position === 'top') {\n borderValue = alignBorderValue(this.bottom);\n ty1 = this.bottom - tl;\n ty2 = borderValue - axisHalfWidth;\n y1 = alignBorderValue(chartArea.top) + axisHalfWidth;\n y2 = chartArea.bottom;\n } else if (position === 'bottom') {\n borderValue = alignBorderValue(this.top);\n y1 = chartArea.top;\n y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;\n ty1 = borderValue + axisHalfWidth;\n ty2 = this.top + tl;\n } else if (position === 'left') {\n borderValue = alignBorderValue(this.right);\n tx1 = this.right - tl;\n tx2 = borderValue - axisHalfWidth;\n x1 = alignBorderValue(chartArea.left) + axisHalfWidth;\n x2 = chartArea.right;\n } else if (position === 'right') {\n borderValue = alignBorderValue(this.left);\n x1 = chartArea.left;\n x2 = alignBorderValue(chartArea.right) - axisHalfWidth;\n tx1 = borderValue + axisHalfWidth;\n tx2 = this.left + tl;\n } else if (axis === 'x') {\n if (position === 'center') {\n borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);\n } else if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));\n }\n\n y1 = chartArea.top;\n y2 = chartArea.bottom;\n ty1 = borderValue + axisHalfWidth;\n ty2 = ty1 + tl;\n } else if (axis === 'y') {\n if (position === 'center') {\n borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);\n } else if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));\n }\n\n tx1 = borderValue - axisHalfWidth;\n tx2 = tx1 - tl;\n x1 = chartArea.left;\n x2 = chartArea.right;\n }\n\n const limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength);\n const step = Math.max(1, Math.ceil(ticksLength / limit));\n for (i = 0; i < ticksLength; i += step) {\n const context = this.getContext(i);\n const optsAtIndex = grid.setContext(context);\n const optsAtIndexBorder = border.setContext(context);\n\n const lineWidth = optsAtIndex.lineWidth;\n const lineColor = optsAtIndex.color;\n const borderDash = optsAtIndexBorder.dash || [];\n const borderDashOffset = optsAtIndexBorder.dashOffset;\n\n const tickWidth = optsAtIndex.tickWidth;\n const tickColor = optsAtIndex.tickColor;\n const tickBorderDash = optsAtIndex.tickBorderDash || [];\n const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;\n\n lineValue = getPixelForGridLine(this, i, offset);\n\n // Skip if the pixel is out of the range\n if (lineValue === undefined) {\n continue;\n }\n\n alignedLineValue = _alignPixel(chart, lineValue, lineWidth);\n\n if (isHorizontal) {\n tx1 = tx2 = x1 = x2 = alignedLineValue;\n } else {\n ty1 = ty2 = y1 = y2 = alignedLineValue;\n }\n\n items.push({\n tx1,\n ty1,\n tx2,\n ty2,\n x1,\n y1,\n x2,\n y2,\n width: lineWidth,\n color: lineColor,\n borderDash,\n borderDashOffset,\n tickWidth,\n tickColor,\n tickBorderDash,\n tickBorderDashOffset,\n });\n }\n\n this._ticksLength = ticksLength;\n this._borderValue = borderValue;\n\n return items;\n }\n\n /**\n\t * @private\n\t */\n _computeLabelItems(chartArea) {\n const axis = this.axis;\n const options = this.options;\n const {position, ticks: optionTicks} = options;\n const isHorizontal = this.isHorizontal();\n const ticks = this.ticks;\n const {align, crossAlign, padding, mirror} = optionTicks;\n const tl = getTickMarkLength(options.grid);\n const tickAndPadding = tl + padding;\n const hTickAndPadding = mirror ? -padding : tickAndPadding;\n const rotation = -toRadians(this.labelRotation);\n const items = [];\n let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;\n let textBaseline = 'middle';\n\n if (position === 'top') {\n y = this.bottom - hTickAndPadding;\n textAlign = this._getXAxisLabelAlignment();\n } else if (position === 'bottom') {\n y = this.top + hTickAndPadding;\n textAlign = this._getXAxisLabelAlignment();\n } else if (position === 'left') {\n const ret = this._getYAxisLabelAlignment(tl);\n textAlign = ret.textAlign;\n x = ret.x;\n } else if (position === 'right') {\n const ret = this._getYAxisLabelAlignment(tl);\n textAlign = ret.textAlign;\n x = ret.x;\n } else if (axis === 'x') {\n if (position === 'center') {\n y = ((chartArea.top + chartArea.bottom) / 2) + tickAndPadding;\n } else if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;\n }\n textAlign = this._getXAxisLabelAlignment();\n } else if (axis === 'y') {\n if (position === 'center') {\n x = ((chartArea.left + chartArea.right) / 2) - tickAndPadding;\n } else if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n x = this.chart.scales[positionAxisID].getPixelForValue(value);\n }\n textAlign = this._getYAxisLabelAlignment(tl).textAlign;\n }\n\n if (axis === 'y') {\n if (align === 'start') {\n textBaseline = 'top';\n } else if (align === 'end') {\n textBaseline = 'bottom';\n }\n }\n\n const labelSizes = this._getLabelSizes();\n for (i = 0, ilen = ticks.length; i < ilen; ++i) {\n tick = ticks[i];\n label = tick.label;\n\n const optsAtIndex = optionTicks.setContext(this.getContext(i));\n pixel = this.getPixelForTick(i) + optionTicks.labelOffset;\n font = this._resolveTickFontOptions(i);\n lineHeight = font.lineHeight;\n lineCount = isArray(label) ? label.length : 1;\n const halfCount = lineCount / 2;\n const color = optsAtIndex.color;\n const strokeColor = optsAtIndex.textStrokeColor;\n const strokeWidth = optsAtIndex.textStrokeWidth;\n let tickTextAlign = textAlign;\n\n if (isHorizontal) {\n x = pixel;\n\n if (textAlign === 'inner') {\n if (i === ilen - 1) {\n tickTextAlign = !this.options.reverse ? 'right' : 'left';\n } else if (i === 0) {\n tickTextAlign = !this.options.reverse ? 'left' : 'right';\n } else {\n tickTextAlign = 'center';\n }\n }\n\n if (position === 'top') {\n if (crossAlign === 'near' || rotation !== 0) {\n textOffset = -lineCount * lineHeight + lineHeight / 2;\n } else if (crossAlign === 'center') {\n textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;\n } else {\n textOffset = -labelSizes.highest.height + lineHeight / 2;\n }\n } else {\n // eslint-disable-next-line no-lonely-if\n if (crossAlign === 'near' || rotation !== 0) {\n textOffset = lineHeight / 2;\n } else if (crossAlign === 'center') {\n textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;\n } else {\n textOffset = labelSizes.highest.height - lineCount * lineHeight;\n }\n }\n if (mirror) {\n textOffset *= -1;\n }\n if (rotation !== 0 && !optsAtIndex.showLabelBackdrop) {\n x += (lineHeight / 2) * Math.sin(rotation);\n }\n } else {\n y = pixel;\n textOffset = (1 - lineCount) * lineHeight / 2;\n }\n\n let backdrop;\n\n if (optsAtIndex.showLabelBackdrop) {\n const labelPadding = toPadding(optsAtIndex.backdropPadding);\n const height = labelSizes.heights[i];\n const width = labelSizes.widths[i];\n\n let top = textOffset - labelPadding.top;\n let left = 0 - labelPadding.left;\n\n switch (textBaseline) {\n case 'middle':\n top -= height / 2;\n break;\n case 'bottom':\n top -= height;\n break;\n default:\n break;\n }\n\n switch (textAlign) {\n case 'center':\n left -= width / 2;\n break;\n case 'right':\n left -= width;\n break;\n case 'inner':\n if (i === ilen - 1) {\n left -= width;\n } else if (i > 0) {\n left -= width / 2;\n }\n break;\n default:\n break;\n }\n\n backdrop = {\n left,\n top,\n width: width + labelPadding.width,\n height: height + labelPadding.height,\n\n color: optsAtIndex.backdropColor,\n };\n }\n\n items.push({\n label,\n font,\n textOffset,\n options: {\n rotation,\n color,\n strokeColor,\n strokeWidth,\n textAlign: tickTextAlign,\n textBaseline,\n translation: [x, y],\n backdrop,\n }\n });\n }\n\n return items;\n }\n\n _getXAxisLabelAlignment() {\n const {position, ticks} = this.options;\n const rotation = -toRadians(this.labelRotation);\n\n if (rotation) {\n return position === 'top' ? 'left' : 'right';\n }\n\n let align = 'center';\n\n if (ticks.align === 'start') {\n align = 'left';\n } else if (ticks.align === 'end') {\n align = 'right';\n } else if (ticks.align === 'inner') {\n align = 'inner';\n }\n\n return align;\n }\n\n _getYAxisLabelAlignment(tl) {\n const {position, ticks: {crossAlign, mirror, padding}} = this.options;\n const labelSizes = this._getLabelSizes();\n const tickAndPadding = tl + padding;\n const widest = labelSizes.widest.width;\n\n let textAlign;\n let x;\n\n if (position === 'left') {\n if (mirror) {\n x = this.right + padding;\n\n if (crossAlign === 'near') {\n textAlign = 'left';\n } else if (crossAlign === 'center') {\n textAlign = 'center';\n x += (widest / 2);\n } else {\n textAlign = 'right';\n x += widest;\n }\n } else {\n x = this.right - tickAndPadding;\n\n if (crossAlign === 'near') {\n textAlign = 'right';\n } else if (crossAlign === 'center') {\n textAlign = 'center';\n x -= (widest / 2);\n } else {\n textAlign = 'left';\n x = this.left;\n }\n }\n } else if (position === 'right') {\n if (mirror) {\n x = this.left + padding;\n\n if (crossAlign === 'near') {\n textAlign = 'right';\n } else if (crossAlign === 'center') {\n textAlign = 'center';\n x -= (widest / 2);\n } else {\n textAlign = 'left';\n x -= widest;\n }\n } else {\n x = this.left + tickAndPadding;\n\n if (crossAlign === 'near') {\n textAlign = 'left';\n } else if (crossAlign === 'center') {\n textAlign = 'center';\n x += widest / 2;\n } else {\n textAlign = 'right';\n x = this.right;\n }\n }\n } else {\n textAlign = 'right';\n }\n\n return {textAlign, x};\n }\n\n /**\n\t * @private\n\t */\n _computeLabelArea() {\n if (this.options.ticks.mirror) {\n return;\n }\n\n const chart = this.chart;\n const position = this.options.position;\n\n if (position === 'left' || position === 'right') {\n return {top: 0, left: this.left, bottom: chart.height, right: this.right};\n } if (position === 'top' || position === 'bottom') {\n return {top: this.top, left: 0, bottom: this.bottom, right: chart.width};\n }\n }\n\n /**\n * @protected\n */\n drawBackground() {\n const {ctx, options: {backgroundColor}, left, top, width, height} = this;\n if (backgroundColor) {\n ctx.save();\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(left, top, width, height);\n ctx.restore();\n }\n }\n\n getLineWidthForValue(value) {\n const grid = this.options.grid;\n if (!this._isVisible() || !grid.display) {\n return 0;\n }\n const ticks = this.ticks;\n const index = ticks.findIndex(t => t.value === value);\n if (index >= 0) {\n const opts = grid.setContext(this.getContext(index));\n return opts.lineWidth;\n }\n return 0;\n }\n\n /**\n\t * @protected\n\t */\n drawGrid(chartArea) {\n const grid = this.options.grid;\n const ctx = this.ctx;\n const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea));\n let i, ilen;\n\n const drawLine = (p1, p2, style) => {\n if (!style.width || !style.color) {\n return;\n }\n ctx.save();\n ctx.lineWidth = style.width;\n ctx.strokeStyle = style.color;\n ctx.setLineDash(style.borderDash || []);\n ctx.lineDashOffset = style.borderDashOffset;\n\n ctx.beginPath();\n ctx.moveTo(p1.x, p1.y);\n ctx.lineTo(p2.x, p2.y);\n ctx.stroke();\n ctx.restore();\n };\n\n if (grid.display) {\n for (i = 0, ilen = items.length; i < ilen; ++i) {\n const item = items[i];\n\n if (grid.drawOnChartArea) {\n drawLine(\n {x: item.x1, y: item.y1},\n {x: item.x2, y: item.y2},\n item\n );\n }\n\n if (grid.drawTicks) {\n drawLine(\n {x: item.tx1, y: item.ty1},\n {x: item.tx2, y: item.ty2},\n {\n color: item.tickColor,\n width: item.tickWidth,\n borderDash: item.tickBorderDash,\n borderDashOffset: item.tickBorderDashOffset\n }\n );\n }\n }\n }\n }\n\n /**\n\t * @protected\n\t */\n drawBorder() {\n const {chart, ctx, options: {border, grid}} = this;\n const borderOpts = border.setContext(this.getContext());\n const axisWidth = border.display ? borderOpts.width : 0;\n if (!axisWidth) {\n return;\n }\n const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth;\n const borderValue = this._borderValue;\n let x1, x2, y1, y2;\n\n if (this.isHorizontal()) {\n x1 = _alignPixel(chart, this.left, axisWidth) - axisWidth / 2;\n x2 = _alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2;\n y1 = y2 = borderValue;\n } else {\n y1 = _alignPixel(chart, this.top, axisWidth) - axisWidth / 2;\n y2 = _alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2;\n x1 = x2 = borderValue;\n }\n ctx.save();\n ctx.lineWidth = borderOpts.width;\n ctx.strokeStyle = borderOpts.color;\n\n ctx.beginPath();\n ctx.moveTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.stroke();\n\n ctx.restore();\n }\n\n /**\n\t * @protected\n\t */\n drawLabels(chartArea) {\n const optionTicks = this.options.ticks;\n\n if (!optionTicks.display) {\n return;\n }\n\n const ctx = this.ctx;\n\n const area = this._computeLabelArea();\n if (area) {\n clipArea(ctx, area);\n }\n\n const items = this.getLabelItems(chartArea);\n for (const item of items) {\n const renderTextOptions = item.options;\n const tickFont = item.font;\n const label = item.label;\n const y = item.textOffset;\n renderText(ctx, label, 0, y, tickFont, renderTextOptions);\n }\n\n if (area) {\n unclipArea(ctx);\n }\n }\n\n /**\n\t * @protected\n\t */\n drawTitle() {\n const {ctx, options: {position, title, reverse}} = this;\n\n if (!title.display) {\n return;\n }\n\n const font = toFont(title.font);\n const padding = toPadding(title.padding);\n const align = title.align;\n let offset = font.lineHeight / 2;\n\n if (position === 'bottom' || position === 'center' || isObject(position)) {\n offset += padding.bottom;\n if (isArray(title.text)) {\n offset += font.lineHeight * (title.text.length - 1);\n }\n } else {\n offset += padding.top;\n }\n\n const {titleX, titleY, maxWidth, rotation} = titleArgs(this, offset, position, align);\n\n renderText(ctx, title.text, 0, 0, font, {\n color: title.color,\n maxWidth,\n rotation,\n textAlign: titleAlign(align, position, reverse),\n textBaseline: 'middle',\n translation: [titleX, titleY],\n });\n }\n\n draw(chartArea) {\n if (!this._isVisible()) {\n return;\n }\n\n this.drawBackground();\n this.drawGrid(chartArea);\n this.drawBorder();\n this.drawTitle();\n this.drawLabels(chartArea);\n }\n\n /**\n\t * @return {object[]}\n\t * @private\n\t */\n _layers() {\n const opts = this.options;\n const tz = opts.ticks && opts.ticks.z || 0;\n const gz = valueOrDefault(opts.grid && opts.grid.z, -1);\n const bz = valueOrDefault(opts.border && opts.border.z, 0);\n\n if (!this._isVisible() || this.draw !== Scale.prototype.draw) {\n // backward compatibility: draw has been overridden by custom scale\n return [{\n z: tz,\n draw: (chartArea) => {\n this.draw(chartArea);\n }\n }];\n }\n\n return [{\n z: gz,\n draw: (chartArea) => {\n this.drawBackground();\n this.drawGrid(chartArea);\n this.drawTitle();\n }\n }, {\n z: bz,\n draw: () => {\n this.drawBorder();\n }\n }, {\n z: tz,\n draw: (chartArea) => {\n this.drawLabels(chartArea);\n }\n }];\n }\n\n /**\n\t * Returns visible dataset metas that are attached to this scale\n\t * @param {string} [type] - if specified, also filter by dataset type\n\t * @return {object[]}\n\t */\n getMatchingVisibleMetas(type) {\n const metas = this.chart.getSortedVisibleDatasetMetas();\n const axisID = this.axis + 'AxisID';\n const result = [];\n let i, ilen;\n\n for (i = 0, ilen = metas.length; i < ilen; ++i) {\n const meta = metas[i];\n if (meta[axisID] === this.id && (!type || meta.type === type)) {\n result.push(meta);\n }\n }\n return result;\n }\n\n /**\n\t * @param {number} index\n\t * @return {object}\n\t * @protected\n \t */\n _resolveTickFontOptions(index) {\n const opts = this.options.ticks.setContext(this.getContext(index));\n return toFont(opts.font);\n }\n\n /**\n * @protected\n */\n _maxDigits() {\n const fontSize = this._resolveTickFontOptions(0).lineHeight;\n return (this.isHorizontal() ? this.width : this.height) / fontSize;\n }\n}\n","import {merge} from '../helpers/index.js';\nimport defaults, {overrides} from './core.defaults.js';\n\n/**\n * @typedef {{id: string, defaults: any, overrides?: any, defaultRoutes: any}} IChartComponent\n */\n\nexport default class TypedRegistry {\n constructor(type, scope, override) {\n this.type = type;\n this.scope = scope;\n this.override = override;\n this.items = Object.create(null);\n }\n\n isForType(type) {\n return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);\n }\n\n /**\n\t * @param {IChartComponent} item\n\t * @returns {string} The scope where items defaults were registered to.\n\t */\n register(item) {\n const proto = Object.getPrototypeOf(item);\n let parentScope;\n\n if (isIChartComponent(proto)) {\n // Make sure the parent is registered and note the scope where its defaults are.\n parentScope = this.register(proto);\n }\n\n const items = this.items;\n const id = item.id;\n const scope = this.scope + '.' + id;\n\n if (!id) {\n throw new Error('class does not have id: ' + item);\n }\n\n if (id in items) {\n // already registered\n return scope;\n }\n\n items[id] = item;\n registerDefaults(item, scope, parentScope);\n if (this.override) {\n defaults.override(item.id, item.overrides);\n }\n\n return scope;\n }\n\n /**\n\t * @param {string} id\n\t * @returns {object?}\n\t */\n get(id) {\n return this.items[id];\n }\n\n /**\n\t * @param {IChartComponent} item\n\t */\n unregister(item) {\n const items = this.items;\n const id = item.id;\n const scope = this.scope;\n\n if (id in items) {\n delete items[id];\n }\n\n if (scope && id in defaults[scope]) {\n delete defaults[scope][id];\n if (this.override) {\n delete overrides[id];\n }\n }\n }\n}\n\nfunction registerDefaults(item, scope, parentScope) {\n // Inherit the parent's defaults and keep existing defaults\n const itemDefaults = merge(Object.create(null), [\n parentScope ? defaults.get(parentScope) : {},\n defaults.get(scope),\n item.defaults\n ]);\n\n defaults.set(scope, itemDefaults);\n\n if (item.defaultRoutes) {\n routeDefaults(scope, item.defaultRoutes);\n }\n\n if (item.descriptors) {\n defaults.describe(scope, item.descriptors);\n }\n}\n\nfunction routeDefaults(scope, routes) {\n Object.keys(routes).forEach(property => {\n const propertyParts = property.split('.');\n const sourceName = propertyParts.pop();\n const sourceScope = [scope].concat(propertyParts).join('.');\n const parts = routes[property].split('.');\n const targetName = parts.pop();\n const targetScope = parts.join('.');\n defaults.route(sourceScope, sourceName, targetScope, targetName);\n });\n}\n\nfunction isIChartComponent(proto) {\n return 'id' in proto && 'defaults' in proto;\n}\n","import DatasetController from './core.datasetController.js';\nimport Element from './core.element.js';\nimport Scale from './core.scale.js';\nimport TypedRegistry from './core.typedRegistry.js';\nimport {each, callback as call, _capitalize} from '../helpers/helpers.core.js';\n\n/**\n * Please use the module's default export which provides a singleton instance\n * Note: class is exported for typedoc\n */\nexport class Registry {\n constructor() {\n this.controllers = new TypedRegistry(DatasetController, 'datasets', true);\n this.elements = new TypedRegistry(Element, 'elements');\n this.plugins = new TypedRegistry(Object, 'plugins');\n this.scales = new TypedRegistry(Scale, 'scales');\n // Order is important, Scale has Element in prototype chain,\n // so Scales must be before Elements. Plugins are a fallback, so not listed here.\n this._typedRegistries = [this.controllers, this.scales, this.elements];\n }\n\n /**\n\t * @param {...any} args\n\t */\n add(...args) {\n this._each('register', args);\n }\n\n remove(...args) {\n this._each('unregister', args);\n }\n\n /**\n\t * @param {...typeof DatasetController} args\n\t */\n addControllers(...args) {\n this._each('register', args, this.controllers);\n }\n\n /**\n\t * @param {...typeof Element} args\n\t */\n addElements(...args) {\n this._each('register', args, this.elements);\n }\n\n /**\n\t * @param {...any} args\n\t */\n addPlugins(...args) {\n this._each('register', args, this.plugins);\n }\n\n /**\n\t * @param {...typeof Scale} args\n\t */\n addScales(...args) {\n this._each('register', args, this.scales);\n }\n\n /**\n\t * @param {string} id\n\t * @returns {typeof DatasetController}\n\t */\n getController(id) {\n return this._get(id, this.controllers, 'controller');\n }\n\n /**\n\t * @param {string} id\n\t * @returns {typeof Element}\n\t */\n getElement(id) {\n return this._get(id, this.elements, 'element');\n }\n\n /**\n\t * @param {string} id\n\t * @returns {object}\n\t */\n getPlugin(id) {\n return this._get(id, this.plugins, 'plugin');\n }\n\n /**\n\t * @param {string} id\n\t * @returns {typeof Scale}\n\t */\n getScale(id) {\n return this._get(id, this.scales, 'scale');\n }\n\n /**\n\t * @param {...typeof DatasetController} args\n\t */\n removeControllers(...args) {\n this._each('unregister', args, this.controllers);\n }\n\n /**\n\t * @param {...typeof Element} args\n\t */\n removeElements(...args) {\n this._each('unregister', args, this.elements);\n }\n\n /**\n\t * @param {...any} args\n\t */\n removePlugins(...args) {\n this._each('unregister', args, this.plugins);\n }\n\n /**\n\t * @param {...typeof Scale} args\n\t */\n removeScales(...args) {\n this._each('unregister', args, this.scales);\n }\n\n /**\n\t * @private\n\t */\n _each(method, args, typedRegistry) {\n [...args].forEach(arg => {\n const reg = typedRegistry || this._getRegistryForType(arg);\n if (typedRegistry || reg.isForType(arg) || (reg === this.plugins && arg.id)) {\n this._exec(method, reg, arg);\n } else {\n // Handle loopable args\n // Use case:\n // import * as plugins from './plugins.js';\n // Chart.register(plugins);\n each(arg, item => {\n // If there are mixed types in the loopable, make sure those are\n // registered in correct registry\n // Use case: (treemap exporting controller, elements etc)\n // import * as treemap from 'chartjs-chart-treemap.js';\n // Chart.register(treemap);\n\n const itemReg = typedRegistry || this._getRegistryForType(item);\n this._exec(method, itemReg, item);\n });\n }\n });\n }\n\n /**\n\t * @private\n\t */\n _exec(method, registry, component) {\n const camelMethod = _capitalize(method);\n call(component['before' + camelMethod], [], component); // beforeRegister / beforeUnregister\n registry[method](component);\n call(component['after' + camelMethod], [], component); // afterRegister / afterUnregister\n }\n\n /**\n\t * @private\n\t */\n _getRegistryForType(type) {\n for (let i = 0; i < this._typedRegistries.length; i++) {\n const reg = this._typedRegistries[i];\n if (reg.isForType(type)) {\n return reg;\n }\n }\n // plugins is the fallback registry\n return this.plugins;\n }\n\n /**\n\t * @private\n\t */\n _get(id, typedRegistry, type) {\n const item = typedRegistry.get(id);\n if (item === undefined) {\n throw new Error('\"' + id + '\" is not a registered ' + type + '.');\n }\n return item;\n }\n\n}\n\n// singleton instance\nexport default /* #__PURE__ */ new Registry();\n","import registry from './core.registry.js';\nimport {callback as callCallback, isNullOrUndef, valueOrDefault} from '../helpers/helpers.core.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n * @typedef { import('../plugins/plugin.tooltip.js').default } Tooltip\n */\n\n/**\n * @callback filterCallback\n * @param {{plugin: object, options: object}} value\n * @param {number} [index]\n * @param {array} [array]\n * @param {object} [thisArg]\n * @return {boolean}\n */\n\n\nexport default class PluginService {\n constructor() {\n this._init = [];\n }\n\n /**\n\t * Calls enabled plugins for `chart` on the specified hook and with the given args.\n\t * This method immediately returns as soon as a plugin explicitly returns false. The\n\t * returned value can be used, for instance, to interrupt the current action.\n\t * @param {Chart} chart - The chart instance for which plugins should be called.\n\t * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').\n\t * @param {object} [args] - Extra arguments to apply to the hook call.\n * @param {filterCallback} [filter] - Filtering function for limiting which plugins are notified\n\t * @returns {boolean} false if any of the plugins return false, else returns true.\n\t */\n notify(chart, hook, args, filter) {\n if (hook === 'beforeInit') {\n this._init = this._createDescriptors(chart, true);\n this._notify(this._init, chart, 'install');\n }\n\n const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart);\n const result = this._notify(descriptors, chart, hook, args);\n\n if (hook === 'afterDestroy') {\n this._notify(descriptors, chart, 'stop');\n this._notify(this._init, chart, 'uninstall');\n }\n return result;\n }\n\n /**\n\t * @private\n\t */\n _notify(descriptors, chart, hook, args) {\n args = args || {};\n for (const descriptor of descriptors) {\n const plugin = descriptor.plugin;\n const method = plugin[hook];\n const params = [chart, args, descriptor.options];\n if (callCallback(method, params, plugin) === false && args.cancelable) {\n return false;\n }\n }\n\n return true;\n }\n\n invalidate() {\n // When plugins are registered, there is the possibility of a double\n // invalidate situation. In this case, we only want to invalidate once.\n // If we invalidate multiple times, the `_oldCache` is lost and all of the\n // plugins are restarted without being correctly stopped.\n // See https://github.com/chartjs/Chart.js/issues/8147\n if (!isNullOrUndef(this._cache)) {\n this._oldCache = this._cache;\n this._cache = undefined;\n }\n }\n\n /**\n\t * @param {Chart} chart\n\t * @private\n\t */\n _descriptors(chart) {\n if (this._cache) {\n return this._cache;\n }\n\n const descriptors = this._cache = this._createDescriptors(chart);\n\n this._notifyStateChanges(chart);\n\n return descriptors;\n }\n\n _createDescriptors(chart, all) {\n const config = chart && chart.config;\n const options = valueOrDefault(config.options && config.options.plugins, {});\n const plugins = allPlugins(config);\n // options === false => all plugins are disabled\n return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);\n }\n\n /**\n\t * @param {Chart} chart\n\t * @private\n\t */\n _notifyStateChanges(chart) {\n const previousDescriptors = this._oldCache || [];\n const descriptors = this._cache;\n const diff = (a, b) => a.filter(x => !b.some(y => x.plugin.id === y.plugin.id));\n this._notify(diff(previousDescriptors, descriptors), chart, 'stop');\n this._notify(diff(descriptors, previousDescriptors), chart, 'start');\n }\n}\n\n/**\n * @param {import('./core.config.js').default} config\n */\nfunction allPlugins(config) {\n const localIds = {};\n const plugins = [];\n const keys = Object.keys(registry.plugins.items);\n for (let i = 0; i < keys.length; i++) {\n plugins.push(registry.getPlugin(keys[i]));\n }\n\n const local = config.plugins || [];\n for (let i = 0; i < local.length; i++) {\n const plugin = local[i];\n\n if (plugins.indexOf(plugin) === -1) {\n plugins.push(plugin);\n localIds[plugin.id] = true;\n }\n }\n\n return {plugins, localIds};\n}\n\nfunction getOpts(options, all) {\n if (!all && options === false) {\n return null;\n }\n if (options === true) {\n return {};\n }\n return options;\n}\n\nfunction createDescriptors(chart, {plugins, localIds}, options, all) {\n const result = [];\n const context = chart.getContext();\n\n for (const plugin of plugins) {\n const id = plugin.id;\n const opts = getOpts(options[id], all);\n if (opts === null) {\n continue;\n }\n result.push({\n plugin,\n options: pluginOpts(chart.config, {plugin, local: localIds[id]}, opts, context)\n });\n }\n\n return result;\n}\n\nfunction pluginOpts(config, {plugin, local}, opts, context) {\n const keys = config.pluginScopeKeys(plugin);\n const scopes = config.getOptionScopes(opts, keys);\n if (local && plugin.defaults) {\n // make sure plugin defaults are in scopes for local (not registered) plugins\n scopes.push(plugin.defaults);\n }\n return config.createResolver(scopes, context, [''], {\n // These are just defaults that plugins can override\n scriptable: false,\n indexable: false,\n allKeys: true\n });\n}\n","import defaults, {overrides, descriptors} from './core.defaults.js';\nimport {mergeIf, resolveObjectKey, isArray, isFunction, valueOrDefault, isObject} from '../helpers/helpers.core.js';\nimport {_attachContext, _createResolver, _descriptors} from '../helpers/helpers.config.js';\n\nexport function getIndexAxis(type, options) {\n const datasetDefaults = defaults.datasets[type] || {};\n const datasetOptions = (options.datasets || {})[type] || {};\n return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';\n}\n\nfunction getAxisFromDefaultScaleID(id, indexAxis) {\n let axis = id;\n if (id === '_index_') {\n axis = indexAxis;\n } else if (id === '_value_') {\n axis = indexAxis === 'x' ? 'y' : 'x';\n }\n return axis;\n}\n\nfunction getDefaultScaleIDFromAxis(axis, indexAxis) {\n return axis === indexAxis ? '_index_' : '_value_';\n}\n\nfunction idMatchesAxis(id) {\n if (id === 'x' || id === 'y' || id === 'r') {\n return id;\n }\n}\n\nfunction axisFromPosition(position) {\n if (position === 'top' || position === 'bottom') {\n return 'x';\n }\n if (position === 'left' || position === 'right') {\n return 'y';\n }\n}\n\nexport function determineAxis(id, ...scaleOptions) {\n if (idMatchesAxis(id)) {\n return id;\n }\n for (const opts of scaleOptions) {\n const axis = opts.axis\n || axisFromPosition(opts.position)\n || id.length > 1 && idMatchesAxis(id[0].toLowerCase());\n if (axis) {\n return axis;\n }\n }\n throw new Error(`Cannot determine type of '${id}' axis. Please provide 'axis' or 'position' option.`);\n}\n\nfunction getAxisFromDataset(id, axis, dataset) {\n if (dataset[axis + 'AxisID'] === id) {\n return {axis};\n }\n}\n\nfunction retrieveAxisFromDatasets(id, config) {\n if (config.data && config.data.datasets) {\n const boundDs = config.data.datasets.filter((d) => d.xAxisID === id || d.yAxisID === id);\n if (boundDs.length) {\n return getAxisFromDataset(id, 'x', boundDs[0]) || getAxisFromDataset(id, 'y', boundDs[0]);\n }\n }\n return {};\n}\n\nfunction mergeScaleConfig(config, options) {\n const chartDefaults = overrides[config.type] || {scales: {}};\n const configScales = options.scales || {};\n const chartIndexAxis = getIndexAxis(config.type, options);\n const scales = Object.create(null);\n\n // First figure out first scale id's per axis.\n Object.keys(configScales).forEach(id => {\n const scaleConf = configScales[id];\n if (!isObject(scaleConf)) {\n return console.error(`Invalid scale configuration for scale: ${id}`);\n }\n if (scaleConf._proxy) {\n return console.warn(`Ignoring resolver passed as options for scale: ${id}`);\n }\n const axis = determineAxis(id, scaleConf, retrieveAxisFromDatasets(id, config), defaults.scales[scaleConf.type]);\n const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);\n const defaultScaleOptions = chartDefaults.scales || {};\n scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, defaultScaleOptions[axis], defaultScaleOptions[defaultId]]);\n });\n\n // Then merge dataset defaults to scale configs\n config.data.datasets.forEach(dataset => {\n const type = dataset.type || config.type;\n const indexAxis = dataset.indexAxis || getIndexAxis(type, options);\n const datasetDefaults = overrides[type] || {};\n const defaultScaleOptions = datasetDefaults.scales || {};\n Object.keys(defaultScaleOptions).forEach(defaultID => {\n const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);\n const id = dataset[axis + 'AxisID'] || axis;\n scales[id] = scales[id] || Object.create(null);\n mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]);\n });\n });\n\n // apply scale defaults, if not overridden by dataset defaults\n Object.keys(scales).forEach(key => {\n const scale = scales[key];\n mergeIf(scale, [defaults.scales[scale.type], defaults.scale]);\n });\n\n return scales;\n}\n\nfunction initOptions(config) {\n const options = config.options || (config.options = {});\n\n options.plugins = valueOrDefault(options.plugins, {});\n options.scales = mergeScaleConfig(config, options);\n}\n\nfunction initData(data) {\n data = data || {};\n data.datasets = data.datasets || [];\n data.labels = data.labels || [];\n return data;\n}\n\nfunction initConfig(config) {\n config = config || {};\n config.data = initData(config.data);\n\n initOptions(config);\n\n return config;\n}\n\nconst keyCache = new Map();\nconst keysCached = new Set();\n\nfunction cachedKeys(cacheKey, generate) {\n let keys = keyCache.get(cacheKey);\n if (!keys) {\n keys = generate();\n keyCache.set(cacheKey, keys);\n keysCached.add(keys);\n }\n return keys;\n}\n\nconst addIfFound = (set, obj, key) => {\n const opts = resolveObjectKey(obj, key);\n if (opts !== undefined) {\n set.add(opts);\n }\n};\n\nexport default class Config {\n constructor(config) {\n this._config = initConfig(config);\n this._scopeCache = new Map();\n this._resolverCache = new Map();\n }\n\n get platform() {\n return this._config.platform;\n }\n\n get type() {\n return this._config.type;\n }\n\n set type(type) {\n this._config.type = type;\n }\n\n get data() {\n return this._config.data;\n }\n\n set data(data) {\n this._config.data = initData(data);\n }\n\n get options() {\n return this._config.options;\n }\n\n set options(options) {\n this._config.options = options;\n }\n\n get plugins() {\n return this._config.plugins;\n }\n\n update() {\n const config = this._config;\n this.clearCache();\n initOptions(config);\n }\n\n clearCache() {\n this._scopeCache.clear();\n this._resolverCache.clear();\n }\n\n /**\n * Returns the option scope keys for resolving dataset options.\n * These keys do not include the dataset itself, because it is not under options.\n * @param {string} datasetType\n * @return {string[][]}\n */\n datasetScopeKeys(datasetType) {\n return cachedKeys(datasetType,\n () => [[\n `datasets.${datasetType}`,\n ''\n ]]);\n }\n\n /**\n * Returns the option scope keys for resolving dataset animation options.\n * These keys do not include the dataset itself, because it is not under options.\n * @param {string} datasetType\n * @param {string} transition\n * @return {string[][]}\n */\n datasetAnimationScopeKeys(datasetType, transition) {\n return cachedKeys(`${datasetType}.transition.${transition}`,\n () => [\n [\n `datasets.${datasetType}.transitions.${transition}`,\n `transitions.${transition}`,\n ],\n // The following are used for looking up the `animations` and `animation` keys\n [\n `datasets.${datasetType}`,\n ''\n ]\n ]);\n }\n\n /**\n * Returns the options scope keys for resolving element options that belong\n * to an dataset. These keys do not include the dataset itself, because it\n * is not under options.\n * @param {string} datasetType\n * @param {string} elementType\n * @return {string[][]}\n */\n datasetElementScopeKeys(datasetType, elementType) {\n return cachedKeys(`${datasetType}-${elementType}`,\n () => [[\n `datasets.${datasetType}.elements.${elementType}`,\n `datasets.${datasetType}`,\n `elements.${elementType}`,\n ''\n ]]);\n }\n\n /**\n * Returns the options scope keys for resolving plugin options.\n * @param {{id: string, additionalOptionScopes?: string[]}} plugin\n * @return {string[][]}\n */\n pluginScopeKeys(plugin) {\n const id = plugin.id;\n const type = this.type;\n return cachedKeys(`${type}-plugin-${id}`,\n () => [[\n `plugins.${id}`,\n ...plugin.additionalOptionScopes || [],\n ]]);\n }\n\n /**\n * @private\n */\n _cachedScopes(mainScope, resetCache) {\n const _scopeCache = this._scopeCache;\n let cache = _scopeCache.get(mainScope);\n if (!cache || resetCache) {\n cache = new Map();\n _scopeCache.set(mainScope, cache);\n }\n return cache;\n }\n\n /**\n * Resolves the objects from options and defaults for option value resolution.\n * @param {object} mainScope - The main scope object for options\n * @param {string[][]} keyLists - The arrays of keys in resolution order\n * @param {boolean} [resetCache] - reset the cache for this mainScope\n */\n getOptionScopes(mainScope, keyLists, resetCache) {\n const {options, type} = this;\n const cache = this._cachedScopes(mainScope, resetCache);\n const cached = cache.get(keyLists);\n if (cached) {\n return cached;\n }\n\n const scopes = new Set();\n\n keyLists.forEach(keys => {\n if (mainScope) {\n scopes.add(mainScope);\n keys.forEach(key => addIfFound(scopes, mainScope, key));\n }\n keys.forEach(key => addIfFound(scopes, options, key));\n keys.forEach(key => addIfFound(scopes, overrides[type] || {}, key));\n keys.forEach(key => addIfFound(scopes, defaults, key));\n keys.forEach(key => addIfFound(scopes, descriptors, key));\n });\n\n const array = Array.from(scopes);\n if (array.length === 0) {\n array.push(Object.create(null));\n }\n if (keysCached.has(keyLists)) {\n cache.set(keyLists, array);\n }\n return array;\n }\n\n /**\n * Returns the option scopes for resolving chart options\n * @return {object[]}\n */\n chartOptionScopes() {\n const {options, type} = this;\n\n return [\n options,\n overrides[type] || {},\n defaults.datasets[type] || {}, // https://github.com/chartjs/Chart.js/issues/8531\n {type},\n defaults,\n descriptors\n ];\n }\n\n /**\n * @param {object[]} scopes\n * @param {string[]} names\n * @param {function|object} context\n * @param {string[]} [prefixes]\n * @return {object}\n */\n resolveNamedOptions(scopes, names, context, prefixes = ['']) {\n const result = {$shared: true};\n const {resolver, subPrefixes} = getResolver(this._resolverCache, scopes, prefixes);\n let options = resolver;\n if (needContext(resolver, names)) {\n result.$shared = false;\n context = isFunction(context) ? context() : context;\n // subResolver is passed to scriptable options. It should not resolve to hover options.\n const subResolver = this.createResolver(scopes, context, subPrefixes);\n options = _attachContext(resolver, context, subResolver);\n }\n\n for (const prop of names) {\n result[prop] = options[prop];\n }\n return result;\n }\n\n /**\n * @param {object[]} scopes\n * @param {object} [context]\n * @param {string[]} [prefixes]\n * @param {{scriptable: boolean, indexable: boolean, allKeys?: boolean}} [descriptorDefaults]\n */\n createResolver(scopes, context, prefixes = [''], descriptorDefaults) {\n const {resolver} = getResolver(this._resolverCache, scopes, prefixes);\n return isObject(context)\n ? _attachContext(resolver, context, undefined, descriptorDefaults)\n : resolver;\n }\n}\n\nfunction getResolver(resolverCache, scopes, prefixes) {\n let cache = resolverCache.get(scopes);\n if (!cache) {\n cache = new Map();\n resolverCache.set(scopes, cache);\n }\n const cacheKey = prefixes.join();\n let cached = cache.get(cacheKey);\n if (!cached) {\n const resolver = _createResolver(scopes, prefixes);\n cached = {\n resolver,\n subPrefixes: prefixes.filter(p => !p.toLowerCase().includes('hover'))\n };\n cache.set(cacheKey, cached);\n }\n return cached;\n}\n\nconst hasFunction = value => isObject(value)\n && Object.getOwnPropertyNames(value).some((key) => isFunction(value[key]));\n\nfunction needContext(proxy, names) {\n const {isScriptable, isIndexable} = _descriptors(proxy);\n\n for (const prop of names) {\n const scriptable = isScriptable(prop);\n const indexable = isIndexable(prop);\n const value = (indexable || scriptable) && proxy[prop];\n if ((scriptable && (isFunction(value) || hasFunction(value)))\n || (indexable && isArray(value))) {\n return true;\n }\n }\n return false;\n}\n","import animator from './core.animator.js';\nimport defaults, {overrides} from './core.defaults.js';\nimport Interaction from './core.interaction.js';\nimport layouts from './core.layouts.js';\nimport {_detectPlatform} from '../platform/index.js';\nimport PluginService from './core.plugins.js';\nimport registry from './core.registry.js';\nimport Config, {determineAxis, getIndexAxis} from './core.config.js';\nimport {retinaScale, _isDomSupported} from '../helpers/helpers.dom.js';\nimport {each, callback as callCallback, uid, valueOrDefault, _elementsEqual, isNullOrUndef, setsEqual, defined, isFunction, _isClickEvent} from '../helpers/helpers.core.js';\nimport {clearCanvas, clipArea, createContext, unclipArea, _isPointInArea} from '../helpers/index.js';\n// @ts-ignore\nimport {version} from '../../package.json';\nimport {debounce} from '../helpers/helpers.extras.js';\n\n/**\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n * @typedef { import('../types/index.js').Point } Point\n */\n\nconst KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea'];\nfunction positionIsHorizontal(position, axis) {\n return position === 'top' || position === 'bottom' || (KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x');\n}\n\nfunction compare2Level(l1, l2) {\n return function(a, b) {\n return a[l1] === b[l1]\n ? a[l2] - b[l2]\n : a[l1] - b[l1];\n };\n}\n\nfunction onAnimationsComplete(context) {\n const chart = context.chart;\n const animationOptions = chart.options.animation;\n\n chart.notifyPlugins('afterRender');\n callCallback(animationOptions && animationOptions.onComplete, [context], chart);\n}\n\nfunction onAnimationProgress(context) {\n const chart = context.chart;\n const animationOptions = chart.options.animation;\n callCallback(animationOptions && animationOptions.onProgress, [context], chart);\n}\n\n/**\n * Chart.js can take a string id of a canvas element, a 2d context, or a canvas element itself.\n * Attempt to unwrap the item passed into the chart constructor so that it is a canvas element (if possible).\n */\nfunction getCanvas(item) {\n if (_isDomSupported() && typeof item === 'string') {\n item = document.getElementById(item);\n } else if (item && item.length) {\n // Support for array based queries (such as jQuery)\n item = item[0];\n }\n\n if (item && item.canvas) {\n // Support for any object associated to a canvas (including a context2d)\n item = item.canvas;\n }\n return item;\n}\n\nconst instances = {};\nconst getChart = (key) => {\n const canvas = getCanvas(key);\n return Object.values(instances).filter((c) => c.canvas === canvas).pop();\n};\n\nfunction moveNumericKeys(obj, start, move) {\n const keys = Object.keys(obj);\n for (const key of keys) {\n const intKey = +key;\n if (intKey >= start) {\n const value = obj[key];\n delete obj[key];\n if (move > 0 || intKey > start) {\n obj[intKey + move] = value;\n }\n }\n }\n}\n\n/**\n * @param {ChartEvent} e\n * @param {ChartEvent|null} lastEvent\n * @param {boolean} inChartArea\n * @param {boolean} isClick\n * @returns {ChartEvent|null}\n */\nfunction determineLastEvent(e, lastEvent, inChartArea, isClick) {\n if (!inChartArea || e.type === 'mouseout') {\n return null;\n }\n if (isClick) {\n return lastEvent;\n }\n return e;\n}\n\nfunction getSizeForArea(scale, chartArea, field) {\n return scale.options.clip ? scale[field] : chartArea[field];\n}\n\nfunction getDatasetArea(meta, chartArea) {\n const {xScale, yScale} = meta;\n if (xScale && yScale) {\n return {\n left: getSizeForArea(xScale, chartArea, 'left'),\n right: getSizeForArea(xScale, chartArea, 'right'),\n top: getSizeForArea(yScale, chartArea, 'top'),\n bottom: getSizeForArea(yScale, chartArea, 'bottom')\n };\n }\n return chartArea;\n}\n\nclass Chart {\n\n static defaults = defaults;\n static instances = instances;\n static overrides = overrides;\n static registry = registry;\n static version = version;\n static getChart = getChart;\n\n static register(...items) {\n registry.add(...items);\n invalidatePlugins();\n }\n\n static unregister(...items) {\n registry.remove(...items);\n invalidatePlugins();\n }\n\n // eslint-disable-next-line max-statements\n constructor(item, userConfig) {\n const config = this.config = new Config(userConfig);\n const initialCanvas = getCanvas(item);\n const existingChart = getChart(initialCanvas);\n if (existingChart) {\n throw new Error(\n 'Canvas is already in use. Chart with ID \\'' + existingChart.id + '\\'' +\n\t\t\t\t' must be destroyed before the canvas with ID \\'' + existingChart.canvas.id + '\\' can be reused.'\n );\n }\n\n const options = config.createResolver(config.chartOptionScopes(), this.getContext());\n\n this.platform = new (config.platform || _detectPlatform(initialCanvas))();\n this.platform.updateConfig(config);\n\n const context = this.platform.acquireContext(initialCanvas, options.aspectRatio);\n const canvas = context && context.canvas;\n const height = canvas && canvas.height;\n const width = canvas && canvas.width;\n\n this.id = uid();\n this.ctx = context;\n this.canvas = canvas;\n this.width = width;\n this.height = height;\n this._options = options;\n // Store the previously used aspect ratio to determine if a resize\n // is needed during updates. Do this after _options is set since\n // aspectRatio uses a getter\n this._aspectRatio = this.aspectRatio;\n this._layers = [];\n this._metasets = [];\n this._stacks = undefined;\n this.boxes = [];\n this.currentDevicePixelRatio = undefined;\n this.chartArea = undefined;\n this._active = [];\n this._lastEvent = undefined;\n this._listeners = {};\n /** @type {?{attach?: function, detach?: function, resize?: function}} */\n this._responsiveListeners = undefined;\n this._sortedMetasets = [];\n this.scales = {};\n this._plugins = new PluginService();\n this.$proxies = {};\n this._hiddenIndices = {};\n this.attached = false;\n this._animationsDisabled = undefined;\n this.$context = undefined;\n this._doResize = debounce(mode => this.update(mode), options.resizeDelay || 0);\n this._dataChanges = [];\n\n // Add the chart instance to the global namespace\n instances[this.id] = this;\n\n if (!context || !canvas) {\n // The given item is not a compatible context2d element, let's return before finalizing\n // the chart initialization but after setting basic chart / controller properties that\n // can help to figure out that the chart is not valid (e.g chart.canvas !== null);\n // https://github.com/chartjs/Chart.js/issues/2807\n console.error(\"Failed to create chart: can't acquire context from the given item\");\n return;\n }\n\n animator.listen(this, 'complete', onAnimationsComplete);\n animator.listen(this, 'progress', onAnimationProgress);\n\n this._initialize();\n if (this.attached) {\n this.update();\n }\n }\n\n get aspectRatio() {\n const {options: {aspectRatio, maintainAspectRatio}, width, height, _aspectRatio} = this;\n if (!isNullOrUndef(aspectRatio)) {\n // If aspectRatio is defined in options, use that.\n return aspectRatio;\n }\n\n if (maintainAspectRatio && _aspectRatio) {\n // If maintainAspectRatio is truthly and we had previously determined _aspectRatio, use that\n return _aspectRatio;\n }\n\n // Calculate\n return height ? width / height : null;\n }\n\n get data() {\n return this.config.data;\n }\n\n set data(data) {\n this.config.data = data;\n }\n\n get options() {\n return this._options;\n }\n\n set options(options) {\n this.config.options = options;\n }\n\n get registry() {\n return registry;\n }\n\n /**\n\t * @private\n\t */\n _initialize() {\n // Before init plugin notification\n this.notifyPlugins('beforeInit');\n\n if (this.options.responsive) {\n this.resize();\n } else {\n retinaScale(this, this.options.devicePixelRatio);\n }\n\n this.bindEvents();\n\n // After init plugin notification\n this.notifyPlugins('afterInit');\n\n return this;\n }\n\n clear() {\n clearCanvas(this.canvas, this.ctx);\n return this;\n }\n\n stop() {\n animator.stop(this);\n return this;\n }\n\n /**\n\t * Resize the chart to its container or to explicit dimensions.\n\t * @param {number} [width]\n\t * @param {number} [height]\n\t */\n resize(width, height) {\n if (!animator.running(this)) {\n this._resize(width, height);\n } else {\n this._resizeBeforeDraw = {width, height};\n }\n }\n\n _resize(width, height) {\n const options = this.options;\n const canvas = this.canvas;\n const aspectRatio = options.maintainAspectRatio && this.aspectRatio;\n const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio);\n const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio();\n const mode = this.width ? 'resize' : 'attach';\n\n this.width = newSize.width;\n this.height = newSize.height;\n this._aspectRatio = this.aspectRatio;\n if (!retinaScale(this, newRatio, true)) {\n return;\n }\n\n this.notifyPlugins('resize', {size: newSize});\n\n callCallback(options.onResize, [this, newSize], this);\n\n if (this.attached) {\n if (this._doResize(mode)) {\n // The resize update is delayed, only draw without updating.\n this.render();\n }\n }\n }\n\n ensureScalesHaveIDs() {\n const options = this.options;\n const scalesOptions = options.scales || {};\n\n each(scalesOptions, (axisOptions, axisID) => {\n axisOptions.id = axisID;\n });\n }\n\n /**\n\t * Builds a map of scale ID to scale object for future lookup.\n\t */\n buildOrUpdateScales() {\n const options = this.options;\n const scaleOpts = options.scales;\n const scales = this.scales;\n const updated = Object.keys(scales).reduce((obj, id) => {\n obj[id] = false;\n return obj;\n }, {});\n let items = [];\n\n if (scaleOpts) {\n items = items.concat(\n Object.keys(scaleOpts).map((id) => {\n const scaleOptions = scaleOpts[id];\n const axis = determineAxis(id, scaleOptions);\n const isRadial = axis === 'r';\n const isHorizontal = axis === 'x';\n return {\n options: scaleOptions,\n dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',\n dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'\n };\n })\n );\n }\n\n each(items, (item) => {\n const scaleOptions = item.options;\n const id = scaleOptions.id;\n const axis = determineAxis(id, scaleOptions);\n const scaleType = valueOrDefault(scaleOptions.type, item.dtype);\n\n if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {\n scaleOptions.position = item.dposition;\n }\n\n updated[id] = true;\n let scale = null;\n if (id in scales && scales[id].type === scaleType) {\n scale = scales[id];\n } else {\n const scaleClass = registry.getScale(scaleType);\n scale = new scaleClass({\n id,\n type: scaleType,\n ctx: this.ctx,\n chart: this\n });\n scales[scale.id] = scale;\n }\n\n scale.init(scaleOptions, options);\n });\n // clear up discarded scales\n each(updated, (hasUpdated, id) => {\n if (!hasUpdated) {\n delete scales[id];\n }\n });\n\n each(scales, (scale) => {\n layouts.configure(this, scale, scale.options);\n layouts.addBox(this, scale);\n });\n }\n\n /**\n\t * @private\n\t */\n _updateMetasets() {\n const metasets = this._metasets;\n const numData = this.data.datasets.length;\n const numMeta = metasets.length;\n\n metasets.sort((a, b) => a.index - b.index);\n if (numMeta > numData) {\n for (let i = numData; i < numMeta; ++i) {\n this._destroyDatasetMeta(i);\n }\n metasets.splice(numData, numMeta - numData);\n }\n this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));\n }\n\n /**\n\t * @private\n\t */\n _removeUnreferencedMetasets() {\n const {_metasets: metasets, data: {datasets}} = this;\n if (metasets.length > datasets.length) {\n delete this._stacks;\n }\n metasets.forEach((meta, index) => {\n if (datasets.filter(x => x === meta._dataset).length === 0) {\n this._destroyDatasetMeta(index);\n }\n });\n }\n\n buildOrUpdateControllers() {\n const newControllers = [];\n const datasets = this.data.datasets;\n let i, ilen;\n\n this._removeUnreferencedMetasets();\n\n for (i = 0, ilen = datasets.length; i < ilen; i++) {\n const dataset = datasets[i];\n let meta = this.getDatasetMeta(i);\n const type = dataset.type || this.config.type;\n\n if (meta.type && meta.type !== type) {\n this._destroyDatasetMeta(i);\n meta = this.getDatasetMeta(i);\n }\n meta.type = type;\n meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options);\n meta.order = dataset.order || 0;\n meta.index = i;\n meta.label = '' + dataset.label;\n meta.visible = this.isDatasetVisible(i);\n\n if (meta.controller) {\n meta.controller.updateIndex(i);\n meta.controller.linkScales();\n } else {\n const ControllerClass = registry.getController(type);\n const {datasetElementType, dataElementType} = defaults.datasets[type];\n Object.assign(ControllerClass, {\n dataElementType: registry.getElement(dataElementType),\n datasetElementType: datasetElementType && registry.getElement(datasetElementType)\n });\n meta.controller = new ControllerClass(this, i);\n newControllers.push(meta.controller);\n }\n }\n\n this._updateMetasets();\n return newControllers;\n }\n\n /**\n\t * Reset the elements of all datasets\n\t * @private\n\t */\n _resetElements() {\n each(this.data.datasets, (dataset, datasetIndex) => {\n this.getDatasetMeta(datasetIndex).controller.reset();\n }, this);\n }\n\n /**\n\t* Resets the chart back to its state before the initial animation\n\t*/\n reset() {\n this._resetElements();\n this.notifyPlugins('reset');\n }\n\n update(mode) {\n const config = this.config;\n\n config.update();\n const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext());\n const animsDisabled = this._animationsDisabled = !options.animation;\n\n this._updateScales();\n this._checkEventBindings();\n this._updateHiddenIndices();\n\n // plugins options references might have change, let's invalidate the cache\n // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167\n this._plugins.invalidate();\n\n if (this.notifyPlugins('beforeUpdate', {mode, cancelable: true}) === false) {\n return;\n }\n\n // Make sure dataset controllers are updated and new controllers are reset\n const newControllers = this.buildOrUpdateControllers();\n\n this.notifyPlugins('beforeElementsUpdate');\n\n // Make sure all dataset controllers have correct meta data counts\n let minPadding = 0;\n for (let i = 0, ilen = this.data.datasets.length; i < ilen; i++) {\n const {controller} = this.getDatasetMeta(i);\n const reset = !animsDisabled && newControllers.indexOf(controller) === -1;\n // New controllers will be reset after the layout pass, so we only want to modify\n // elements added to new datasets\n controller.buildOrUpdateElements(reset);\n minPadding = Math.max(+controller.getMaxOverflow(), minPadding);\n }\n minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0;\n this._updateLayout(minPadding);\n\n // Only reset the controllers if we have animations\n if (!animsDisabled) {\n // Can only reset the new controllers after the scales have been updated\n // Reset is done to get the starting point for the initial animation\n each(newControllers, (controller) => {\n controller.reset();\n });\n }\n\n this._updateDatasets(mode);\n\n // Do this before render so that any plugins that need final scale updates can use it\n this.notifyPlugins('afterUpdate', {mode});\n\n this._layers.sort(compare2Level('z', '_idx'));\n\n // Replay last event from before update, or set hover styles on active elements\n const {_active, _lastEvent} = this;\n if (_lastEvent) {\n this._eventHandler(_lastEvent, true);\n } else if (_active.length) {\n this._updateHoverStyles(_active, _active, true);\n }\n\n this.render();\n }\n\n /**\n * @private\n */\n _updateScales() {\n each(this.scales, (scale) => {\n layouts.removeBox(this, scale);\n });\n\n this.ensureScalesHaveIDs();\n this.buildOrUpdateScales();\n }\n\n /**\n * @private\n */\n _checkEventBindings() {\n const options = this.options;\n const existingEvents = new Set(Object.keys(this._listeners));\n const newEvents = new Set(options.events);\n\n if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) {\n // The configured events have changed. Rebind.\n this.unbindEvents();\n this.bindEvents();\n }\n }\n\n /**\n * @private\n */\n _updateHiddenIndices() {\n const {_hiddenIndices} = this;\n const changes = this._getUniformDataChanges() || [];\n for (const {method, start, count} of changes) {\n const move = method === '_removeElements' ? -count : count;\n moveNumericKeys(_hiddenIndices, start, move);\n }\n }\n\n /**\n * @private\n */\n _getUniformDataChanges() {\n const _dataChanges = this._dataChanges;\n if (!_dataChanges || !_dataChanges.length) {\n return;\n }\n\n this._dataChanges = [];\n const datasetCount = this.data.datasets.length;\n const makeSet = (idx) => new Set(\n _dataChanges\n .filter(c => c[0] === idx)\n .map((c, i) => i + ',' + c.splice(1).join(','))\n );\n\n const changeSet = makeSet(0);\n for (let i = 1; i < datasetCount; i++) {\n if (!setsEqual(changeSet, makeSet(i))) {\n return;\n }\n }\n return Array.from(changeSet)\n .map(c => c.split(','))\n .map(a => ({method: a[1], start: +a[2], count: +a[3]}));\n }\n\n /**\n\t * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`\n\t * hook, in which case, plugins will not be called on `afterLayout`.\n\t * @private\n\t */\n _updateLayout(minPadding) {\n if (this.notifyPlugins('beforeLayout', {cancelable: true}) === false) {\n return;\n }\n\n layouts.update(this, this.width, this.height, minPadding);\n\n const area = this.chartArea;\n const noArea = area.width <= 0 || area.height <= 0;\n\n this._layers = [];\n each(this.boxes, (box) => {\n if (noArea && box.position === 'chartArea') {\n // Skip drawing and configuring chartArea boxes when chartArea is zero or negative\n return;\n }\n\n // configure is called twice, once in core.scale.update and once here.\n // Here the boxes are fully updated and at their final positions.\n if (box.configure) {\n box.configure();\n }\n this._layers.push(...box._layers());\n }, this);\n\n this._layers.forEach((item, index) => {\n item._idx = index;\n });\n\n this.notifyPlugins('afterLayout');\n }\n\n /**\n\t * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`\n\t * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.\n\t * @private\n\t */\n _updateDatasets(mode) {\n if (this.notifyPlugins('beforeDatasetsUpdate', {mode, cancelable: true}) === false) {\n return;\n }\n\n for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {\n this.getDatasetMeta(i).controller.configure();\n }\n\n for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {\n this._updateDataset(i, isFunction(mode) ? mode({datasetIndex: i}) : mode);\n }\n\n this.notifyPlugins('afterDatasetsUpdate', {mode});\n }\n\n /**\n\t * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`\n\t * hook, in which case, plugins will not be called on `afterDatasetUpdate`.\n\t * @private\n\t */\n _updateDataset(index, mode) {\n const meta = this.getDatasetMeta(index);\n const args = {meta, index, mode, cancelable: true};\n\n if (this.notifyPlugins('beforeDatasetUpdate', args) === false) {\n return;\n }\n\n meta.controller._update(mode);\n\n args.cancelable = false;\n this.notifyPlugins('afterDatasetUpdate', args);\n }\n\n render() {\n if (this.notifyPlugins('beforeRender', {cancelable: true}) === false) {\n return;\n }\n\n if (animator.has(this)) {\n if (this.attached && !animator.running(this)) {\n animator.start(this);\n }\n } else {\n this.draw();\n onAnimationsComplete({chart: this});\n }\n }\n\n draw() {\n let i;\n if (this._resizeBeforeDraw) {\n const {width, height} = this._resizeBeforeDraw;\n this._resize(width, height);\n this._resizeBeforeDraw = null;\n }\n this.clear();\n\n if (this.width <= 0 || this.height <= 0) {\n return;\n }\n\n if (this.notifyPlugins('beforeDraw', {cancelable: true}) === false) {\n return;\n }\n\n // Because of plugin hooks (before/afterDatasetsDraw), datasets can't\n // currently be part of layers. Instead, we draw\n // layers <= 0 before(default, backward compat), and the rest after\n const layers = this._layers;\n for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {\n layers[i].draw(this.chartArea);\n }\n\n this._drawDatasets();\n\n // Rest of layers\n for (; i < layers.length; ++i) {\n layers[i].draw(this.chartArea);\n }\n\n this.notifyPlugins('afterDraw');\n }\n\n /**\n\t * @private\n\t */\n _getSortedDatasetMetas(filterVisible) {\n const metasets = this._sortedMetasets;\n const result = [];\n let i, ilen;\n\n for (i = 0, ilen = metasets.length; i < ilen; ++i) {\n const meta = metasets[i];\n if (!filterVisible || meta.visible) {\n result.push(meta);\n }\n }\n\n return result;\n }\n\n /**\n\t * Gets the visible dataset metas in drawing order\n\t * @return {object[]}\n\t */\n getSortedVisibleDatasetMetas() {\n return this._getSortedDatasetMetas(true);\n }\n\n /**\n\t * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`\n\t * hook, in which case, plugins will not be called on `afterDatasetsDraw`.\n\t * @private\n\t */\n _drawDatasets() {\n if (this.notifyPlugins('beforeDatasetsDraw', {cancelable: true}) === false) {\n return;\n }\n\n const metasets = this.getSortedVisibleDatasetMetas();\n for (let i = metasets.length - 1; i >= 0; --i) {\n this._drawDataset(metasets[i]);\n }\n\n this.notifyPlugins('afterDatasetsDraw');\n }\n\n /**\n\t * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`\n\t * hook, in which case, plugins will not be called on `afterDatasetDraw`.\n\t * @private\n\t */\n _drawDataset(meta) {\n const ctx = this.ctx;\n const clip = meta._clip;\n const useClip = !clip.disabled;\n const area = getDatasetArea(meta, this.chartArea);\n const args = {\n meta,\n index: meta.index,\n cancelable: true\n };\n\n if (this.notifyPlugins('beforeDatasetDraw', args) === false) {\n return;\n }\n\n if (useClip) {\n clipArea(ctx, {\n left: clip.left === false ? 0 : area.left - clip.left,\n right: clip.right === false ? this.width : area.right + clip.right,\n top: clip.top === false ? 0 : area.top - clip.top,\n bottom: clip.bottom === false ? this.height : area.bottom + clip.bottom\n });\n }\n\n meta.controller.draw();\n\n if (useClip) {\n unclipArea(ctx);\n }\n\n args.cancelable = false;\n this.notifyPlugins('afterDatasetDraw', args);\n }\n\n /**\n * Checks whether the given point is in the chart area.\n * @param {Point} point - in relative coordinates (see, e.g., getRelativePosition)\n * @returns {boolean}\n */\n isPointInArea(point) {\n return _isPointInArea(point, this.chartArea, this._minPadding);\n }\n\n getElementsAtEventForMode(e, mode, options, useFinalPosition) {\n const method = Interaction.modes[mode];\n if (typeof method === 'function') {\n return method(this, e, options, useFinalPosition);\n }\n\n return [];\n }\n\n getDatasetMeta(datasetIndex) {\n const dataset = this.data.datasets[datasetIndex];\n const metasets = this._metasets;\n let meta = metasets.filter(x => x && x._dataset === dataset).pop();\n\n if (!meta) {\n meta = {\n type: null,\n data: [],\n dataset: null,\n controller: null,\n hidden: null,\t\t\t// See isDatasetVisible() comment\n xAxisID: null,\n yAxisID: null,\n order: dataset && dataset.order || 0,\n index: datasetIndex,\n _dataset: dataset,\n _parsed: [],\n _sorted: false\n };\n metasets.push(meta);\n }\n\n return meta;\n }\n\n getContext() {\n return this.$context || (this.$context = createContext(null, {chart: this, type: 'chart'}));\n }\n\n getVisibleDatasetCount() {\n return this.getSortedVisibleDatasetMetas().length;\n }\n\n isDatasetVisible(datasetIndex) {\n const dataset = this.data.datasets[datasetIndex];\n if (!dataset) {\n return false;\n }\n\n const meta = this.getDatasetMeta(datasetIndex);\n\n // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,\n // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.\n return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;\n }\n\n setDatasetVisibility(datasetIndex, visible) {\n const meta = this.getDatasetMeta(datasetIndex);\n meta.hidden = !visible;\n }\n\n toggleDataVisibility(index) {\n this._hiddenIndices[index] = !this._hiddenIndices[index];\n }\n\n getDataVisibility(index) {\n return !this._hiddenIndices[index];\n }\n\n /**\n\t * @private\n\t */\n _updateVisibility(datasetIndex, dataIndex, visible) {\n const mode = visible ? 'show' : 'hide';\n const meta = this.getDatasetMeta(datasetIndex);\n const anims = meta.controller._resolveAnimations(undefined, mode);\n\n if (defined(dataIndex)) {\n meta.data[dataIndex].hidden = !visible;\n this.update();\n } else {\n this.setDatasetVisibility(datasetIndex, visible);\n // Animate visible state, so hide animation can be seen. This could be handled better if update / updateDataset returned a Promise.\n anims.update(meta, {visible});\n this.update((ctx) => ctx.datasetIndex === datasetIndex ? mode : undefined);\n }\n }\n\n hide(datasetIndex, dataIndex) {\n this._updateVisibility(datasetIndex, dataIndex, false);\n }\n\n show(datasetIndex, dataIndex) {\n this._updateVisibility(datasetIndex, dataIndex, true);\n }\n\n /**\n\t * @private\n\t */\n _destroyDatasetMeta(datasetIndex) {\n const meta = this._metasets[datasetIndex];\n if (meta && meta.controller) {\n meta.controller._destroy();\n }\n delete this._metasets[datasetIndex];\n }\n\n _stop() {\n let i, ilen;\n this.stop();\n animator.remove(this);\n\n for (i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {\n this._destroyDatasetMeta(i);\n }\n }\n\n destroy() {\n this.notifyPlugins('beforeDestroy');\n const {canvas, ctx} = this;\n\n this._stop();\n this.config.clearCache();\n\n if (canvas) {\n this.unbindEvents();\n clearCanvas(canvas, ctx);\n this.platform.releaseContext(ctx);\n this.canvas = null;\n this.ctx = null;\n }\n\n delete instances[this.id];\n\n this.notifyPlugins('afterDestroy');\n }\n\n toBase64Image(...args) {\n return this.canvas.toDataURL(...args);\n }\n\n /**\n\t * @private\n\t */\n bindEvents() {\n this.bindUserEvents();\n if (this.options.responsive) {\n this.bindResponsiveEvents();\n } else {\n this.attached = true;\n }\n }\n\n /**\n * @private\n */\n bindUserEvents() {\n const listeners = this._listeners;\n const platform = this.platform;\n\n const _add = (type, listener) => {\n platform.addEventListener(this, type, listener);\n listeners[type] = listener;\n };\n\n const listener = (e, x, y) => {\n e.offsetX = x;\n e.offsetY = y;\n this._eventHandler(e);\n };\n\n each(this.options.events, (type) => _add(type, listener));\n }\n\n /**\n * @private\n */\n bindResponsiveEvents() {\n if (!this._responsiveListeners) {\n this._responsiveListeners = {};\n }\n const listeners = this._responsiveListeners;\n const platform = this.platform;\n\n const _add = (type, listener) => {\n platform.addEventListener(this, type, listener);\n listeners[type] = listener;\n };\n const _remove = (type, listener) => {\n if (listeners[type]) {\n platform.removeEventListener(this, type, listener);\n delete listeners[type];\n }\n };\n\n const listener = (width, height) => {\n if (this.canvas) {\n this.resize(width, height);\n }\n };\n\n let detached; // eslint-disable-line prefer-const\n const attached = () => {\n _remove('attach', attached);\n\n this.attached = true;\n this.resize();\n\n _add('resize', listener);\n _add('detach', detached);\n };\n\n detached = () => {\n this.attached = false;\n\n _remove('resize', listener);\n\n // Stop animating and remove metasets, so when re-attached, the animations start from beginning.\n this._stop();\n this._resize(0, 0);\n\n _add('attach', attached);\n };\n\n if (platform.isAttached(this.canvas)) {\n attached();\n } else {\n detached();\n }\n }\n\n /**\n\t * @private\n\t */\n unbindEvents() {\n each(this._listeners, (listener, type) => {\n this.platform.removeEventListener(this, type, listener);\n });\n this._listeners = {};\n\n each(this._responsiveListeners, (listener, type) => {\n this.platform.removeEventListener(this, type, listener);\n });\n this._responsiveListeners = undefined;\n }\n\n updateHoverStyle(items, mode, enabled) {\n const prefix = enabled ? 'set' : 'remove';\n let meta, item, i, ilen;\n\n if (mode === 'dataset') {\n meta = this.getDatasetMeta(items[0].datasetIndex);\n meta.controller['_' + prefix + 'DatasetHoverStyle']();\n }\n\n for (i = 0, ilen = items.length; i < ilen; ++i) {\n item = items[i];\n const controller = item && this.getDatasetMeta(item.datasetIndex).controller;\n if (controller) {\n controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);\n }\n }\n }\n\n /**\n\t * Get active (hovered) elements\n\t * @returns array\n\t */\n getActiveElements() {\n return this._active || [];\n }\n\n /**\n\t * Set active (hovered) elements\n\t * @param {array} activeElements New active data points\n\t */\n setActiveElements(activeElements) {\n const lastActive = this._active || [];\n const active = activeElements.map(({datasetIndex, index}) => {\n const meta = this.getDatasetMeta(datasetIndex);\n if (!meta) {\n throw new Error('No dataset found at index ' + datasetIndex);\n }\n\n return {\n datasetIndex,\n element: meta.data[index],\n index,\n };\n });\n const changed = !_elementsEqual(active, lastActive);\n\n if (changed) {\n this._active = active;\n // Make sure we don't use the previous mouse event to override the active elements in update.\n this._lastEvent = null;\n this._updateHoverStyles(active, lastActive);\n }\n }\n\n /**\n\t * Calls enabled plugins on the specified hook and with the given args.\n\t * This method immediately returns as soon as a plugin explicitly returns false. The\n\t * returned value can be used, for instance, to interrupt the current action.\n\t * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').\n\t * @param {Object} [args] - Extra arguments to apply to the hook call.\n * @param {import('./core.plugins.js').filterCallback} [filter] - Filtering function for limiting which plugins are notified\n\t * @returns {boolean} false if any of the plugins return false, else returns true.\n\t */\n notifyPlugins(hook, args, filter) {\n return this._plugins.notify(this, hook, args, filter);\n }\n\n /**\n * Check if a plugin with the specific ID is registered and enabled\n * @param {string} pluginId - The ID of the plugin of which to check if it is enabled\n * @returns {boolean}\n */\n isPluginEnabled(pluginId) {\n return this._plugins._cache.filter(p => p.plugin.id === pluginId).length === 1;\n }\n\n /**\n\t * @private\n\t */\n _updateHoverStyles(active, lastActive, replay) {\n const hoverOptions = this.options.hover;\n const diff = (a, b) => a.filter(x => !b.some(y => x.datasetIndex === y.datasetIndex && x.index === y.index));\n const deactivated = diff(lastActive, active);\n const activated = replay ? active : diff(active, lastActive);\n\n if (deactivated.length) {\n this.updateHoverStyle(deactivated, hoverOptions.mode, false);\n }\n\n if (activated.length && hoverOptions.mode) {\n this.updateHoverStyle(activated, hoverOptions.mode, true);\n }\n }\n\n /**\n\t * @private\n\t */\n _eventHandler(e, replay) {\n const args = {\n event: e,\n replay,\n cancelable: true,\n inChartArea: this.isPointInArea(e)\n };\n const eventFilter = (plugin) => (plugin.options.events || this.options.events).includes(e.native.type);\n\n if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) {\n return;\n }\n\n const changed = this._handleEvent(e, replay, args.inChartArea);\n\n args.cancelable = false;\n this.notifyPlugins('afterEvent', args, eventFilter);\n\n if (changed || args.changed) {\n this.render();\n }\n\n return this;\n }\n\n /**\n\t * Handle an event\n\t * @param {ChartEvent} e the event to handle\n\t * @param {boolean} [replay] - true if the event was replayed by `update`\n * @param {boolean} [inChartArea] - true if the event is inside chartArea\n\t * @return {boolean} true if the chart needs to re-render\n\t * @private\n\t */\n _handleEvent(e, replay, inChartArea) {\n const {_active: lastActive = [], options} = this;\n\n // If the event is replayed from `update`, we should evaluate with the final positions.\n //\n // The `replay`:\n // It's the last event (excluding click) that has occurred before `update`.\n // So mouse has not moved. It's also over the chart, because there is a `replay`.\n //\n // The why:\n // If animations are active, the elements haven't moved yet compared to state before update.\n // But if they will, we are activating the elements that would be active, if this check\n // was done after the animations have completed. => \"final positions\".\n // If there is no animations, the \"final\" and \"current\" positions are equal.\n // This is done so we do not have to evaluate the active elements each animation frame\n // - it would be expensive.\n const useFinalPosition = replay;\n const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition);\n const isClick = _isClickEvent(e);\n const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick);\n\n if (inChartArea) {\n // Set _lastEvent to null while we are processing the event handlers.\n // This prevents recursion if the handler calls chart.update()\n this._lastEvent = null;\n\n // Invoke onHover hook\n callCallback(options.onHover, [e, active, this], this);\n\n if (isClick) {\n callCallback(options.onClick, [e, active, this], this);\n }\n }\n\n const changed = !_elementsEqual(active, lastActive);\n if (changed || replay) {\n this._active = active;\n this._updateHoverStyles(active, lastActive, replay);\n }\n\n this._lastEvent = lastEvent;\n\n return changed;\n }\n\n /**\n * @param {ChartEvent} e - The event\n * @param {import('../types/index.js').ActiveElement[]} lastActive - Previously active elements\n * @param {boolean} inChartArea - Is the envent inside chartArea\n * @param {boolean} useFinalPosition - Should the evaluation be done with current or final (after animation) element positions\n * @returns {import('../types/index.js').ActiveElement[]} - The active elements\n * @pravate\n */\n _getActiveElements(e, lastActive, inChartArea, useFinalPosition) {\n if (e.type === 'mouseout') {\n return [];\n }\n\n if (!inChartArea) {\n // Let user control the active elements outside chartArea. Eg. using Legend.\n return lastActive;\n }\n\n const hoverOptions = this.options.hover;\n return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);\n }\n}\n\n// @ts-ignore\nfunction invalidatePlugins() {\n return each(Chart.instances, (chart) => chart._plugins.invalidate());\n}\n\nexport default Chart;\n","/**\n * @namespace Chart._adapters\n * @since 2.8.0\n * @private\n */\n\nimport type {AnyObject} from '../types/basic.js';\nimport type {ChartOptions} from '../types/index.js';\n\nexport type TimeUnit = 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';\n\nexport interface DateAdapter {\n readonly options: T;\n /**\n * Will called with chart options after adapter creation.\n */\n init(this: DateAdapter, chartOptions: ChartOptions): void;\n /**\n * Returns a map of time formats for the supported formatting units defined\n * in Unit as well as 'datetime' representing a detailed date/time string.\n */\n formats(this: DateAdapter): Record;\n /**\n * Parses the given `value` and return the associated timestamp.\n * @param value - the value to parse (usually comes from the data)\n * @param [format] - the expected data format\n */\n parse(this: DateAdapter, value: unknown, format?: TimeUnit): number | null;\n /**\n * Returns the formatted date in the specified `format` for a given `timestamp`.\n * @param timestamp - the timestamp to format\n * @param format - the date/time token\n */\n format(this: DateAdapter, timestamp: number, format: TimeUnit): string;\n /**\n * Adds the specified `amount` of `unit` to the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param amount - the amount to add\n * @param unit - the unit as string\n */\n add(this: DateAdapter, timestamp: number, amount: number, unit: TimeUnit): number;\n /**\n * Returns the number of `unit` between the given timestamps.\n * @param a - the input timestamp (reference)\n * @param b - the timestamp to subtract\n * @param unit - the unit as string\n */\n diff(this: DateAdapter, a: number, b: number, unit: TimeUnit): number;\n /**\n * Returns start of `unit` for the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param unit - the unit as string\n * @param [weekday] - the ISO day of the week with 1 being Monday\n * and 7 being Sunday (only needed if param *unit* is `isoWeek`).\n */\n startOf(this: DateAdapter, timestamp: number, unit: TimeUnit | 'isoWeek', weekday?: number): number;\n /**\n * Returns end of `unit` for the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param unit - the unit as string\n */\n endOf(this: DateAdapter, timestamp: number, unit: TimeUnit | 'isoWeek'): number;\n}\n\nfunction abstract(): T {\n throw new Error('This method is not implemented: Check that a complete date adapter is provided.');\n}\n\n/**\n * Date adapter (current used by the time scale)\n * @namespace Chart._adapters._date\n * @memberof Chart._adapters\n * @private\n */\nclass DateAdapterBase implements DateAdapter {\n\n /**\n * Override default date adapter methods.\n * Accepts type parameter to define options type.\n * @example\n * Chart._adapters._date.override<{myAdapterOption: string}>({\n * init() {\n * console.log(this.options.myAdapterOption);\n * }\n * })\n */\n static override(\n members: Partial, 'options'>>\n ) {\n Object.assign(DateAdapterBase.prototype, members);\n }\n\n readonly options: AnyObject;\n\n constructor(options: AnyObject) {\n this.options = options || {};\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n init() {}\n\n formats(): Record {\n return abstract();\n }\n\n parse(): number | null {\n return abstract();\n }\n\n format(): string {\n return abstract();\n }\n\n add(): number {\n return abstract();\n }\n\n diff(): number {\n return abstract();\n }\n\n startOf(): number {\n return abstract();\n }\n\n endOf(): number {\n return abstract();\n }\n}\n\nexport default {\n _date: DateAdapterBase\n};\n","import DatasetController from '../core/core.datasetController.js';\nimport {\n _arrayUnique, isArray, isNullOrUndef,\n valueOrDefault, resolveObjectKey, sign, defined\n} from '../helpers/index.js';\n\nfunction getAllScaleValues(scale, type) {\n if (!scale._cache.$bar) {\n const visibleMetas = scale.getMatchingVisibleMetas(type);\n let values = [];\n\n for (let i = 0, ilen = visibleMetas.length; i < ilen; i++) {\n values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale));\n }\n scale._cache.$bar = _arrayUnique(values.sort((a, b) => a - b));\n }\n return scale._cache.$bar;\n}\n\n/**\n * Computes the \"optimal\" sample size to maintain bars equally sized while preventing overlap.\n * @private\n */\nfunction computeMinSampleSize(meta) {\n const scale = meta.iScale;\n const values = getAllScaleValues(scale, meta.type);\n let min = scale._length;\n let i, ilen, curr, prev;\n const updateMinAndPrev = () => {\n if (curr === 32767 || curr === -32768) {\n // Ignore truncated pixels\n return;\n }\n if (defined(prev)) {\n // curr - prev === 0 is ignored\n min = Math.min(min, Math.abs(curr - prev) || min);\n }\n prev = curr;\n };\n\n for (i = 0, ilen = values.length; i < ilen; ++i) {\n curr = scale.getPixelForValue(values[i]);\n updateMinAndPrev();\n }\n\n prev = undefined;\n for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {\n curr = scale.getPixelForTick(i);\n updateMinAndPrev();\n }\n\n return min;\n}\n\n/**\n * Computes an \"ideal\" category based on the absolute bar thickness or, if undefined or null,\n * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This\n * mode currently always generates bars equally sized (until we introduce scriptable options?).\n * @private\n */\nfunction computeFitCategoryTraits(index, ruler, options, stackCount) {\n const thickness = options.barThickness;\n let size, ratio;\n\n if (isNullOrUndef(thickness)) {\n size = ruler.min * options.categoryPercentage;\n ratio = options.barPercentage;\n } else {\n // When bar thickness is enforced, category and bar percentages are ignored.\n // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')\n // and deprecate barPercentage since this value is ignored when thickness is absolute.\n size = thickness * stackCount;\n ratio = 1;\n }\n\n return {\n chunk: size / stackCount,\n ratio,\n start: ruler.pixels[index] - (size / 2)\n };\n}\n\n/**\n * Computes an \"optimal\" category that globally arranges bars side by side (no gap when\n * percentage options are 1), based on the previous and following categories. This mode\n * generates bars with different widths when data are not evenly spaced.\n * @private\n */\nfunction computeFlexCategoryTraits(index, ruler, options, stackCount) {\n const pixels = ruler.pixels;\n const curr = pixels[index];\n let prev = index > 0 ? pixels[index - 1] : null;\n let next = index < pixels.length - 1 ? pixels[index + 1] : null;\n const percent = options.categoryPercentage;\n\n if (prev === null) {\n // first data: its size is double based on the next point or,\n // if it's also the last data, we use the scale size.\n prev = curr - (next === null ? ruler.end - ruler.start : next - curr);\n }\n\n if (next === null) {\n // last data: its size is also double based on the previous point.\n next = curr + curr - prev;\n }\n\n const start = curr - (curr - Math.min(prev, next)) / 2 * percent;\n const size = Math.abs(next - prev) / 2 * percent;\n\n return {\n chunk: size / stackCount,\n ratio: options.barPercentage,\n start\n };\n}\n\nfunction parseFloatBar(entry, item, vScale, i) {\n const startValue = vScale.parse(entry[0], i);\n const endValue = vScale.parse(entry[1], i);\n const min = Math.min(startValue, endValue);\n const max = Math.max(startValue, endValue);\n let barStart = min;\n let barEnd = max;\n\n if (Math.abs(min) > Math.abs(max)) {\n barStart = max;\n barEnd = min;\n }\n\n // Store `barEnd` (furthest away from origin) as parsed value,\n // to make stacking straight forward\n item[vScale.axis] = barEnd;\n\n item._custom = {\n barStart,\n barEnd,\n start: startValue,\n end: endValue,\n min,\n max\n };\n}\n\nfunction parseValue(entry, item, vScale, i) {\n if (isArray(entry)) {\n parseFloatBar(entry, item, vScale, i);\n } else {\n item[vScale.axis] = vScale.parse(entry, i);\n }\n return item;\n}\n\nfunction parseArrayOrPrimitive(meta, data, start, count) {\n const iScale = meta.iScale;\n const vScale = meta.vScale;\n const labels = iScale.getLabels();\n const singleScale = iScale === vScale;\n const parsed = [];\n let i, ilen, item, entry;\n\n for (i = start, ilen = start + count; i < ilen; ++i) {\n entry = data[i];\n item = {};\n item[iScale.axis] = singleScale || iScale.parse(labels[i], i);\n parsed.push(parseValue(entry, item, vScale, i));\n }\n return parsed;\n}\n\nfunction isFloatBar(custom) {\n return custom && custom.barStart !== undefined && custom.barEnd !== undefined;\n}\n\nfunction barSign(size, vScale, actualBase) {\n if (size !== 0) {\n return sign(size);\n }\n return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);\n}\n\nfunction borderProps(properties) {\n let reverse, start, end, top, bottom;\n if (properties.horizontal) {\n reverse = properties.base > properties.x;\n start = 'left';\n end = 'right';\n } else {\n reverse = properties.base < properties.y;\n start = 'bottom';\n end = 'top';\n }\n if (reverse) {\n top = 'end';\n bottom = 'start';\n } else {\n top = 'start';\n bottom = 'end';\n }\n return {start, end, reverse, top, bottom};\n}\n\nfunction setBorderSkipped(properties, options, stack, index) {\n let edge = options.borderSkipped;\n const res = {};\n\n if (!edge) {\n properties.borderSkipped = res;\n return;\n }\n\n if (edge === true) {\n properties.borderSkipped = {top: true, right: true, bottom: true, left: true};\n return;\n }\n\n const {start, end, reverse, top, bottom} = borderProps(properties);\n\n if (edge === 'middle' && stack) {\n properties.enableBorderRadius = true;\n if ((stack._top || 0) === index) {\n edge = top;\n } else if ((stack._bottom || 0) === index) {\n edge = bottom;\n } else {\n res[parseEdge(bottom, start, end, reverse)] = true;\n edge = top;\n }\n }\n\n res[parseEdge(edge, start, end, reverse)] = true;\n properties.borderSkipped = res;\n}\n\nfunction parseEdge(edge, a, b, reverse) {\n if (reverse) {\n edge = swap(edge, a, b);\n edge = startEnd(edge, b, a);\n } else {\n edge = startEnd(edge, a, b);\n }\n return edge;\n}\n\nfunction swap(orig, v1, v2) {\n return orig === v1 ? v2 : orig === v2 ? v1 : orig;\n}\n\nfunction startEnd(v, start, end) {\n return v === 'start' ? start : v === 'end' ? end : v;\n}\n\nfunction setInflateAmount(properties, {inflateAmount}, ratio) {\n properties.inflateAmount = inflateAmount === 'auto'\n ? ratio === 1 ? 0.33 : 0\n : inflateAmount;\n}\n\nexport default class BarController extends DatasetController {\n\n static id = 'bar';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'bar',\n\n categoryPercentage: 0.8,\n barPercentage: 0.9,\n grouped: true,\n\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'base', 'width', 'height']\n }\n }\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n _index_: {\n type: 'category',\n offset: true,\n grid: {\n offset: true\n }\n },\n _value_: {\n type: 'linear',\n beginAtZero: true,\n }\n }\n };\n\n\n /**\n\t * Overriding primitive data parsing since we support mixed primitive/array\n\t * data for float bars\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n return parseArrayOrPrimitive(meta, data, start, count);\n }\n\n /**\n\t * Overriding array data parsing since we support mixed primitive/array\n\t * data for float bars\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n return parseArrayOrPrimitive(meta, data, start, count);\n }\n\n /**\n\t * Overriding object data parsing since we support mixed primitive/array\n\t * value-scale data for float bars\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const {iScale, vScale} = meta;\n const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;\n const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;\n const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;\n const parsed = [];\n let i, ilen, item, obj;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n obj = data[i];\n item = {};\n item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);\n parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n updateRangeFromParsed(range, scale, parsed, stack) {\n super.updateRangeFromParsed(range, scale, parsed, stack);\n const custom = parsed._custom;\n if (custom && scale === this._cachedMeta.vScale) {\n // float bar: only one end of the bar is considered by `super`\n range.min = Math.min(range.min, custom.min);\n range.max = Math.max(range.max, custom.max);\n }\n }\n\n /**\n\t * @return {number|boolean}\n\t * @protected\n\t */\n getMaxOverflow() {\n return 0;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const {iScale, vScale} = meta;\n const parsed = this.getParsed(index);\n const custom = parsed._custom;\n const value = isFloatBar(custom)\n ? '[' + custom.start + ', ' + custom.end + ']'\n : '' + vScale.getLabelForValue(parsed[vScale.axis]);\n\n return {\n label: '' + iScale.getLabelForValue(parsed[iScale.axis]),\n value\n };\n }\n\n initialize() {\n this.enableOptionSharing = true;\n\n super.initialize();\n\n const meta = this._cachedMeta;\n meta.stack = this.getDataset().stack;\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n this.updateElements(meta.data, 0, meta.data.length, mode);\n }\n\n updateElements(bars, start, count, mode) {\n const reset = mode === 'reset';\n const {index, _cachedMeta: {vScale}} = this;\n const base = vScale.getBasePixel();\n const horizontal = vScale.isHorizontal();\n const ruler = this._getRuler();\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n\n for (let i = start; i < start + count; i++) {\n const parsed = this.getParsed(i);\n const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {base, head: base} : this._calculateBarValuePixels(i);\n const ipixels = this._calculateBarIndexPixels(i, ruler);\n const stack = (parsed._stacks || {})[vScale.axis];\n\n const properties = {\n horizontal,\n base: vpixels.base,\n enableBorderRadius: !stack || isFloatBar(parsed._custom) || (index === stack._top || index === stack._bottom),\n x: horizontal ? vpixels.head : ipixels.center,\n y: horizontal ? ipixels.center : vpixels.head,\n height: horizontal ? ipixels.size : Math.abs(vpixels.size),\n width: horizontal ? Math.abs(vpixels.size) : ipixels.size\n };\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);\n }\n const options = properties.options || bars[i].options;\n setBorderSkipped(properties, options, stack, index);\n setInflateAmount(properties, options, ruler.ratio);\n this.updateElement(bars[i], i, properties, mode);\n }\n }\n\n /**\n\t * Returns the stacks based on groups and bar visibility.\n\t * @param {number} [last] - The dataset index\n\t * @param {number} [dataIndex] - The data index of the ruler\n\t * @returns {string[]} The list of stack IDs\n\t * @private\n\t */\n _getStacks(last, dataIndex) {\n const {iScale} = this._cachedMeta;\n const metasets = iScale.getMatchingVisibleMetas(this._type)\n .filter(meta => meta.controller.options.grouped);\n const stacked = iScale.options.stacked;\n const stacks = [];\n\n const skipNull = (meta) => {\n const parsed = meta.controller.getParsed(dataIndex);\n const val = parsed && parsed[meta.vScale.axis];\n\n if (isNullOrUndef(val) || isNaN(val)) {\n return true;\n }\n };\n\n for (const meta of metasets) {\n if (dataIndex !== undefined && skipNull(meta)) {\n continue;\n }\n\n // stacked | meta.stack\n // | found | not found | undefined\n // false | x | x | x\n // true | | x |\n // undefined | | x | x\n if (stacked === false || stacks.indexOf(meta.stack) === -1 ||\n\t\t\t\t(stacked === undefined && meta.stack === undefined)) {\n stacks.push(meta.stack);\n }\n if (meta.index === last) {\n break;\n }\n }\n\n // No stacks? that means there is no visible data. Let's still initialize an `undefined`\n // stack where possible invisible bars will be located.\n // https://github.com/chartjs/Chart.js/issues/6368\n if (!stacks.length) {\n stacks.push(undefined);\n }\n\n return stacks;\n }\n\n /**\n\t * Returns the effective number of stacks based on groups and bar visibility.\n\t * @private\n\t */\n _getStackCount(index) {\n return this._getStacks(undefined, index).length;\n }\n\n /**\n\t * Returns the stack index for the given dataset based on groups and bar visibility.\n\t * @param {number} [datasetIndex] - The dataset index\n\t * @param {string} [name] - The stack name to find\n * @param {number} [dataIndex]\n\t * @returns {number} The stack index\n\t * @private\n\t */\n _getStackIndex(datasetIndex, name, dataIndex) {\n const stacks = this._getStacks(datasetIndex, dataIndex);\n const index = (name !== undefined)\n ? stacks.indexOf(name)\n : -1; // indexOf returns -1 if element is not present\n\n return (index === -1)\n ? stacks.length - 1\n : index;\n }\n\n /**\n\t * @private\n\t */\n _getRuler() {\n const opts = this.options;\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const pixels = [];\n let i, ilen;\n\n for (i = 0, ilen = meta.data.length; i < ilen; ++i) {\n pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i));\n }\n\n const barThickness = opts.barThickness;\n const min = barThickness || computeMinSampleSize(meta);\n\n return {\n min,\n pixels,\n start: iScale._startPixel,\n end: iScale._endPixel,\n stackCount: this._getStackCount(),\n scale: iScale,\n grouped: opts.grouped,\n // bar thickness ratio used for non-grouped bars\n ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage\n };\n }\n\n /**\n\t * Note: pixel values are not clamped to the scale area.\n\t * @private\n\t */\n _calculateBarValuePixels(index) {\n const {_cachedMeta: {vScale, _stacked, index: datasetIndex}, options: {base: baseValue, minBarLength}} = this;\n const actualBase = baseValue || 0;\n const parsed = this.getParsed(index);\n const custom = parsed._custom;\n const floating = isFloatBar(custom);\n let value = parsed[vScale.axis];\n let start = 0;\n let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value;\n let head, size;\n\n if (length !== value) {\n start = length - value;\n length = value;\n }\n\n if (floating) {\n value = custom.barStart;\n length = custom.barEnd - custom.barStart;\n // bars crossing origin are not stacked\n if (value !== 0 && sign(value) !== sign(custom.barEnd)) {\n start = 0;\n }\n start += value;\n }\n\n const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;\n let base = vScale.getPixelForValue(startValue);\n\n if (this.chart.getDataVisibility(index)) {\n head = vScale.getPixelForValue(start + length);\n } else {\n // When not visible, no height\n head = base;\n }\n\n size = head - base;\n\n if (Math.abs(size) < minBarLength) {\n size = barSign(size, vScale, actualBase) * minBarLength;\n if (value === actualBase) {\n base -= size / 2;\n }\n const startPixel = vScale.getPixelForDecimal(0);\n const endPixel = vScale.getPixelForDecimal(1);\n const min = Math.min(startPixel, endPixel);\n const max = Math.max(startPixel, endPixel);\n base = Math.max(Math.min(base, max), min);\n head = base + size;\n\n if (_stacked && !floating) {\n // visual data coordinates after applying minBarLength\n parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base);\n }\n }\n\n if (base === vScale.getPixelForValue(actualBase)) {\n const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2;\n base += halfGrid;\n size -= halfGrid;\n }\n\n return {\n size,\n base,\n head,\n center: head + size / 2\n };\n }\n\n /**\n\t * @private\n\t */\n _calculateBarIndexPixels(index, ruler) {\n const scale = ruler.scale;\n const options = this.options;\n const skipNull = options.skipNull;\n const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);\n let center, size;\n if (ruler.grouped) {\n const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount;\n const range = options.barThickness === 'flex'\n ? computeFlexCategoryTraits(index, ruler, options, stackCount)\n : computeFitCategoryTraits(index, ruler, options, stackCount);\n\n const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined);\n center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);\n size = Math.min(maxBarThickness, range.chunk * range.ratio);\n } else {\n // For non-grouped bar charts, exact pixel values are used\n center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index);\n size = Math.min(maxBarThickness, ruler.min * ruler.ratio);\n }\n\n return {\n base: center - size / 2,\n head: center + size / 2,\n center,\n size\n };\n }\n\n draw() {\n const meta = this._cachedMeta;\n const vScale = meta.vScale;\n const rects = meta.data;\n const ilen = rects.length;\n let i = 0;\n\n for (; i < ilen; ++i) {\n if (this.getParsed(i)[vScale.axis] !== null) {\n rects[i].draw(this._ctx);\n }\n }\n }\n\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isObject, resolveObjectKey, toPercentage, toDimension, valueOrDefault} from '../helpers/helpers.core.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\nimport {toRadians, PI, TAU, HALF_PI, _angleBetween} from '../helpers/helpers.math.js';\n\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\nfunction getRatioAndOffset(rotation, circumference, cutout) {\n let ratioX = 1;\n let ratioY = 1;\n let offsetX = 0;\n let offsetY = 0;\n // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc\n if (circumference < TAU) {\n const startAngle = rotation;\n const endAngle = startAngle + circumference;\n const startX = Math.cos(startAngle);\n const startY = Math.sin(startAngle);\n const endX = Math.cos(endAngle);\n const endY = Math.sin(endAngle);\n const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);\n const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);\n const maxX = calcMax(0, startX, endX);\n const maxY = calcMax(HALF_PI, startY, endY);\n const minX = calcMin(PI, startX, endX);\n const minY = calcMin(PI + HALF_PI, startY, endY);\n ratioX = (maxX - minX) / 2;\n ratioY = (maxY - minY) / 2;\n offsetX = -(maxX + minX) / 2;\n offsetY = -(maxY + minY) / 2;\n }\n return {ratioX, ratioY, offsetX, offsetY};\n}\n\nexport default class DoughnutController extends DatasetController {\n\n static id = 'doughnut';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'arc',\n animation: {\n // Boolean - Whether we animate the rotation of the Doughnut\n animateRotate: true,\n // Boolean - Whether we animate scaling the Doughnut from the centre\n animateScale: false\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing']\n },\n },\n // The percentage of the chart that we cut out of the middle.\n cutout: '50%',\n\n // The rotation of the chart, where the first data arc begins.\n rotation: 0,\n\n // The total circumference of the chart.\n circumference: 360,\n\n // The outer radius of the chart\n radius: '100%',\n\n // Spacing between arcs\n spacing: 0,\n\n indexAxis: 'r',\n };\n\n static descriptors = {\n _scriptable: (name) => name !== 'spacing',\n _indexable: (name) => name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash'),\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n // Need to override these to give a nice default\n plugins: {\n legend: {\n labels: {\n generateLabels(chart) {\n const data = chart.data;\n if (data.labels.length && data.datasets.length) {\n const {labels: {pointStyle, color}} = chart.legend.options;\n\n return data.labels.map((label, i) => {\n const meta = chart.getDatasetMeta(0);\n const style = meta.controller.getStyle(i);\n\n return {\n text: label,\n fillStyle: style.backgroundColor,\n strokeStyle: style.borderColor,\n fontColor: color,\n lineWidth: style.borderWidth,\n pointStyle: pointStyle,\n hidden: !chart.getDataVisibility(i),\n\n // Extra data used for toggling the correct item\n index: i\n };\n });\n }\n return [];\n }\n },\n\n onClick(e, legendItem, legend) {\n legend.chart.toggleDataVisibility(legendItem.index);\n legend.chart.update();\n }\n }\n }\n };\n\n constructor(chart, datasetIndex) {\n super(chart, datasetIndex);\n\n this.enableOptionSharing = true;\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n this.offsetX = undefined;\n this.offsetY = undefined;\n }\n\n linkScales() {}\n\n /**\n\t * Override data parsing, since we are not using scales\n\t */\n parse(start, count) {\n const data = this.getDataset().data;\n const meta = this._cachedMeta;\n\n if (this._parsing === false) {\n meta._parsed = data;\n } else {\n let getter = (i) => +data[i];\n\n if (isObject(data[start])) {\n const {key = 'value'} = this._parsing;\n getter = (i) => +resolveObjectKey(data[i], key);\n }\n\n let i, ilen;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n meta._parsed[i] = getter(i);\n }\n }\n }\n\n /**\n\t * @private\n\t */\n _getRotation() {\n return toRadians(this.options.rotation - 90);\n }\n\n /**\n\t * @private\n\t */\n _getCircumference() {\n return toRadians(this.options.circumference);\n }\n\n /**\n\t * Get the maximal rotation & circumference extents\n\t * across all visible datasets.\n\t */\n _getRotationExtents() {\n let min = TAU;\n let max = -TAU;\n\n for (let i = 0; i < this.chart.data.datasets.length; ++i) {\n if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) {\n const controller = this.chart.getDatasetMeta(i).controller;\n const rotation = controller._getRotation();\n const circumference = controller._getCircumference();\n\n min = Math.min(min, rotation);\n max = Math.max(max, rotation + circumference);\n }\n }\n\n return {\n rotation: min,\n circumference: max - min,\n };\n }\n\n /**\n\t * @param {string} mode\n\t */\n update(mode) {\n const chart = this.chart;\n const {chartArea} = chart;\n const meta = this._cachedMeta;\n const arcs = meta.data;\n const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;\n const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);\n const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1);\n const chartWeight = this._getRingWeight(this.index);\n\n // Compute the maximal rotation & circumference limits.\n // If we only consider our dataset, this can cause problems when two datasets\n // are both less than a circle with different rotations (starting angles)\n const {circumference, rotation} = this._getRotationExtents();\n const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout);\n const maxWidth = (chartArea.width - spacing) / ratioX;\n const maxHeight = (chartArea.height - spacing) / ratioY;\n const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);\n const outerRadius = toDimension(this.options.radius, maxRadius);\n const innerRadius = Math.max(outerRadius * cutout, 0);\n const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();\n this.offsetX = offsetX * outerRadius;\n this.offsetY = offsetY * outerRadius;\n\n meta.total = this.calculateTotal();\n\n this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);\n this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);\n\n this.updateElements(arcs, 0, arcs.length, mode);\n }\n\n /**\n * @private\n */\n _circumference(i, reset) {\n const opts = this.options;\n const meta = this._cachedMeta;\n const circumference = this._getCircumference();\n if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {\n return 0;\n }\n return this.calculateCircumference(meta._parsed[i] * circumference / TAU);\n }\n\n updateElements(arcs, start, count, mode) {\n const reset = mode === 'reset';\n const chart = this.chart;\n const chartArea = chart.chartArea;\n const opts = chart.options;\n const animationOpts = opts.animation;\n const centerX = (chartArea.left + chartArea.right) / 2;\n const centerY = (chartArea.top + chartArea.bottom) / 2;\n const animateScale = reset && animationOpts.animateScale;\n const innerRadius = animateScale ? 0 : this.innerRadius;\n const outerRadius = animateScale ? 0 : this.outerRadius;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n let startAngle = this._getRotation();\n let i;\n\n for (i = 0; i < start; ++i) {\n startAngle += this._circumference(i, reset);\n }\n\n for (i = start; i < start + count; ++i) {\n const circumference = this._circumference(i, reset);\n const arc = arcs[i];\n const properties = {\n x: centerX + this.offsetX,\n y: centerY + this.offsetY,\n startAngle,\n endAngle: startAngle + circumference,\n circumference,\n outerRadius,\n innerRadius\n };\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);\n }\n startAngle += circumference;\n\n this.updateElement(arc, i, properties, mode);\n }\n }\n\n calculateTotal() {\n const meta = this._cachedMeta;\n const metaData = meta.data;\n let total = 0;\n let i;\n\n for (i = 0; i < metaData.length; i++) {\n const value = meta._parsed[i];\n if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {\n total += Math.abs(value);\n }\n }\n\n return total;\n }\n\n calculateCircumference(value) {\n const total = this._cachedMeta.total;\n if (total > 0 && !isNaN(value)) {\n return TAU * (Math.abs(value) / total);\n }\n return 0;\n }\n\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const chart = this.chart;\n const labels = chart.data.labels || [];\n const value = formatNumber(meta._parsed[index], chart.options.locale);\n\n return {\n label: labels[index] || '',\n value,\n };\n }\n\n getMaxBorderWidth(arcs) {\n let max = 0;\n const chart = this.chart;\n let i, ilen, meta, controller, options;\n\n if (!arcs) {\n // Find the outmost visible dataset\n for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {\n if (chart.isDatasetVisible(i)) {\n meta = chart.getDatasetMeta(i);\n arcs = meta.data;\n controller = meta.controller;\n break;\n }\n }\n }\n\n if (!arcs) {\n return 0;\n }\n\n for (i = 0, ilen = arcs.length; i < ilen; ++i) {\n options = controller.resolveDataElementOptions(i);\n if (options.borderAlign !== 'inner') {\n max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);\n }\n }\n return max;\n }\n\n getMaxOffset(arcs) {\n let max = 0;\n\n for (let i = 0, ilen = arcs.length; i < ilen; ++i) {\n const options = this.resolveDataElementOptions(i);\n max = Math.max(max, options.offset || 0, options.hoverOffset || 0);\n }\n return max;\n }\n\n /**\n\t * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly\n\t * @private\n\t */\n _getRingWeightOffset(datasetIndex) {\n let ringWeightOffset = 0;\n\n for (let i = 0; i < datasetIndex; ++i) {\n if (this.chart.isDatasetVisible(i)) {\n ringWeightOffset += this._getRingWeight(i);\n }\n }\n\n return ringWeightOffset;\n }\n\n /**\n\t * @private\n\t */\n _getRingWeight(datasetIndex) {\n return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);\n }\n\n /**\n\t * Returns the sum of all visible data set weights.\n\t * @private\n\t */\n _getVisibleDatasetWeightTotal() {\n return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {toRadians, PI, formatNumber, _parseObjectDataRadialScale} from '../helpers/index.js';\n\nexport default class PolarAreaController extends DatasetController {\n\n static id = 'polarArea';\n\n /**\n * @type {any}\n */\n static defaults = {\n dataElementType: 'arc',\n animation: {\n animateRotate: true,\n animateScale: true\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius']\n },\n },\n indexAxis: 'r',\n startAngle: 0,\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n plugins: {\n legend: {\n labels: {\n generateLabels(chart) {\n const data = chart.data;\n if (data.labels.length && data.datasets.length) {\n const {labels: {pointStyle, color}} = chart.legend.options;\n\n return data.labels.map((label, i) => {\n const meta = chart.getDatasetMeta(0);\n const style = meta.controller.getStyle(i);\n\n return {\n text: label,\n fillStyle: style.backgroundColor,\n strokeStyle: style.borderColor,\n fontColor: color,\n lineWidth: style.borderWidth,\n pointStyle: pointStyle,\n hidden: !chart.getDataVisibility(i),\n\n // Extra data used for toggling the correct item\n index: i\n };\n });\n }\n return [];\n }\n },\n\n onClick(e, legendItem, legend) {\n legend.chart.toggleDataVisibility(legendItem.index);\n legend.chart.update();\n }\n }\n },\n\n scales: {\n r: {\n type: 'radialLinear',\n angleLines: {\n display: false\n },\n beginAtZero: true,\n grid: {\n circular: true\n },\n pointLabels: {\n display: false\n },\n startAngle: 0\n }\n }\n };\n\n constructor(chart, datasetIndex) {\n super(chart, datasetIndex);\n\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n }\n\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const chart = this.chart;\n const labels = chart.data.labels || [];\n const value = formatNumber(meta._parsed[index].r, chart.options.locale);\n\n return {\n label: labels[index] || '',\n value,\n };\n }\n\n parseObjectData(meta, data, start, count) {\n return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);\n }\n\n update(mode) {\n const arcs = this._cachedMeta.data;\n\n this._updateRadius();\n this.updateElements(arcs, 0, arcs.length, mode);\n }\n\n /**\n * @protected\n */\n getMinMax() {\n const meta = this._cachedMeta;\n const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};\n\n meta.data.forEach((element, index) => {\n const parsed = this.getParsed(index).r;\n\n if (!isNaN(parsed) && this.chart.getDataVisibility(index)) {\n if (parsed < range.min) {\n range.min = parsed;\n }\n\n if (parsed > range.max) {\n range.max = parsed;\n }\n }\n });\n\n return range;\n }\n\n /**\n\t * @private\n\t */\n _updateRadius() {\n const chart = this.chart;\n const chartArea = chart.chartArea;\n const opts = chart.options;\n const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);\n\n const outerRadius = Math.max(minSize / 2, 0);\n const innerRadius = Math.max(opts.cutoutPercentage ? (outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);\n const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();\n\n this.outerRadius = outerRadius - (radiusLength * this.index);\n this.innerRadius = this.outerRadius - radiusLength;\n }\n\n updateElements(arcs, start, count, mode) {\n const reset = mode === 'reset';\n const chart = this.chart;\n const opts = chart.options;\n const animationOpts = opts.animation;\n const scale = this._cachedMeta.rScale;\n const centerX = scale.xCenter;\n const centerY = scale.yCenter;\n const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;\n let angle = datasetStartAngle;\n let i;\n\n const defaultAngle = 360 / this.countVisibleElements();\n\n for (i = 0; i < start; ++i) {\n angle += this._computeAngle(i, mode, defaultAngle);\n }\n for (i = start; i < start + count; i++) {\n const arc = arcs[i];\n let startAngle = angle;\n let endAngle = angle + this._computeAngle(i, mode, defaultAngle);\n let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0;\n angle = endAngle;\n\n if (reset) {\n if (animationOpts.animateScale) {\n outerRadius = 0;\n }\n if (animationOpts.animateRotate) {\n startAngle = endAngle = datasetStartAngle;\n }\n }\n\n const properties = {\n x: centerX,\n y: centerY,\n innerRadius: 0,\n outerRadius,\n startAngle,\n endAngle,\n options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode)\n };\n\n this.updateElement(arc, i, properties, mode);\n }\n }\n\n countVisibleElements() {\n const meta = this._cachedMeta;\n let count = 0;\n\n meta.data.forEach((element, index) => {\n if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) {\n count++;\n }\n });\n\n return count;\n }\n\n /**\n\t * @private\n\t */\n _computeAngle(index, mode, defaultAngle) {\n return this.chart.getDataVisibility(index)\n ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle)\n : 0;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {valueOrDefault} from '../helpers/helpers.core.js';\n\nexport default class BubbleController extends DatasetController {\n\n static id = 'bubble';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'point',\n\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'borderWidth', 'radius']\n }\n }\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n x: {\n type: 'linear'\n },\n y: {\n type: 'linear'\n }\n }\n };\n\n initialize() {\n this.enableOptionSharing = true;\n super.initialize();\n }\n\n /**\n\t * Parse array of primitive values\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n const parsed = super.parsePrimitiveData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n parsed[i]._custom = this.resolveDataElementOptions(i + start).radius;\n }\n return parsed;\n }\n\n /**\n\t * Parse array of arrays\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n const parsed = super.parseArrayData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n const item = data[start + i];\n parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius);\n }\n return parsed;\n }\n\n /**\n\t * Parse array of objects\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const parsed = super.parseObjectData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n const item = data[start + i];\n parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius);\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const data = this._cachedMeta.data;\n\n let max = 0;\n for (let i = data.length - 1; i >= 0; --i) {\n max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);\n }\n return max > 0 && max;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const labels = this.chart.data.labels || [];\n const {xScale, yScale} = meta;\n const parsed = this.getParsed(index);\n const x = xScale.getLabelForValue(parsed.x);\n const y = yScale.getLabelForValue(parsed.y);\n const r = parsed._custom;\n\n return {\n label: labels[index] || '',\n value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'\n };\n }\n\n update(mode) {\n const points = this._cachedMeta.data;\n\n // Update Points\n this.updateElements(points, 0, points.length, mode);\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale} = this._cachedMeta;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n\n for (let i = start; i < start + count; i++) {\n const point = points[i];\n const parsed = !reset && this.getParsed(i);\n const properties = {};\n const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);\n const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel);\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n\n if (reset) {\n properties.options.radius = 0;\n }\n }\n\n this.updateElement(point, i, properties, mode);\n }\n }\n\n /**\n\t * @param {number} index\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDataElementOptions(index, mode) {\n const parsed = this.getParsed(index);\n let values = super.resolveDataElementOptions(index, mode);\n\n // In case values were cached (and thus frozen), we need to clone the values\n if (values.$shared) {\n values = Object.assign({}, values, {$shared: false});\n }\n\n // Custom radius resolution\n const radius = values.radius;\n if (mode !== 'active') {\n values.radius = 0;\n }\n values.radius += valueOrDefault(parsed && parsed._custom, radius);\n\n return values;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isNullOrUndef} from '../helpers/index.js';\nimport {isNumber} from '../helpers/helpers.math.js';\nimport {_getStartAndCountOfVisiblePoints, _scaleRangesChanged} from '../helpers/helpers.extras.js';\n\nexport default class LineController extends DatasetController {\n\n static id = 'line';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: 'line',\n dataElementType: 'point',\n\n showLine: true,\n spanGaps: false,\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n _index_: {\n type: 'category',\n },\n _value_: {\n type: 'linear',\n },\n }\n };\n\n initialize() {\n this.enableOptionSharing = true;\n this.supportsDecimation = true;\n super.initialize();\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const {dataset: line, data: points = [], _dataset} = meta;\n // @ts-ignore\n const animationsDisabled = this.chart._animationsDisabled;\n let {start, count} = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);\n\n this._drawStart = start;\n this._drawCount = count;\n\n if (_scaleRangesChanged(meta)) {\n start = 0;\n count = points.length;\n }\n\n // Update Line\n line._chart = this.chart;\n line._datasetIndex = this.index;\n line._decimated = !!_dataset._decimated;\n line.points = points;\n\n const options = this.resolveDatasetElementOptions(mode);\n if (!this.options.showLine) {\n options.borderWidth = 0;\n }\n options.segment = this.options.segment;\n this.updateElement(line, undefined, {\n animated: !animationsDisabled,\n options\n }, mode);\n\n // Update Points\n this.updateElements(points, start, count, mode);\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale, _stacked, _dataset} = this._cachedMeta;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const {spanGaps, segment} = this.options;\n const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;\n const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';\n const end = start + count;\n const pointsCount = points.length;\n let prevParsed = start > 0 && this.getParsed(start - 1);\n\n for (let i = 0; i < pointsCount; ++i) {\n const point = points[i];\n const properties = directUpdate ? point : {};\n\n if (i < start || i >= end) {\n properties.skip = true;\n continue;\n }\n\n const parsed = this.getParsed(i);\n const nullData = isNullOrUndef(parsed[vAxis]);\n const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);\n const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;\n properties.stop = i > 0 && (Math.abs(parsed[iAxis] - prevParsed[iAxis])) > maxGapLength;\n if (segment) {\n properties.parsed = parsed;\n properties.raw = _dataset.data[i];\n }\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n }\n\n if (!directUpdate) {\n this.updateElement(point, i, properties, mode);\n }\n\n prevParsed = parsed;\n }\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const meta = this._cachedMeta;\n const dataset = meta.dataset;\n const border = dataset.options && dataset.options.borderWidth || 0;\n const data = meta.data || [];\n if (!data.length) {\n return border;\n }\n const firstPoint = data[0].size(this.resolveDataElementOptions(0));\n const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));\n return Math.max(border, firstPoint, lastPoint) / 2;\n }\n\n draw() {\n const meta = this._cachedMeta;\n meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);\n super.draw();\n }\n}\n","import DoughnutController from './controller.doughnut.js';\n\n// Pie charts are Doughnut chart with different defaults\nexport default class PieController extends DoughnutController {\n\n static id = 'pie';\n\n /**\n * @type {any}\n */\n static defaults = {\n // The percentage of the chart that we cut out of the middle.\n cutout: 0,\n\n // The rotation of the chart, where the first data arc begins.\n rotation: 0,\n\n // The total circumference of the chart.\n circumference: 360,\n\n // The outer radius of the chart\n radius: '100%'\n };\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {_parseObjectDataRadialScale} from '../helpers/index.js';\n\nexport default class RadarController extends DatasetController {\n\n static id = 'radar';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: 'line',\n dataElementType: 'point',\n indexAxis: 'r',\n showLine: true,\n elements: {\n line: {\n fill: 'start'\n }\n },\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n scales: {\n r: {\n type: 'radialLinear',\n }\n }\n };\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const vScale = this._cachedMeta.vScale;\n const parsed = this.getParsed(index);\n\n return {\n label: vScale.getLabels()[index],\n value: '' + vScale.getLabelForValue(parsed[vScale.axis])\n };\n }\n\n parseObjectData(meta, data, start, count) {\n return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const line = meta.dataset;\n const points = meta.data || [];\n const labels = meta.iScale.getLabels();\n\n // Update Line\n line.points = points;\n // In resize mode only point locations change, so no need to set the points or options.\n if (mode !== 'resize') {\n const options = this.resolveDatasetElementOptions(mode);\n if (!this.options.showLine) {\n options.borderWidth = 0;\n }\n\n const properties = {\n _loop: true,\n _fullLoop: labels.length === points.length,\n options\n };\n\n this.updateElement(line, undefined, properties, mode);\n }\n\n // Update Points\n this.updateElements(points, 0, points.length, mode);\n }\n\n updateElements(points, start, count, mode) {\n const scale = this._cachedMeta.rScale;\n const reset = mode === 'reset';\n\n for (let i = start; i < start + count; i++) {\n const point = points[i];\n const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r);\n\n const x = reset ? scale.xCenter : pointPosition.x;\n const y = reset ? scale.yCenter : pointPosition.y;\n\n const properties = {\n x,\n y,\n angle: pointPosition.angle,\n skip: isNaN(x) || isNaN(y),\n options\n };\n\n this.updateElement(point, i, properties, mode);\n }\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isNullOrUndef} from '../helpers/index.js';\nimport {isNumber} from '../helpers/helpers.math.js';\nimport {_getStartAndCountOfVisiblePoints, _scaleRangesChanged} from '../helpers/helpers.extras.js';\n\nexport default class ScatterController extends DatasetController {\n\n static id = 'scatter';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'point',\n showLine: false,\n fill: false\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n\n interaction: {\n mode: 'point'\n },\n\n scales: {\n x: {\n type: 'linear'\n },\n y: {\n type: 'linear'\n }\n }\n };\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const labels = this.chart.data.labels || [];\n const {xScale, yScale} = meta;\n const parsed = this.getParsed(index);\n const x = xScale.getLabelForValue(parsed.x);\n const y = yScale.getLabelForValue(parsed.y);\n\n return {\n label: labels[index] || '',\n value: '(' + x + ', ' + y + ')'\n };\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const {data: points = []} = meta;\n // @ts-ignore\n const animationsDisabled = this.chart._animationsDisabled;\n let {start, count} = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);\n\n this._drawStart = start;\n this._drawCount = count;\n\n if (_scaleRangesChanged(meta)) {\n start = 0;\n count = points.length;\n }\n\n if (this.options.showLine) {\n\n // https://github.com/chartjs/Chart.js/issues/11333\n if (!this.datasetElementType) {\n this.addElements();\n }\n const {dataset: line, _dataset} = meta;\n\n // Update Line\n line._chart = this.chart;\n line._datasetIndex = this.index;\n line._decimated = !!_dataset._decimated;\n line.points = points;\n\n const options = this.resolveDatasetElementOptions(mode);\n options.segment = this.options.segment;\n this.updateElement(line, undefined, {\n animated: !animationsDisabled,\n options\n }, mode);\n } else if (this.datasetElementType) {\n // https://github.com/chartjs/Chart.js/issues/11333\n delete meta.dataset;\n this.datasetElementType = false;\n }\n\n // Update Points\n this.updateElements(points, start, count, mode);\n }\n\n addElements() {\n const {showLine} = this.options;\n\n if (!this.datasetElementType && showLine) {\n this.datasetElementType = this.chart.registry.getElement('line');\n }\n\n super.addElements();\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale, _stacked, _dataset} = this._cachedMeta;\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const {spanGaps, segment} = this.options;\n const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;\n const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';\n let prevParsed = start > 0 && this.getParsed(start - 1);\n\n for (let i = start; i < start + count; ++i) {\n const point = points[i];\n const parsed = this.getParsed(i);\n const properties = directUpdate ? point : {};\n const nullData = isNullOrUndef(parsed[vAxis]);\n const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);\n const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;\n properties.stop = i > 0 && (Math.abs(parsed[iAxis] - prevParsed[iAxis])) > maxGapLength;\n if (segment) {\n properties.parsed = parsed;\n properties.raw = _dataset.data[i];\n }\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n }\n\n if (!directUpdate) {\n this.updateElement(point, i, properties, mode);\n }\n\n prevParsed = parsed;\n }\n\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const meta = this._cachedMeta;\n const data = meta.data || [];\n\n if (!this.options.showLine) {\n let max = 0;\n for (let i = data.length - 1; i >= 0; --i) {\n max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);\n }\n return max > 0 && max;\n }\n\n const dataset = meta.dataset;\n const border = dataset.options && dataset.options.borderWidth || 0;\n\n if (!data.length) {\n return border;\n }\n\n const firstPoint = data[0].size(this.resolveDataElementOptions(0));\n const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));\n return Math.max(border, firstPoint, lastPoint) / 2;\n }\n}\n","import Element from '../core/core.element.js';\nimport {_angleBetween, getAngleFromPoint, TAU, HALF_PI, valueOrDefault} from '../helpers/index.js';\nimport {PI, _isBetween, _limitValue} from '../helpers/helpers.math.js';\nimport {_readValueToProps} from '../helpers/helpers.options.js';\nimport type {ArcOptions, Point} from '../types/index.js';\n\n\nfunction clipArc(ctx: CanvasRenderingContext2D, element: ArcElement, endAngle: number) {\n const {startAngle, pixelMargin, x, y, outerRadius, innerRadius} = element;\n let angleMargin = pixelMargin / outerRadius;\n\n // Draw an inner border by clipping the arc and drawing a double-width border\n // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders\n ctx.beginPath();\n ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);\n if (innerRadius > pixelMargin) {\n angleMargin = pixelMargin / innerRadius;\n ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);\n } else {\n ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI);\n }\n ctx.closePath();\n ctx.clip();\n}\n\nfunction toRadiusCorners(value) {\n return _readValueToProps(value, ['outerStart', 'outerEnd', 'innerStart', 'innerEnd']);\n}\n\n/**\n * Parse border radius from the provided options\n */\nfunction parseBorderRadius(arc: ArcElement, innerRadius: number, outerRadius: number, angleDelta: number) {\n const o = toRadiusCorners(arc.options.borderRadius);\n const halfThickness = (outerRadius - innerRadius) / 2;\n const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);\n\n // Outer limits are complicated. We want to compute the available angular distance at\n // a radius of outerRadius - borderRadius because for small angular distances, this term limits.\n // We compute at r = outerRadius - borderRadius because this circle defines the center of the border corners.\n //\n // If the borderRadius is large, that value can become negative.\n // This causes the outer borders to lose their radius entirely, which is rather unexpected. To solve that, if borderRadius > outerRadius\n // we know that the thickness term will dominate and compute the limits at that point\n const computeOuterLimit = (val) => {\n const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;\n return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit));\n };\n\n return {\n outerStart: computeOuterLimit(o.outerStart),\n outerEnd: computeOuterLimit(o.outerEnd),\n innerStart: _limitValue(o.innerStart, 0, innerLimit),\n innerEnd: _limitValue(o.innerEnd, 0, innerLimit),\n };\n}\n\n/**\n * Convert (r, 𝜃) to (x, y)\n */\nfunction rThetaToXY(r: number, theta: number, x: number, y: number) {\n return {\n x: x + r * Math.cos(theta),\n y: y + r * Math.sin(theta),\n };\n}\n\n\n/**\n * Path the arc, respecting border radius by separating into left and right halves.\n *\n * Start End\n *\n * 1--->a--->2 Outer\n * / \\\n * 8 3\n * | |\n * | |\n * 7 4\n * \\ /\n * 6<---b<---5 Inner\n */\nfunction pathArc(\n ctx: CanvasRenderingContext2D,\n element: ArcElement,\n offset: number,\n spacing: number,\n end: number,\n circular: boolean,\n) {\n const {x, y, startAngle: start, pixelMargin, innerRadius: innerR} = element;\n\n const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0);\n const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0;\n\n let spacingOffset = 0;\n const alpha = end - start;\n\n if (spacing) {\n // When spacing is present, it is the same for all items\n // So we adjust the start and end angle of the arc such that\n // the distance is the same as it would be without the spacing\n const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;\n const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;\n const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;\n const adjustedAngle = avNogSpacingRadius !== 0 ? (alpha * avNogSpacingRadius) / (avNogSpacingRadius + spacing) : alpha;\n spacingOffset = (alpha - adjustedAngle) / 2;\n }\n\n const beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius;\n const angleOffset = (alpha - beta) / 2;\n const startAngle = start + angleOffset + spacingOffset;\n const endAngle = end - angleOffset - spacingOffset;\n const {outerStart, outerEnd, innerStart, innerEnd} = parseBorderRadius(element, innerRadius, outerRadius, endAngle - startAngle);\n\n const outerStartAdjustedRadius = outerRadius - outerStart;\n const outerEndAdjustedRadius = outerRadius - outerEnd;\n const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;\n const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;\n\n const innerStartAdjustedRadius = innerRadius + innerStart;\n const innerEndAdjustedRadius = innerRadius + innerEnd;\n const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;\n const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;\n\n ctx.beginPath();\n\n if (circular) {\n // The first arc segments from point 1 to point a to point 2\n const outerMidAdjustedAngle = (outerStartAdjustedAngle + outerEndAdjustedAngle) / 2;\n ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerMidAdjustedAngle);\n ctx.arc(x, y, outerRadius, outerMidAdjustedAngle, outerEndAdjustedAngle);\n\n // The corner segment from point 2 to point 3\n if (outerEnd > 0) {\n const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);\n }\n\n // The line from point 3 to point 4\n const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);\n ctx.lineTo(p4.x, p4.y);\n\n // The corner segment from point 4 to point 5\n if (innerEnd > 0) {\n const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);\n }\n\n // The inner arc from point 5 to point b to point 6\n const innerMidAdjustedAngle = ((endAngle - (innerEnd / innerRadius)) + (startAngle + (innerStart / innerRadius))) / 2;\n ctx.arc(x, y, innerRadius, endAngle - (innerEnd / innerRadius), innerMidAdjustedAngle, true);\n ctx.arc(x, y, innerRadius, innerMidAdjustedAngle, startAngle + (innerStart / innerRadius), true);\n\n // The corner segment from point 6 to point 7\n if (innerStart > 0) {\n const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);\n }\n\n // The line from point 7 to point 8\n const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);\n ctx.lineTo(p8.x, p8.y);\n\n // The corner segment from point 8 to point 1\n if (outerStart > 0) {\n const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);\n }\n } else {\n ctx.moveTo(x, y);\n\n const outerStartX = Math.cos(outerStartAdjustedAngle) * outerRadius + x;\n const outerStartY = Math.sin(outerStartAdjustedAngle) * outerRadius + y;\n ctx.lineTo(outerStartX, outerStartY);\n\n const outerEndX = Math.cos(outerEndAdjustedAngle) * outerRadius + x;\n const outerEndY = Math.sin(outerEndAdjustedAngle) * outerRadius + y;\n ctx.lineTo(outerEndX, outerEndY);\n }\n\n ctx.closePath();\n}\n\nfunction drawArc(\n ctx: CanvasRenderingContext2D,\n element: ArcElement,\n offset: number,\n spacing: number,\n circular: boolean,\n) {\n const {fullCircles, startAngle, circumference} = element;\n let endAngle = element.endAngle;\n if (fullCircles) {\n pathArc(ctx, element, offset, spacing, endAngle, circular);\n for (let i = 0; i < fullCircles; ++i) {\n ctx.fill();\n }\n if (!isNaN(circumference)) {\n endAngle = startAngle + (circumference % TAU || TAU);\n }\n }\n pathArc(ctx, element, offset, spacing, endAngle, circular);\n ctx.fill();\n return endAngle;\n}\n\nfunction drawBorder(\n ctx: CanvasRenderingContext2D,\n element: ArcElement,\n offset: number,\n spacing: number,\n circular: boolean,\n) {\n const {fullCircles, startAngle, circumference, options} = element;\n const {borderWidth, borderJoinStyle, borderDash, borderDashOffset} = options;\n const inner = options.borderAlign === 'inner';\n\n if (!borderWidth) {\n return;\n }\n\n ctx.setLineDash(borderDash || []);\n ctx.lineDashOffset = borderDashOffset;\n\n if (inner) {\n ctx.lineWidth = borderWidth * 2;\n ctx.lineJoin = borderJoinStyle || 'round';\n } else {\n ctx.lineWidth = borderWidth;\n ctx.lineJoin = borderJoinStyle || 'bevel';\n }\n\n let endAngle = element.endAngle;\n if (fullCircles) {\n pathArc(ctx, element, offset, spacing, endAngle, circular);\n for (let i = 0; i < fullCircles; ++i) {\n ctx.stroke();\n }\n if (!isNaN(circumference)) {\n endAngle = startAngle + (circumference % TAU || TAU);\n }\n }\n\n if (inner) {\n clipArc(ctx, element, endAngle);\n }\n\n if (!fullCircles) {\n pathArc(ctx, element, offset, spacing, endAngle, circular);\n ctx.stroke();\n }\n}\n\nexport interface ArcProps extends Point {\n startAngle: number;\n endAngle: number;\n innerRadius: number;\n outerRadius: number;\n circumference: number;\n}\n\nexport default class ArcElement extends Element {\n\n static id = 'arc';\n\n static defaults = {\n borderAlign: 'center',\n borderColor: '#fff',\n borderDash: [],\n borderDashOffset: 0,\n borderJoinStyle: undefined,\n borderRadius: 0,\n borderWidth: 2,\n offset: 0,\n spacing: 0,\n angle: undefined,\n circular: true,\n };\n\n static defaultRoutes = {\n backgroundColor: 'backgroundColor'\n };\n\n static descriptors = {\n _scriptable: true,\n _indexable: (name) => name !== 'borderDash'\n };\n\n circumference: number;\n endAngle: number;\n fullCircles: number;\n innerRadius: number;\n outerRadius: number;\n pixelMargin: number;\n startAngle: number;\n\n constructor(cfg) {\n super();\n\n this.options = undefined;\n this.circumference = undefined;\n this.startAngle = undefined;\n this.endAngle = undefined;\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n this.pixelMargin = 0;\n this.fullCircles = 0;\n\n if (cfg) {\n Object.assign(this, cfg);\n }\n }\n\n inRange(chartX: number, chartY: number, useFinalPosition: boolean) {\n const point = this.getProps(['x', 'y'], useFinalPosition);\n const {angle, distance} = getAngleFromPoint(point, {x: chartX, y: chartY});\n const {startAngle, endAngle, innerRadius, outerRadius, circumference} = this.getProps([\n 'startAngle',\n 'endAngle',\n 'innerRadius',\n 'outerRadius',\n 'circumference'\n ], useFinalPosition);\n const rAdjust = (this.options.spacing + this.options.borderWidth) / 2;\n const _circumference = valueOrDefault(circumference, endAngle - startAngle);\n const betweenAngles = _circumference >= TAU || _angleBetween(angle, startAngle, endAngle);\n const withinRadius = _isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust);\n\n return (betweenAngles && withinRadius);\n }\n\n getCenterPoint(useFinalPosition: boolean) {\n const {x, y, startAngle, endAngle, innerRadius, outerRadius} = this.getProps([\n 'x',\n 'y',\n 'startAngle',\n 'endAngle',\n 'innerRadius',\n 'outerRadius'\n ], useFinalPosition);\n const {offset, spacing} = this.options;\n const halfAngle = (startAngle + endAngle) / 2;\n const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2;\n return {\n x: x + Math.cos(halfAngle) * halfRadius,\n y: y + Math.sin(halfAngle) * halfRadius\n };\n }\n\n tooltipPosition(useFinalPosition: boolean) {\n return this.getCenterPoint(useFinalPosition);\n }\n\n draw(ctx: CanvasRenderingContext2D) {\n const {options, circumference} = this;\n const offset = (options.offset || 0) / 4;\n const spacing = (options.spacing || 0) / 2;\n const circular = options.circular;\n this.pixelMargin = (options.borderAlign === 'inner') ? 0.33 : 0;\n this.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0;\n\n if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) {\n return;\n }\n\n ctx.save();\n\n const halfAngle = (this.startAngle + this.endAngle) / 2;\n ctx.translate(Math.cos(halfAngle) * offset, Math.sin(halfAngle) * offset);\n const fix = 1 - Math.sin(Math.min(PI, circumference || 0));\n const radiusOffset = offset * fix;\n\n ctx.fillStyle = options.backgroundColor;\n ctx.strokeStyle = options.borderColor;\n\n drawArc(ctx, this, radiusOffset, spacing, circular);\n drawBorder(ctx, this, radiusOffset, spacing, circular);\n\n ctx.restore();\n }\n}\n","import Element from '../core/core.element.js';\nimport {_bezierInterpolation, _pointInLine, _steppedInterpolation} from '../helpers/helpers.interpolation.js';\nimport {_computeSegments, _boundSegments} from '../helpers/helpers.segment.js';\nimport {_steppedLineTo, _bezierCurveTo} from '../helpers/helpers.canvas.js';\nimport {_updateBezierControlPoints} from '../helpers/helpers.curve.js';\nimport {valueOrDefault} from '../helpers/index.js';\n\n/**\n * @typedef { import('./element.point.js').default } PointElement\n */\n\nfunction setStyle(ctx, options, style = options) {\n ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle);\n ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash));\n ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset);\n ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);\n ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth);\n ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor);\n}\n\nfunction lineTo(ctx, previous, target) {\n ctx.lineTo(target.x, target.y);\n}\n\n/**\n * @returns {any}\n */\nfunction getLineMethod(options) {\n if (options.stepped) {\n return _steppedLineTo;\n }\n\n if (options.tension || options.cubicInterpolationMode === 'monotone') {\n return _bezierCurveTo;\n }\n\n return lineTo;\n}\n\nfunction pathVars(points, segment, params = {}) {\n const count = points.length;\n const {start: paramsStart = 0, end: paramsEnd = count - 1} = params;\n const {start: segmentStart, end: segmentEnd} = segment;\n const start = Math.max(paramsStart, segmentStart);\n const end = Math.min(paramsEnd, segmentEnd);\n const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;\n\n return {\n count,\n start,\n loop: segment.loop,\n ilen: end < start && !outside ? count + end - start : end - start\n };\n}\n\n/**\n * Create path from points, grouping by truncated x-coordinate\n * Points need to be in order by x-coordinate for this to work efficiently\n * @param {CanvasRenderingContext2D|Path2D} ctx - Context\n * @param {LineElement} line\n * @param {object} segment\n * @param {number} segment.start - start index of the segment, referring the points array\n * @param {number} segment.end - end index of the segment, referring the points array\n * @param {boolean} segment.loop - indicates that the segment is a loop\n * @param {object} params\n * @param {boolean} params.move - move to starting point (vs line to it)\n * @param {boolean} params.reverse - path the segment from end to start\n * @param {number} params.start - limit segment to points starting from `start` index\n * @param {number} params.end - limit segment to points ending at `start` + `count` index\n */\nfunction pathSegment(ctx, line, segment, params) {\n const {points, options} = line;\n const {count, start, loop, ilen} = pathVars(points, segment, params);\n const lineMethod = getLineMethod(options);\n // eslint-disable-next-line prefer-const\n let {move = true, reverse} = params || {};\n let i, point, prev;\n\n for (i = 0; i <= ilen; ++i) {\n point = points[(start + (reverse ? ilen - i : i)) % count];\n\n if (point.skip) {\n // If there is a skipped point inside a segment, spanGaps must be true\n continue;\n } else if (move) {\n ctx.moveTo(point.x, point.y);\n move = false;\n } else {\n lineMethod(ctx, prev, point, reverse, options.stepped);\n }\n\n prev = point;\n }\n\n if (loop) {\n point = points[(start + (reverse ? ilen : 0)) % count];\n lineMethod(ctx, prev, point, reverse, options.stepped);\n }\n\n return !!loop;\n}\n\n/**\n * Create path from points, grouping by truncated x-coordinate\n * Points need to be in order by x-coordinate for this to work efficiently\n * @param {CanvasRenderingContext2D|Path2D} ctx - Context\n * @param {LineElement} line\n * @param {object} segment\n * @param {number} segment.start - start index of the segment, referring the points array\n * @param {number} segment.end - end index of the segment, referring the points array\n * @param {boolean} segment.loop - indicates that the segment is a loop\n * @param {object} params\n * @param {boolean} params.move - move to starting point (vs line to it)\n * @param {boolean} params.reverse - path the segment from end to start\n * @param {number} params.start - limit segment to points starting from `start` index\n * @param {number} params.end - limit segment to points ending at `start` + `count` index\n */\nfunction fastPathSegment(ctx, line, segment, params) {\n const points = line.points;\n const {count, start, ilen} = pathVars(points, segment, params);\n const {move = true, reverse} = params || {};\n let avgX = 0;\n let countX = 0;\n let i, point, prevX, minY, maxY, lastY;\n\n const pointIndex = (index) => (start + (reverse ? ilen - index : index)) % count;\n const drawX = () => {\n if (minY !== maxY) {\n // Draw line to maxY and minY, using the average x-coordinate\n ctx.lineTo(avgX, maxY);\n ctx.lineTo(avgX, minY);\n // Line to y-value of last point in group. So the line continues\n // from correct position. Not using move, to have solid path.\n ctx.lineTo(avgX, lastY);\n }\n };\n\n if (move) {\n point = points[pointIndex(0)];\n ctx.moveTo(point.x, point.y);\n }\n\n for (i = 0; i <= ilen; ++i) {\n point = points[pointIndex(i)];\n\n if (point.skip) {\n // If there is a skipped point inside a segment, spanGaps must be true\n continue;\n }\n\n const x = point.x;\n const y = point.y;\n const truncX = x | 0; // truncated x-coordinate\n\n if (truncX === prevX) {\n // Determine `minY` / `maxY` and `avgX` while we stay within same x-position\n if (y < minY) {\n minY = y;\n } else if (y > maxY) {\n maxY = y;\n }\n // For first point in group, countX is `0`, so average will be `x` / 1.\n avgX = (countX * avgX + x) / ++countX;\n } else {\n drawX();\n // Draw line to next x-position, using the first (or only)\n // y-value in that group\n ctx.lineTo(x, y);\n\n prevX = truncX;\n countX = 0;\n minY = maxY = y;\n }\n // Keep track of the last y-value in group\n lastY = y;\n }\n drawX();\n}\n\n/**\n * @param {LineElement} line - the line\n * @returns {function}\n * @private\n */\nfunction _getSegmentMethod(line) {\n const opts = line.options;\n const borderDash = opts.borderDash && opts.borderDash.length;\n const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;\n return useFastPath ? fastPathSegment : pathSegment;\n}\n\n/**\n * @private\n */\nfunction _getInterpolationMethod(options) {\n if (options.stepped) {\n return _steppedInterpolation;\n }\n\n if (options.tension || options.cubicInterpolationMode === 'monotone') {\n return _bezierInterpolation;\n }\n\n return _pointInLine;\n}\n\nfunction strokePathWithCache(ctx, line, start, count) {\n let path = line._path;\n if (!path) {\n path = line._path = new Path2D();\n if (line.path(path, start, count)) {\n path.closePath();\n }\n }\n setStyle(ctx, line.options);\n ctx.stroke(path);\n}\n\nfunction strokePathDirect(ctx, line, start, count) {\n const {segments, options} = line;\n const segmentMethod = _getSegmentMethod(line);\n\n for (const segment of segments) {\n setStyle(ctx, options, segment.style);\n ctx.beginPath();\n if (segmentMethod(ctx, line, segment, {start, end: start + count - 1})) {\n ctx.closePath();\n }\n ctx.stroke();\n }\n}\n\nconst usePath2D = typeof Path2D === 'function';\n\nfunction draw(ctx, line, start, count) {\n if (usePath2D && !line.options.segment) {\n strokePathWithCache(ctx, line, start, count);\n } else {\n strokePathDirect(ctx, line, start, count);\n }\n}\n\nexport default class LineElement extends Element {\n\n static id = 'line';\n\n /**\n * @type {any}\n */\n static defaults = {\n borderCapStyle: 'butt',\n borderDash: [],\n borderDashOffset: 0,\n borderJoinStyle: 'miter',\n borderWidth: 3,\n capBezierPoints: true,\n cubicInterpolationMode: 'default',\n fill: false,\n spanGaps: false,\n stepped: false,\n tension: 0,\n };\n\n /**\n * @type {any}\n */\n static defaultRoutes = {\n backgroundColor: 'backgroundColor',\n borderColor: 'borderColor'\n };\n\n\n static descriptors = {\n _scriptable: true,\n _indexable: (name) => name !== 'borderDash' && name !== 'fill',\n };\n\n\n constructor(cfg) {\n super();\n\n this.animated = true;\n this.options = undefined;\n this._chart = undefined;\n this._loop = undefined;\n this._fullLoop = undefined;\n this._path = undefined;\n this._points = undefined;\n this._segments = undefined;\n this._decimated = false;\n this._pointsUpdated = false;\n this._datasetIndex = undefined;\n\n if (cfg) {\n Object.assign(this, cfg);\n }\n }\n\n updateControlPoints(chartArea, indexAxis) {\n const options = this.options;\n if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) {\n const loop = options.spanGaps ? this._loop : this._fullLoop;\n _updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis);\n this._pointsUpdated = true;\n }\n }\n\n set points(points) {\n this._points = points;\n delete this._segments;\n delete this._path;\n this._pointsUpdated = false;\n }\n\n get points() {\n return this._points;\n }\n\n get segments() {\n return this._segments || (this._segments = _computeSegments(this, this.options.segment));\n }\n\n /**\n\t * First non-skipped point on this line\n\t * @returns {PointElement|undefined}\n\t */\n first() {\n const segments = this.segments;\n const points = this.points;\n return segments.length && points[segments[0].start];\n }\n\n /**\n\t * Last non-skipped point on this line\n\t * @returns {PointElement|undefined}\n\t */\n last() {\n const segments = this.segments;\n const points = this.points;\n const count = segments.length;\n return count && points[segments[count - 1].end];\n }\n\n /**\n\t * Interpolate a point in this line at the same value on `property` as\n\t * the reference `point` provided\n\t * @param {PointElement} point - the reference point\n\t * @param {string} property - the property to match on\n\t * @returns {PointElement|undefined}\n\t */\n interpolate(point, property) {\n const options = this.options;\n const value = point[property];\n const points = this.points;\n const segments = _boundSegments(this, {property, start: value, end: value});\n\n if (!segments.length) {\n return;\n }\n\n const result = [];\n const _interpolate = _getInterpolationMethod(options);\n let i, ilen;\n for (i = 0, ilen = segments.length; i < ilen; ++i) {\n const {start, end} = segments[i];\n const p1 = points[start];\n const p2 = points[end];\n if (p1 === p2) {\n result.push(p1);\n continue;\n }\n const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));\n const interpolated = _interpolate(p1, p2, t, options.stepped);\n interpolated[property] = point[property];\n result.push(interpolated);\n }\n return result.length === 1 ? result[0] : result;\n }\n\n /**\n\t * Append a segment of this line to current path.\n\t * @param {CanvasRenderingContext2D} ctx\n\t * @param {object} segment\n\t * @param {number} segment.start - start index of the segment, referring the points array\n \t * @param {number} segment.end - end index of the segment, referring the points array\n \t * @param {boolean} segment.loop - indicates that the segment is a loop\n\t * @param {object} params\n\t * @param {boolean} params.move - move to starting point (vs line to it)\n\t * @param {boolean} params.reverse - path the segment from end to start\n\t * @param {number} params.start - limit segment to points starting from `start` index\n\t * @param {number} params.end - limit segment to points ending at `start` + `count` index\n\t * @returns {undefined|boolean} - true if the segment is a full loop (path should be closed)\n\t */\n pathSegment(ctx, segment, params) {\n const segmentMethod = _getSegmentMethod(this);\n return segmentMethod(ctx, this, segment, params);\n }\n\n /**\n\t * Append all segments of this line to current path.\n\t * @param {CanvasRenderingContext2D|Path2D} ctx\n\t * @param {number} [start]\n\t * @param {number} [count]\n\t * @returns {undefined|boolean} - true if line is a full loop (path should be closed)\n\t */\n path(ctx, start, count) {\n const segments = this.segments;\n const segmentMethod = _getSegmentMethod(this);\n let loop = this._loop;\n\n start = start || 0;\n count = count || (this.points.length - start);\n\n for (const segment of segments) {\n loop &= segmentMethod(ctx, this, segment, {start, end: start + count - 1});\n }\n return !!loop;\n }\n\n /**\n\t * Draw\n\t * @param {CanvasRenderingContext2D} ctx\n\t * @param {object} chartArea\n\t * @param {number} [start]\n\t * @param {number} [count]\n\t */\n draw(ctx, chartArea, start, count) {\n const options = this.options || {};\n const points = this.points || [];\n\n if (points.length && options.borderWidth) {\n ctx.save();\n\n draw(ctx, this, start, count);\n\n ctx.restore();\n }\n\n if (this.animated) {\n // When line is animated, the control points and path are not cached.\n this._pointsUpdated = false;\n this._path = undefined;\n }\n }\n}\n","import Element from '../core/core.element.js';\nimport {drawPoint, _isPointInArea} from '../helpers/helpers.canvas.js';\nimport type {\n CartesianParsedData,\n ChartArea,\n Point,\n PointHoverOptions,\n PointOptions,\n} from '../types/index.js';\n\nfunction inRange(el: PointElement, pos: number, axis: 'x' | 'y', useFinalPosition?: boolean) {\n const options = el.options;\n const {[axis]: value} = el.getProps([axis], useFinalPosition);\n\n return (Math.abs(pos - value) < options.radius + options.hitRadius);\n}\n\nexport type PointProps = Point\n\nexport default class PointElement extends Element {\n\n static id = 'point';\n\n parsed: CartesianParsedData;\n skip?: boolean;\n stop?: boolean;\n\n /**\n * @type {any}\n */\n static defaults = {\n borderWidth: 1,\n hitRadius: 1,\n hoverBorderWidth: 1,\n hoverRadius: 4,\n pointStyle: 'circle',\n radius: 3,\n rotation: 0\n };\n\n /**\n * @type {any}\n */\n static defaultRoutes = {\n backgroundColor: 'backgroundColor',\n borderColor: 'borderColor'\n };\n\n constructor(cfg) {\n super();\n\n this.options = undefined;\n this.parsed = undefined;\n this.skip = undefined;\n this.stop = undefined;\n\n if (cfg) {\n Object.assign(this, cfg);\n }\n }\n\n inRange(mouseX: number, mouseY: number, useFinalPosition?: boolean) {\n const options = this.options;\n const {x, y} = this.getProps(['x', 'y'], useFinalPosition);\n return ((Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2)) < Math.pow(options.hitRadius + options.radius, 2));\n }\n\n inXRange(mouseX: number, useFinalPosition?: boolean) {\n return inRange(this, mouseX, 'x', useFinalPosition);\n }\n\n inYRange(mouseY: number, useFinalPosition?: boolean) {\n return inRange(this, mouseY, 'y', useFinalPosition);\n }\n\n getCenterPoint(useFinalPosition?: boolean) {\n const {x, y} = this.getProps(['x', 'y'], useFinalPosition);\n return {x, y};\n }\n\n size(options?: Partial) {\n options = options || this.options || {};\n let radius = options.radius || 0;\n radius = Math.max(radius, radius && options.hoverRadius || 0);\n const borderWidth = radius && options.borderWidth || 0;\n return (radius + borderWidth) * 2;\n }\n\n draw(ctx: CanvasRenderingContext2D, area: ChartArea) {\n const options = this.options;\n\n if (this.skip || options.radius < 0.1 || !_isPointInArea(this, area, this.size(options) / 2)) {\n return;\n }\n\n ctx.strokeStyle = options.borderColor;\n ctx.lineWidth = options.borderWidth;\n ctx.fillStyle = options.backgroundColor;\n drawPoint(ctx, options, this.x, this.y);\n }\n\n getRange() {\n const options = this.options || {};\n // @ts-expect-error Fallbacks should never be hit in practice\n return options.radius + options.hitRadius;\n }\n}\n","import Element from '../core/core.element.js';\nimport {isObject, _isBetween, _limitValue} from '../helpers/index.js';\nimport {addRoundedRectPath} from '../helpers/helpers.canvas.js';\nimport {toTRBL, toTRBLCorners} from '../helpers/helpers.options.js';\n\n/** @typedef {{ x: number, y: number, base: number, horizontal: boolean, width: number, height: number }} BarProps */\n\n/**\n * Helper function to get the bounds of the bar regardless of the orientation\n * @param {BarElement} bar the bar\n * @param {boolean} [useFinalPosition]\n * @return {object} bounds of the bar\n * @private\n */\nfunction getBarBounds(bar, useFinalPosition) {\n const {x, y, base, width, height} = /** @type {BarProps} */ (bar.getProps(['x', 'y', 'base', 'width', 'height'], useFinalPosition));\n\n let left, right, top, bottom, half;\n\n if (bar.horizontal) {\n half = height / 2;\n left = Math.min(x, base);\n right = Math.max(x, base);\n top = y - half;\n bottom = y + half;\n } else {\n half = width / 2;\n left = x - half;\n right = x + half;\n top = Math.min(y, base);\n bottom = Math.max(y, base);\n }\n\n return {left, top, right, bottom};\n}\n\nfunction skipOrLimit(skip, value, min, max) {\n return skip ? 0 : _limitValue(value, min, max);\n}\n\nfunction parseBorderWidth(bar, maxW, maxH) {\n const value = bar.options.borderWidth;\n const skip = bar.borderSkipped;\n const o = toTRBL(value);\n\n return {\n t: skipOrLimit(skip.top, o.top, 0, maxH),\n r: skipOrLimit(skip.right, o.right, 0, maxW),\n b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),\n l: skipOrLimit(skip.left, o.left, 0, maxW)\n };\n}\n\nfunction parseBorderRadius(bar, maxW, maxH) {\n const {enableBorderRadius} = bar.getProps(['enableBorderRadius']);\n const value = bar.options.borderRadius;\n const o = toTRBLCorners(value);\n const maxR = Math.min(maxW, maxH);\n const skip = bar.borderSkipped;\n\n // If the value is an object, assume the user knows what they are doing\n // and apply as directed.\n const enableBorder = enableBorderRadius || isObject(value);\n\n return {\n topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),\n topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),\n bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),\n bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)\n };\n}\n\nfunction boundingRects(bar) {\n const bounds = getBarBounds(bar);\n const width = bounds.right - bounds.left;\n const height = bounds.bottom - bounds.top;\n const border = parseBorderWidth(bar, width / 2, height / 2);\n const radius = parseBorderRadius(bar, width / 2, height / 2);\n\n return {\n outer: {\n x: bounds.left,\n y: bounds.top,\n w: width,\n h: height,\n radius\n },\n inner: {\n x: bounds.left + border.l,\n y: bounds.top + border.t,\n w: width - border.l - border.r,\n h: height - border.t - border.b,\n radius: {\n topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),\n topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),\n bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),\n bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r)),\n }\n }\n };\n}\n\nfunction inRange(bar, x, y, useFinalPosition) {\n const skipX = x === null;\n const skipY = y === null;\n const skipBoth = skipX && skipY;\n const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);\n\n return bounds\n\t\t&& (skipX || _isBetween(x, bounds.left, bounds.right))\n\t\t&& (skipY || _isBetween(y, bounds.top, bounds.bottom));\n}\n\nfunction hasRadius(radius) {\n return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;\n}\n\n/**\n * Add a path of a rectangle to the current sub-path\n * @param {CanvasRenderingContext2D} ctx Context\n * @param {*} rect Bounding rect\n */\nfunction addNormalRectPath(ctx, rect) {\n ctx.rect(rect.x, rect.y, rect.w, rect.h);\n}\n\nfunction inflateRect(rect, amount, refRect = {}) {\n const x = rect.x !== refRect.x ? -amount : 0;\n const y = rect.y !== refRect.y ? -amount : 0;\n const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x;\n const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y;\n return {\n x: rect.x + x,\n y: rect.y + y,\n w: rect.w + w,\n h: rect.h + h,\n radius: rect.radius\n };\n}\n\nexport default class BarElement extends Element {\n\n static id = 'bar';\n\n /**\n * @type {any}\n */\n static defaults = {\n borderSkipped: 'start',\n borderWidth: 0,\n borderRadius: 0,\n inflateAmount: 'auto',\n pointStyle: undefined\n };\n\n /**\n * @type {any}\n */\n static defaultRoutes = {\n backgroundColor: 'backgroundColor',\n borderColor: 'borderColor'\n };\n\n constructor(cfg) {\n super();\n\n this.options = undefined;\n this.horizontal = undefined;\n this.base = undefined;\n this.width = undefined;\n this.height = undefined;\n this.inflateAmount = undefined;\n\n if (cfg) {\n Object.assign(this, cfg);\n }\n }\n\n draw(ctx) {\n const {inflateAmount, options: {borderColor, backgroundColor}} = this;\n const {inner, outer} = boundingRects(this);\n const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath;\n\n ctx.save();\n\n if (outer.w !== inner.w || outer.h !== inner.h) {\n ctx.beginPath();\n addRectPath(ctx, inflateRect(outer, inflateAmount, inner));\n ctx.clip();\n addRectPath(ctx, inflateRect(inner, -inflateAmount, outer));\n ctx.fillStyle = borderColor;\n ctx.fill('evenodd');\n }\n\n ctx.beginPath();\n addRectPath(ctx, inflateRect(inner, inflateAmount));\n ctx.fillStyle = backgroundColor;\n ctx.fill();\n\n ctx.restore();\n }\n\n inRange(mouseX, mouseY, useFinalPosition) {\n return inRange(this, mouseX, mouseY, useFinalPosition);\n }\n\n inXRange(mouseX, useFinalPosition) {\n return inRange(this, mouseX, null, useFinalPosition);\n }\n\n inYRange(mouseY, useFinalPosition) {\n return inRange(this, null, mouseY, useFinalPosition);\n }\n\n getCenterPoint(useFinalPosition) {\n const {x, y, base, horizontal} = /** @type {BarProps} */ (this.getProps(['x', 'y', 'base', 'horizontal'], useFinalPosition));\n return {\n x: horizontal ? (x + base) / 2 : x,\n y: horizontal ? y : (y + base) / 2\n };\n }\n\n getRange(axis) {\n return axis === 'x' ? this.width / 2 : this.height / 2;\n }\n}\n","import Scale from '../core/core.scale.js';\nimport {isNullOrUndef, valueOrDefault, _limitValue} from '../helpers/index.js';\n\nconst addIfString = (labels, raw, index, addedLabels) => {\n if (typeof raw === 'string') {\n index = labels.push(raw) - 1;\n addedLabels.unshift({index, label: raw});\n } else if (isNaN(raw)) {\n index = null;\n }\n return index;\n};\n\nfunction findOrAddLabel(labels, raw, index, addedLabels) {\n const first = labels.indexOf(raw);\n if (first === -1) {\n return addIfString(labels, raw, index, addedLabels);\n }\n const last = labels.lastIndexOf(raw);\n return first !== last ? index : first;\n}\n\nconst validIndex = (index, max) => index === null ? null : _limitValue(Math.round(index), 0, max);\n\nfunction _getLabelForValue(value) {\n const labels = this.getLabels();\n\n if (value >= 0 && value < labels.length) {\n return labels[value];\n }\n return value;\n}\n\nexport default class CategoryScale extends Scale {\n\n static id = 'category';\n\n /**\n * @type {any}\n */\n static defaults = {\n ticks: {\n callback: _getLabelForValue\n }\n };\n\n constructor(cfg) {\n super(cfg);\n\n /** @type {number} */\n this._startValue = undefined;\n this._valueRange = 0;\n this._addedLabels = [];\n }\n\n init(scaleOptions) {\n const added = this._addedLabels;\n if (added.length) {\n const labels = this.getLabels();\n for (const {index, label} of added) {\n if (labels[index] === label) {\n labels.splice(index, 1);\n }\n }\n this._addedLabels = [];\n }\n super.init(scaleOptions);\n }\n\n parse(raw, index) {\n if (isNullOrUndef(raw)) {\n return null;\n }\n const labels = this.getLabels();\n index = isFinite(index) && labels[index] === raw ? index\n : findOrAddLabel(labels, raw, valueOrDefault(index, raw), this._addedLabels);\n return validIndex(index, labels.length - 1);\n }\n\n determineDataLimits() {\n const {minDefined, maxDefined} = this.getUserBounds();\n let {min, max} = this.getMinMax(true);\n\n if (this.options.bounds === 'ticks') {\n if (!minDefined) {\n min = 0;\n }\n if (!maxDefined) {\n max = this.getLabels().length - 1;\n }\n }\n\n this.min = min;\n this.max = max;\n }\n\n buildTicks() {\n const min = this.min;\n const max = this.max;\n const offset = this.options.offset;\n const ticks = [];\n let labels = this.getLabels();\n\n // If we are viewing some subset of labels, slice the original array\n labels = (min === 0 && max === labels.length - 1) ? labels : labels.slice(min, max + 1);\n\n this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);\n this._startValue = this.min - (offset ? 0.5 : 0);\n\n for (let value = min; value <= max; value++) {\n ticks.push({value});\n }\n return ticks;\n }\n\n getLabelForValue(value) {\n return _getLabelForValue.call(this, value);\n }\n\n /**\n\t * @protected\n\t */\n configure() {\n super.configure();\n\n if (!this.isHorizontal()) {\n // For backward compatibility, vertical category scale reverse is inverted.\n this._reversePixels = !this._reversePixels;\n }\n }\n\n // Used to get data value locations. Value can either be an index or a numerical value\n getPixelForValue(value) {\n if (typeof value !== 'number') {\n value = this.parse(value);\n }\n\n return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);\n }\n\n // Must override base implementation because it calls getPixelForValue\n // and category scale can have duplicate values\n getPixelForTick(index) {\n const ticks = this.ticks;\n if (index < 0 || index > ticks.length - 1) {\n return null;\n }\n return this.getPixelForValue(ticks[index].value);\n }\n\n getValueForPixel(pixel) {\n return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange);\n }\n\n getBasePixel() {\n return this.bottom;\n }\n}\n","import {isNullOrUndef} from '../helpers/helpers.core.js';\nimport {almostEquals, almostWhole, niceNum, _decimalPlaces, _setMinAndMaxByKey, sign, toRadians} from '../helpers/helpers.math.js';\nimport Scale from '../core/core.scale.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\n\n/**\n * Generate a set of linear ticks for an axis\n * 1. If generationOptions.min, generationOptions.max, and generationOptions.step are defined:\n * if (max - min) / step is an integer, ticks are generated as [min, min + step, ..., max]\n * Note that the generationOptions.maxCount setting is respected in this scenario\n *\n * 2. If generationOptions.min, generationOptions.max, and generationOptions.count is defined\n * spacing = (max - min) / count\n * Ticks are generated as [min, min + spacing, ..., max]\n *\n * 3. If generationOptions.count is defined\n * spacing = (niceMax - niceMin) / count\n *\n * 4. Compute optimal spacing of ticks using niceNum algorithm\n *\n * @param generationOptions the options used to generate the ticks\n * @param dataRange the range of the data\n * @returns {object[]} array of tick objects\n */\nfunction generateTicks(generationOptions, dataRange) {\n const ticks = [];\n // To get a \"nice\" value for the tick spacing, we will use the appropriately named\n // \"nice number\" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks\n // for details.\n\n const MIN_SPACING = 1e-14;\n const {bounds, step, min, max, precision, count, maxTicks, maxDigits, includeBounds} = generationOptions;\n const unit = step || 1;\n const maxSpaces = maxTicks - 1;\n const {min: rmin, max: rmax} = dataRange;\n const minDefined = !isNullOrUndef(min);\n const maxDefined = !isNullOrUndef(max);\n const countDefined = !isNullOrUndef(count);\n const minSpacing = (rmax - rmin) / (maxDigits + 1);\n let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit;\n let factor, niceMin, niceMax, numSpaces;\n\n // Beyond MIN_SPACING floating point numbers being to lose precision\n // such that we can't do the math necessary to generate ticks\n if (spacing < MIN_SPACING && !minDefined && !maxDefined) {\n return [{value: rmin}, {value: rmax}];\n }\n\n numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);\n if (numSpaces > maxSpaces) {\n // If the calculated num of spaces exceeds maxNumSpaces, recalculate it\n spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit;\n }\n\n if (!isNullOrUndef(precision)) {\n // If the user specified a precision, round to that number of decimal places\n factor = Math.pow(10, precision);\n spacing = Math.ceil(spacing * factor) / factor;\n }\n\n if (bounds === 'ticks') {\n niceMin = Math.floor(rmin / spacing) * spacing;\n niceMax = Math.ceil(rmax / spacing) * spacing;\n } else {\n niceMin = rmin;\n niceMax = rmax;\n }\n\n if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) {\n // Case 1: If min, max and stepSize are set and they make an evenly spaced scale use it.\n // spacing = step;\n // numSpaces = (max - min) / spacing;\n // Note that we round here to handle the case where almostWhole translated an FP error\n numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks));\n spacing = (max - min) / numSpaces;\n niceMin = min;\n niceMax = max;\n } else if (countDefined) {\n // Cases 2 & 3, we have a count specified. Handle optional user defined edges to the range.\n // Sometimes these are no-ops, but it makes the code a lot clearer\n // and when a user defined range is specified, we want the correct ticks\n niceMin = minDefined ? min : niceMin;\n niceMax = maxDefined ? max : niceMax;\n numSpaces = count - 1;\n spacing = (niceMax - niceMin) / numSpaces;\n } else {\n // Case 4\n numSpaces = (niceMax - niceMin) / spacing;\n\n // If very close to our rounded value, use it.\n if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {\n numSpaces = Math.round(numSpaces);\n } else {\n numSpaces = Math.ceil(numSpaces);\n }\n }\n\n // The spacing will have changed in cases 1, 2, and 3 so the factor cannot be computed\n // until this point\n const decimalPlaces = Math.max(\n _decimalPlaces(spacing),\n _decimalPlaces(niceMin)\n );\n factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision);\n niceMin = Math.round(niceMin * factor) / factor;\n niceMax = Math.round(niceMax * factor) / factor;\n\n let j = 0;\n if (minDefined) {\n if (includeBounds && niceMin !== min) {\n ticks.push({value: min});\n\n if (niceMin < min) {\n j++; // Skip niceMin\n }\n // If the next nice tick is close to min, skip it\n if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) {\n j++;\n }\n } else if (niceMin < min) {\n j++;\n }\n }\n\n for (; j < numSpaces; ++j) {\n const tickValue = Math.round((niceMin + j * spacing) * factor) / factor;\n if (maxDefined && tickValue > max) {\n break;\n }\n ticks.push({value: tickValue});\n }\n\n if (maxDefined && includeBounds && niceMax !== max) {\n // If the previous tick is too close to max, replace it with max, else add max\n if (ticks.length && almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) {\n ticks[ticks.length - 1].value = max;\n } else {\n ticks.push({value: max});\n }\n } else if (!maxDefined || niceMax === max) {\n ticks.push({value: niceMax});\n }\n\n return ticks;\n}\n\nfunction relativeLabelSize(value, minSpacing, {horizontal, minRotation}) {\n const rad = toRadians(minRotation);\n const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001;\n const length = 0.75 * minSpacing * ('' + value).length;\n return Math.min(minSpacing / ratio, length);\n}\n\nexport default class LinearScaleBase extends Scale {\n\n constructor(cfg) {\n super(cfg);\n\n /** @type {number} */\n this.start = undefined;\n /** @type {number} */\n this.end = undefined;\n /** @type {number} */\n this._startValue = undefined;\n /** @type {number} */\n this._endValue = undefined;\n this._valueRange = 0;\n }\n\n parse(raw, index) { // eslint-disable-line no-unused-vars\n if (isNullOrUndef(raw)) {\n return null;\n }\n if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {\n return null;\n }\n\n return +raw;\n }\n\n handleTickRangeOptions() {\n const {beginAtZero} = this.options;\n const {minDefined, maxDefined} = this.getUserBounds();\n let {min, max} = this;\n\n const setMin = v => (min = minDefined ? min : v);\n const setMax = v => (max = maxDefined ? max : v);\n\n if (beginAtZero) {\n const minSign = sign(min);\n const maxSign = sign(max);\n\n if (minSign < 0 && maxSign < 0) {\n setMax(0);\n } else if (minSign > 0 && maxSign > 0) {\n setMin(0);\n }\n }\n\n if (min === max) {\n let offset = max === 0 ? 1 : Math.abs(max * 0.05);\n\n setMax(max + offset);\n\n if (!beginAtZero) {\n setMin(min - offset);\n }\n }\n this.min = min;\n this.max = max;\n }\n\n getTickLimit() {\n const tickOpts = this.options.ticks;\n // eslint-disable-next-line prefer-const\n let {maxTicksLimit, stepSize} = tickOpts;\n let maxTicks;\n\n if (stepSize) {\n maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1;\n if (maxTicks > 1000) {\n console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`);\n maxTicks = 1000;\n }\n } else {\n maxTicks = this.computeTickLimit();\n maxTicksLimit = maxTicksLimit || 11;\n }\n\n if (maxTicksLimit) {\n maxTicks = Math.min(maxTicksLimit, maxTicks);\n }\n\n return maxTicks;\n }\n\n /**\n\t * @protected\n\t */\n computeTickLimit() {\n return Number.POSITIVE_INFINITY;\n }\n\n buildTicks() {\n const opts = this.options;\n const tickOpts = opts.ticks;\n\n // Figure out what the max number of ticks we can support it is based on the size of\n // the axis area. For now, we say that the minimum tick spacing in pixels must be 40\n // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on\n // the graph. Make sure we always have at least 2 ticks\n let maxTicks = this.getTickLimit();\n maxTicks = Math.max(2, maxTicks);\n\n const numericGeneratorOptions = {\n maxTicks,\n bounds: opts.bounds,\n min: opts.min,\n max: opts.max,\n precision: tickOpts.precision,\n step: tickOpts.stepSize,\n count: tickOpts.count,\n maxDigits: this._maxDigits(),\n horizontal: this.isHorizontal(),\n minRotation: tickOpts.minRotation || 0,\n includeBounds: tickOpts.includeBounds !== false\n };\n const dataRange = this._range || this;\n const ticks = generateTicks(numericGeneratorOptions, dataRange);\n\n // At this point, we need to update our max and min given the tick values,\n // since we probably have expanded the range of the scale\n if (opts.bounds === 'ticks') {\n _setMinAndMaxByKey(ticks, this, 'value');\n }\n\n if (opts.reverse) {\n ticks.reverse();\n\n this.start = this.max;\n this.end = this.min;\n } else {\n this.start = this.min;\n this.end = this.max;\n }\n\n return ticks;\n }\n\n /**\n\t * @protected\n\t */\n configure() {\n const ticks = this.ticks;\n let start = this.min;\n let end = this.max;\n\n super.configure();\n\n if (this.options.offset && ticks.length) {\n const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;\n start -= offset;\n end += offset;\n }\n this._startValue = start;\n this._endValue = end;\n this._valueRange = end - start;\n }\n\n getLabelForValue(value) {\n return formatNumber(value, this.chart.options.locale, this.options.ticks.format);\n }\n}\n","import {isFinite} from '../helpers/helpers.core.js';\nimport LinearScaleBase from './scale.linearbase.js';\nimport Ticks from '../core/core.ticks.js';\nimport {toRadians} from '../helpers/index.js';\n\nexport default class LinearScale extends LinearScaleBase {\n\n static id = 'linear';\n\n /**\n * @type {any}\n */\n static defaults = {\n ticks: {\n callback: Ticks.formatters.numeric\n }\n };\n\n\n determineDataLimits() {\n const {min, max} = this.getMinMax(true);\n\n this.min = isFinite(min) ? min : 0;\n this.max = isFinite(max) ? max : 1;\n\n // Common base implementation to handle min, max, beginAtZero\n this.handleTickRangeOptions();\n }\n\n /**\n\t * Returns the maximum number of ticks based on the scale dimension\n\t * @protected\n \t */\n computeTickLimit() {\n const horizontal = this.isHorizontal();\n const length = horizontal ? this.width : this.height;\n const minRotation = toRadians(this.options.ticks.minRotation);\n const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001;\n const tickFont = this._resolveTickFontOptions(0);\n return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio));\n }\n\n // Utils\n getPixelForValue(value) {\n return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);\n }\n\n getValueForPixel(pixel) {\n return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;\n }\n}\n","import {finiteOrDefault, isFinite} from '../helpers/helpers.core.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\nimport {_setMinAndMaxByKey, log10} from '../helpers/helpers.math.js';\nimport Scale from '../core/core.scale.js';\nimport LinearScaleBase from './scale.linearbase.js';\nimport Ticks from '../core/core.ticks.js';\n\nconst log10Floor = v => Math.floor(log10(v));\nconst changeExponent = (v, m) => Math.pow(10, log10Floor(v) + m);\n\nfunction isMajor(tickVal) {\n const remain = tickVal / (Math.pow(10, log10Floor(tickVal)));\n return remain === 1;\n}\n\nfunction steps(min, max, rangeExp) {\n const rangeStep = Math.pow(10, rangeExp);\n const start = Math.floor(min / rangeStep);\n const end = Math.ceil(max / rangeStep);\n return end - start;\n}\n\nfunction startExp(min, max) {\n const range = max - min;\n let rangeExp = log10Floor(range);\n while (steps(min, max, rangeExp) > 10) {\n rangeExp++;\n }\n while (steps(min, max, rangeExp) < 10) {\n rangeExp--;\n }\n return Math.min(rangeExp, log10Floor(min));\n}\n\n\n/**\n * Generate a set of logarithmic ticks\n * @param generationOptions the options used to generate the ticks\n * @param dataRange the range of the data\n * @returns {object[]} array of tick objects\n */\nfunction generateTicks(generationOptions, {min, max}) {\n min = finiteOrDefault(generationOptions.min, min);\n const ticks = [];\n const minExp = log10Floor(min);\n let exp = startExp(min, max);\n let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;\n const stepSize = Math.pow(10, exp);\n const base = minExp > exp ? Math.pow(10, minExp) : 0;\n const start = Math.round((min - base) * precision) / precision;\n const offset = Math.floor((min - base) / stepSize / 10) * stepSize * 10;\n let significand = Math.floor((start - offset) / Math.pow(10, exp));\n let value = finiteOrDefault(generationOptions.min, Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision);\n while (value < max) {\n ticks.push({value, major: isMajor(value), significand});\n if (significand >= 10) {\n significand = significand < 15 ? 15 : 20;\n } else {\n significand++;\n }\n if (significand >= 20) {\n exp++;\n significand = 2;\n precision = exp >= 0 ? 1 : precision;\n }\n value = Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision;\n }\n const lastTick = finiteOrDefault(generationOptions.max, value);\n ticks.push({value: lastTick, major: isMajor(lastTick), significand});\n\n return ticks;\n}\n\nexport default class LogarithmicScale extends Scale {\n\n static id = 'logarithmic';\n\n /**\n * @type {any}\n */\n static defaults = {\n ticks: {\n callback: Ticks.formatters.logarithmic,\n major: {\n enabled: true\n }\n }\n };\n\n\n constructor(cfg) {\n super(cfg);\n\n /** @type {number} */\n this.start = undefined;\n /** @type {number} */\n this.end = undefined;\n /** @type {number} */\n this._startValue = undefined;\n this._valueRange = 0;\n }\n\n parse(raw, index) {\n const value = LinearScaleBase.prototype.parse.apply(this, [raw, index]);\n if (value === 0) {\n this._zero = true;\n return undefined;\n }\n return isFinite(value) && value > 0 ? value : null;\n }\n\n determineDataLimits() {\n const {min, max} = this.getMinMax(true);\n\n this.min = isFinite(min) ? Math.max(0, min) : null;\n this.max = isFinite(max) ? Math.max(0, max) : null;\n\n if (this.options.beginAtZero) {\n this._zero = true;\n }\n\n // if data has `0` in it or `beginAtZero` is true, min (non zero) value is at bottom\n // of scale, and it does not equal suggestedMin, lower the min bound by one exp.\n if (this._zero && this.min !== this._suggestedMin && !isFinite(this._userMin)) {\n this.min = min === changeExponent(this.min, 0) ? changeExponent(this.min, -1) : changeExponent(this.min, 0);\n }\n\n this.handleTickRangeOptions();\n }\n\n handleTickRangeOptions() {\n const {minDefined, maxDefined} = this.getUserBounds();\n let min = this.min;\n let max = this.max;\n\n const setMin = v => (min = minDefined ? min : v);\n const setMax = v => (max = maxDefined ? max : v);\n\n if (min === max) {\n if (min <= 0) { // includes null\n setMin(1);\n setMax(10);\n } else {\n setMin(changeExponent(min, -1));\n setMax(changeExponent(max, +1));\n }\n }\n if (min <= 0) {\n setMin(changeExponent(max, -1));\n }\n if (max <= 0) {\n\n setMax(changeExponent(min, +1));\n }\n\n this.min = min;\n this.max = max;\n }\n\n buildTicks() {\n const opts = this.options;\n\n const generationOptions = {\n min: this._userMin,\n max: this._userMax\n };\n const ticks = generateTicks(generationOptions, this);\n\n // At this point, we need to update our max and min given the tick values,\n // since we probably have expanded the range of the scale\n if (opts.bounds === 'ticks') {\n _setMinAndMaxByKey(ticks, this, 'value');\n }\n\n if (opts.reverse) {\n ticks.reverse();\n\n this.start = this.max;\n this.end = this.min;\n } else {\n this.start = this.min;\n this.end = this.max;\n }\n\n return ticks;\n }\n\n /**\n\t * @param {number} value\n\t * @return {string}\n\t */\n getLabelForValue(value) {\n return value === undefined\n ? '0'\n : formatNumber(value, this.chart.options.locale, this.options.ticks.format);\n }\n\n /**\n\t * @protected\n\t */\n configure() {\n const start = this.min;\n\n super.configure();\n\n this._startValue = log10(start);\n this._valueRange = log10(this.max) - log10(start);\n }\n\n getPixelForValue(value) {\n if (value === undefined || value === 0) {\n value = this.min;\n }\n if (value === null || isNaN(value)) {\n return NaN;\n }\n return this.getPixelForDecimal(value === this.min\n ? 0\n : (log10(value) - this._startValue) / this._valueRange);\n }\n\n getValueForPixel(pixel) {\n const decimal = this.getDecimalForPixel(pixel);\n return Math.pow(10, this._startValue + decimal * this._valueRange);\n }\n}\n","import defaults from '../core/core.defaults.js';\nimport {_longestText, addRoundedRectPath, renderText, _isPointInArea} from '../helpers/helpers.canvas.js';\nimport {HALF_PI, TAU, toDegrees, toRadians, _normalizeAngle, PI} from '../helpers/helpers.math.js';\nimport LinearScaleBase from './scale.linearbase.js';\nimport Ticks from '../core/core.ticks.js';\nimport {valueOrDefault, isArray, isFinite, callback as callCallback, isNullOrUndef} from '../helpers/helpers.core.js';\nimport {createContext, toFont, toPadding, toTRBLCorners} from '../helpers/helpers.options.js';\n\nfunction getTickBackdropHeight(opts) {\n const tickOpts = opts.ticks;\n\n if (tickOpts.display && opts.display) {\n const padding = toPadding(tickOpts.backdropPadding);\n return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height;\n }\n return 0;\n}\n\nfunction measureLabelSize(ctx, font, label) {\n label = isArray(label) ? label : [label];\n return {\n w: _longestText(ctx, font.string, label),\n h: label.length * font.lineHeight\n };\n}\n\nfunction determineLimits(angle, pos, size, min, max) {\n if (angle === min || angle === max) {\n return {\n start: pos - (size / 2),\n end: pos + (size / 2)\n };\n } else if (angle < min || angle > max) {\n return {\n start: pos - size,\n end: pos\n };\n }\n\n return {\n start: pos,\n end: pos + size\n };\n}\n\n/**\n * Helper function to fit a radial linear scale with point labels\n */\nfunction fitWithPointLabels(scale) {\n\n // Right, this is really confusing and there is a lot of maths going on here\n // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9\n //\n // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif\n //\n // Solution:\n //\n // We assume the radius of the polygon is half the size of the canvas at first\n // at each index we check if the text overlaps.\n //\n // Where it does, we store that angle and that index.\n //\n // After finding the largest index and angle we calculate how much we need to remove\n // from the shape radius to move the point inwards by that x.\n //\n // We average the left and right distances to get the maximum shape radius that can fit in the box\n // along with labels.\n //\n // Once we have that, we can find the centre point for the chart, by taking the x text protrusion\n // on each side, removing that from the size, halving it and adding the left x protrusion width.\n //\n // This will mean we have a shape fitted to the canvas, as large as it can be with the labels\n // and position it in the most space efficient manner\n //\n // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif\n\n // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.\n // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points\n const orig = {\n l: scale.left + scale._padding.left,\n r: scale.right - scale._padding.right,\n t: scale.top + scale._padding.top,\n b: scale.bottom - scale._padding.bottom\n };\n const limits = Object.assign({}, orig);\n const labelSizes = [];\n const padding = [];\n const valueCount = scale._pointLabels.length;\n const pointLabelOpts = scale.options.pointLabels;\n const additionalAngle = pointLabelOpts.centerPointLabels ? PI / valueCount : 0;\n\n for (let i = 0; i < valueCount; i++) {\n const opts = pointLabelOpts.setContext(scale.getPointLabelContext(i));\n padding[i] = opts.padding;\n const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle);\n const plFont = toFont(opts.font);\n const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]);\n labelSizes[i] = textSize;\n\n const angleRadians = _normalizeAngle(scale.getIndexAngle(i) + additionalAngle);\n const angle = Math.round(toDegrees(angleRadians));\n const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);\n const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);\n updateLimits(limits, orig, angleRadians, hLimits, vLimits);\n }\n\n scale.setCenterPoint(\n orig.l - limits.l,\n limits.r - orig.r,\n orig.t - limits.t,\n limits.b - orig.b\n );\n\n // Now that text size is determined, compute the full positions\n scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding);\n}\n\nfunction updateLimits(limits, orig, angle, hLimits, vLimits) {\n const sin = Math.abs(Math.sin(angle));\n const cos = Math.abs(Math.cos(angle));\n let x = 0;\n let y = 0;\n if (hLimits.start < orig.l) {\n x = (orig.l - hLimits.start) / sin;\n limits.l = Math.min(limits.l, orig.l - x);\n } else if (hLimits.end > orig.r) {\n x = (hLimits.end - orig.r) / sin;\n limits.r = Math.max(limits.r, orig.r + x);\n }\n if (vLimits.start < orig.t) {\n y = (orig.t - vLimits.start) / cos;\n limits.t = Math.min(limits.t, orig.t - y);\n } else if (vLimits.end > orig.b) {\n y = (vLimits.end - orig.b) / cos;\n limits.b = Math.max(limits.b, orig.b + y);\n }\n}\n\nfunction createPointLabelItem(scale, index, itemOpts) {\n const outerDistance = scale.drawingArea;\n const {extra, additionalAngle, padding, size} = itemOpts;\n const pointLabelPosition = scale.getPointPosition(index, outerDistance + extra + padding, additionalAngle);\n const angle = Math.round(toDegrees(_normalizeAngle(pointLabelPosition.angle + HALF_PI)));\n const y = yForAngle(pointLabelPosition.y, size.h, angle);\n const textAlign = getTextAlignForAngle(angle);\n const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign);\n return {\n // if to draw or overlapped\n visible: true,\n\n // Text position\n x: pointLabelPosition.x,\n y,\n\n // Text rendering data\n textAlign,\n\n // Bounding box\n left,\n top: y,\n right: left + size.w,\n bottom: y + size.h\n };\n}\n\nfunction isNotOverlapped(item, area) {\n if (!area) {\n return true;\n }\n const {left, top, right, bottom} = item;\n const apexesInArea = _isPointInArea({x: left, y: top}, area) || _isPointInArea({x: left, y: bottom}, area) ||\n _isPointInArea({x: right, y: top}, area) || _isPointInArea({x: right, y: bottom}, area);\n return !apexesInArea;\n}\n\nfunction buildPointLabelItems(scale, labelSizes, padding) {\n const items = [];\n const valueCount = scale._pointLabels.length;\n const opts = scale.options;\n const {centerPointLabels, display} = opts.pointLabels;\n const itemOpts = {\n extra: getTickBackdropHeight(opts) / 2,\n additionalAngle: centerPointLabels ? PI / valueCount : 0\n };\n let area;\n\n for (let i = 0; i < valueCount; i++) {\n itemOpts.padding = padding[i];\n itemOpts.size = labelSizes[i];\n\n const item = createPointLabelItem(scale, i, itemOpts);\n items.push(item);\n if (display === 'auto') {\n item.visible = isNotOverlapped(item, area);\n if (item.visible) {\n area = item;\n }\n }\n }\n return items;\n}\n\nfunction getTextAlignForAngle(angle) {\n if (angle === 0 || angle === 180) {\n return 'center';\n } else if (angle < 180) {\n return 'left';\n }\n\n return 'right';\n}\n\nfunction leftForTextAlign(x, w, align) {\n if (align === 'right') {\n x -= w;\n } else if (align === 'center') {\n x -= (w / 2);\n }\n return x;\n}\n\nfunction yForAngle(y, h, angle) {\n if (angle === 90 || angle === 270) {\n y -= (h / 2);\n } else if (angle > 270 || angle < 90) {\n y -= h;\n }\n return y;\n}\n\nfunction drawPointLabelBox(ctx, opts, item) {\n const {left, top, right, bottom} = item;\n const {backdropColor} = opts;\n\n if (!isNullOrUndef(backdropColor)) {\n const borderRadius = toTRBLCorners(opts.borderRadius);\n const padding = toPadding(opts.backdropPadding);\n ctx.fillStyle = backdropColor;\n\n const backdropLeft = left - padding.left;\n const backdropTop = top - padding.top;\n const backdropWidth = right - left + padding.width;\n const backdropHeight = bottom - top + padding.height;\n\n if (Object.values(borderRadius).some(v => v !== 0)) {\n ctx.beginPath();\n addRoundedRectPath(ctx, {\n x: backdropLeft,\n y: backdropTop,\n w: backdropWidth,\n h: backdropHeight,\n radius: borderRadius,\n });\n ctx.fill();\n } else {\n ctx.fillRect(backdropLeft, backdropTop, backdropWidth, backdropHeight);\n }\n }\n}\n\nfunction drawPointLabels(scale, labelCount) {\n const {ctx, options: {pointLabels}} = scale;\n\n for (let i = labelCount - 1; i >= 0; i--) {\n const item = scale._pointLabelItems[i];\n if (!item.visible) {\n // overlapping\n continue;\n }\n const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i));\n drawPointLabelBox(ctx, optsAtIndex, item);\n const plFont = toFont(optsAtIndex.font);\n const {x, y, textAlign} = item;\n\n renderText(\n ctx,\n scale._pointLabels[i],\n x,\n y + (plFont.lineHeight / 2),\n plFont,\n {\n color: optsAtIndex.color,\n textAlign: textAlign,\n textBaseline: 'middle'\n }\n );\n }\n}\n\nfunction pathRadiusLine(scale, radius, circular, labelCount) {\n const {ctx} = scale;\n if (circular) {\n // Draw circular arcs between the points\n ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU);\n } else {\n // Draw straight lines connecting each index\n let pointPosition = scale.getPointPosition(0, radius);\n ctx.moveTo(pointPosition.x, pointPosition.y);\n\n for (let i = 1; i < labelCount; i++) {\n pointPosition = scale.getPointPosition(i, radius);\n ctx.lineTo(pointPosition.x, pointPosition.y);\n }\n }\n}\n\nfunction drawRadiusLine(scale, gridLineOpts, radius, labelCount, borderOpts) {\n const ctx = scale.ctx;\n const circular = gridLineOpts.circular;\n\n const {color, lineWidth} = gridLineOpts;\n\n if ((!circular && !labelCount) || !color || !lineWidth || radius < 0) {\n return;\n }\n\n ctx.save();\n ctx.strokeStyle = color;\n ctx.lineWidth = lineWidth;\n ctx.setLineDash(borderOpts.dash);\n ctx.lineDashOffset = borderOpts.dashOffset;\n\n ctx.beginPath();\n pathRadiusLine(scale, radius, circular, labelCount);\n ctx.closePath();\n ctx.stroke();\n ctx.restore();\n}\n\nfunction createPointLabelContext(parent, index, label) {\n return createContext(parent, {\n label,\n index,\n type: 'pointLabel'\n });\n}\n\nexport default class RadialLinearScale extends LinearScaleBase {\n\n static id = 'radialLinear';\n\n /**\n * @type {any}\n */\n static defaults = {\n display: true,\n\n // Boolean - Whether to animate scaling the chart from the centre\n animate: true,\n position: 'chartArea',\n\n angleLines: {\n display: true,\n lineWidth: 1,\n borderDash: [],\n borderDashOffset: 0.0\n },\n\n grid: {\n circular: false\n },\n\n startAngle: 0,\n\n // label settings\n ticks: {\n // Boolean - Show a backdrop to the scale label\n showLabelBackdrop: true,\n\n callback: Ticks.formatters.numeric\n },\n\n pointLabels: {\n backdropColor: undefined,\n\n // Number - The backdrop padding above & below the label in pixels\n backdropPadding: 2,\n\n // Boolean - if true, show point labels\n display: true,\n\n // Number - Point label font size in pixels\n font: {\n size: 10\n },\n\n // Function - Used to convert point labels\n callback(label) {\n return label;\n },\n\n // Number - Additionl padding between scale and pointLabel\n padding: 5,\n\n // Boolean - if true, center point labels to slices in polar chart\n centerPointLabels: false\n }\n };\n\n static defaultRoutes = {\n 'angleLines.color': 'borderColor',\n 'pointLabels.color': 'color',\n 'ticks.color': 'color'\n };\n\n static descriptors = {\n angleLines: {\n _fallback: 'grid'\n }\n };\n\n constructor(cfg) {\n super(cfg);\n\n /** @type {number} */\n this.xCenter = undefined;\n /** @type {number} */\n this.yCenter = undefined;\n /** @type {number} */\n this.drawingArea = undefined;\n /** @type {string[]} */\n this._pointLabels = [];\n this._pointLabelItems = [];\n }\n\n setDimensions() {\n // Set the unconstrained dimension before label rotation\n const padding = this._padding = toPadding(getTickBackdropHeight(this.options) / 2);\n const w = this.width = this.maxWidth - padding.width;\n const h = this.height = this.maxHeight - padding.height;\n this.xCenter = Math.floor(this.left + w / 2 + padding.left);\n this.yCenter = Math.floor(this.top + h / 2 + padding.top);\n this.drawingArea = Math.floor(Math.min(w, h) / 2);\n }\n\n determineDataLimits() {\n const {min, max} = this.getMinMax(false);\n\n this.min = isFinite(min) && !isNaN(min) ? min : 0;\n this.max = isFinite(max) && !isNaN(max) ? max : 0;\n\n // Common base implementation to handle min, max, beginAtZero\n this.handleTickRangeOptions();\n }\n\n /**\n\t * Returns the maximum number of ticks based on the scale dimension\n\t * @protected\n\t */\n computeTickLimit() {\n return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));\n }\n\n generateTickLabels(ticks) {\n LinearScaleBase.prototype.generateTickLabels.call(this, ticks);\n\n // Point labels\n this._pointLabels = this.getLabels()\n .map((value, index) => {\n const label = callCallback(this.options.pointLabels.callback, [value, index], this);\n return label || label === 0 ? label : '';\n })\n .filter((v, i) => this.chart.getDataVisibility(i));\n }\n\n fit() {\n const opts = this.options;\n\n if (opts.display && opts.pointLabels.display) {\n fitWithPointLabels(this);\n } else {\n this.setCenterPoint(0, 0, 0, 0);\n }\n }\n\n setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {\n this.xCenter += Math.floor((leftMovement - rightMovement) / 2);\n this.yCenter += Math.floor((topMovement - bottomMovement) / 2);\n this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement));\n }\n\n getIndexAngle(index) {\n const angleMultiplier = TAU / (this._pointLabels.length || 1);\n const startAngle = this.options.startAngle || 0;\n\n return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));\n }\n\n getDistanceFromCenterForValue(value) {\n if (isNullOrUndef(value)) {\n return NaN;\n }\n\n // Take into account half font size + the yPadding of the top value\n const scalingFactor = this.drawingArea / (this.max - this.min);\n if (this.options.reverse) {\n return (this.max - value) * scalingFactor;\n }\n return (value - this.min) * scalingFactor;\n }\n\n getValueForDistanceFromCenter(distance) {\n if (isNullOrUndef(distance)) {\n return NaN;\n }\n\n const scaledDistance = distance / (this.drawingArea / (this.max - this.min));\n return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance;\n }\n\n getPointLabelContext(index) {\n const pointLabels = this._pointLabels || [];\n\n if (index >= 0 && index < pointLabels.length) {\n const pointLabel = pointLabels[index];\n return createPointLabelContext(this.getContext(), index, pointLabel);\n }\n }\n\n getPointPosition(index, distanceFromCenter, additionalAngle = 0) {\n const angle = this.getIndexAngle(index) - HALF_PI + additionalAngle;\n return {\n x: Math.cos(angle) * distanceFromCenter + this.xCenter,\n y: Math.sin(angle) * distanceFromCenter + this.yCenter,\n angle\n };\n }\n\n getPointPositionForValue(index, value) {\n return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));\n }\n\n getBasePosition(index) {\n return this.getPointPositionForValue(index || 0, this.getBaseValue());\n }\n\n getPointLabelPosition(index) {\n const {left, top, right, bottom} = this._pointLabelItems[index];\n return {\n left,\n top,\n right,\n bottom,\n };\n }\n\n /**\n\t * @protected\n\t */\n drawBackground() {\n const {backgroundColor, grid: {circular}} = this.options;\n if (backgroundColor) {\n const ctx = this.ctx;\n ctx.save();\n ctx.beginPath();\n pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length);\n ctx.closePath();\n ctx.fillStyle = backgroundColor;\n ctx.fill();\n ctx.restore();\n }\n }\n\n /**\n\t * @protected\n\t */\n drawGrid() {\n const ctx = this.ctx;\n const opts = this.options;\n const {angleLines, grid, border} = opts;\n const labelCount = this._pointLabels.length;\n\n let i, offset, position;\n\n if (opts.pointLabels.display) {\n drawPointLabels(this, labelCount);\n }\n\n if (grid.display) {\n this.ticks.forEach((tick, index) => {\n if (index !== 0) {\n offset = this.getDistanceFromCenterForValue(tick.value);\n const context = this.getContext(index);\n const optsAtIndex = grid.setContext(context);\n const optsAtIndexBorder = border.setContext(context);\n\n drawRadiusLine(this, optsAtIndex, offset, labelCount, optsAtIndexBorder);\n }\n });\n }\n\n if (angleLines.display) {\n ctx.save();\n\n for (i = labelCount - 1; i >= 0; i--) {\n const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i));\n const {color, lineWidth} = optsAtIndex;\n\n if (!lineWidth || !color) {\n continue;\n }\n\n ctx.lineWidth = lineWidth;\n ctx.strokeStyle = color;\n\n ctx.setLineDash(optsAtIndex.borderDash);\n ctx.lineDashOffset = optsAtIndex.borderDashOffset;\n\n offset = this.getDistanceFromCenterForValue(opts.ticks.reverse ? this.min : this.max);\n position = this.getPointPosition(i, offset);\n ctx.beginPath();\n ctx.moveTo(this.xCenter, this.yCenter);\n ctx.lineTo(position.x, position.y);\n ctx.stroke();\n }\n\n ctx.restore();\n }\n }\n\n /**\n\t * @protected\n\t */\n drawBorder() {}\n\n /**\n\t * @protected\n\t */\n drawLabels() {\n const ctx = this.ctx;\n const opts = this.options;\n const tickOpts = opts.ticks;\n\n if (!tickOpts.display) {\n return;\n }\n\n const startAngle = this.getIndexAngle(0);\n let offset, width;\n\n ctx.save();\n ctx.translate(this.xCenter, this.yCenter);\n ctx.rotate(startAngle);\n ctx.textAlign = 'center';\n ctx.textBaseline = 'middle';\n\n this.ticks.forEach((tick, index) => {\n if (index === 0 && !opts.reverse) {\n return;\n }\n\n const optsAtIndex = tickOpts.setContext(this.getContext(index));\n const tickFont = toFont(optsAtIndex.font);\n offset = this.getDistanceFromCenterForValue(this.ticks[index].value);\n\n if (optsAtIndex.showLabelBackdrop) {\n ctx.font = tickFont.string;\n width = ctx.measureText(tick.label).width;\n ctx.fillStyle = optsAtIndex.backdropColor;\n\n const padding = toPadding(optsAtIndex.backdropPadding);\n ctx.fillRect(\n -width / 2 - padding.left,\n -offset - tickFont.size / 2 - padding.top,\n width + padding.width,\n tickFont.size + padding.height\n );\n }\n\n renderText(ctx, tick.label, 0, -offset, tickFont, {\n color: optsAtIndex.color,\n strokeColor: optsAtIndex.textStrokeColor,\n strokeWidth: optsAtIndex.textStrokeWidth,\n });\n });\n\n ctx.restore();\n }\n\n /**\n\t * @protected\n\t */\n drawTitle() {}\n}\n","import adapters from '../core/core.adapters.js';\nimport {callback as call, isFinite, isNullOrUndef, mergeIf, valueOrDefault} from '../helpers/helpers.core.js';\nimport {toRadians, isNumber, _limitValue} from '../helpers/helpers.math.js';\nimport Scale from '../core/core.scale.js';\nimport {_arrayUnique, _filterBetween, _lookup} from '../helpers/helpers.collection.js';\n\n/**\n * @typedef { import('../core/core.adapters.js').TimeUnit } Unit\n * @typedef {{common: boolean, size: number, steps?: number}} Interval\n * @typedef { import('../core/core.adapters.js').DateAdapter } DateAdapter\n */\n\n/**\n * @type {Object}\n */\nconst INTERVALS = {\n millisecond: {common: true, size: 1, steps: 1000},\n second: {common: true, size: 1000, steps: 60},\n minute: {common: true, size: 60000, steps: 60},\n hour: {common: true, size: 3600000, steps: 24},\n day: {common: true, size: 86400000, steps: 30},\n week: {common: false, size: 604800000, steps: 4},\n month: {common: true, size: 2.628e9, steps: 12},\n quarter: {common: false, size: 7.884e9, steps: 4},\n year: {common: true, size: 3.154e10}\n};\n\n/**\n * @type {Unit[]}\n */\nconst UNITS = /** @type Unit[] */ /* #__PURE__ */ (Object.keys(INTERVALS));\n\n/**\n * @param {number} a\n * @param {number} b\n */\nfunction sorter(a, b) {\n return a - b;\n}\n\n/**\n * @param {TimeScale} scale\n * @param {*} input\n * @return {number}\n */\nfunction parse(scale, input) {\n if (isNullOrUndef(input)) {\n return null;\n }\n\n const adapter = scale._adapter;\n const {parser, round, isoWeekday} = scale._parseOpts;\n let value = input;\n\n if (typeof parser === 'function') {\n value = parser(value);\n }\n\n // Only parse if it's not a timestamp already\n if (!isFinite(value)) {\n value = typeof parser === 'string'\n ? adapter.parse(value, /** @type {Unit} */ (parser))\n : adapter.parse(value);\n }\n\n if (value === null) {\n return null;\n }\n\n if (round) {\n value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true)\n ? adapter.startOf(value, 'isoWeek', isoWeekday)\n : adapter.startOf(value, round);\n }\n\n return +value;\n}\n\n/**\n * Figures out what unit results in an appropriate number of auto-generated ticks\n * @param {Unit} minUnit\n * @param {number} min\n * @param {number} max\n * @param {number} capacity\n * @return {object}\n */\nfunction determineUnitForAutoTicks(minUnit, min, max, capacity) {\n const ilen = UNITS.length;\n\n for (let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {\n const interval = INTERVALS[UNITS[i]];\n const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;\n\n if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {\n return UNITS[i];\n }\n }\n\n return UNITS[ilen - 1];\n}\n\n/**\n * Figures out what unit to format a set of ticks with\n * @param {TimeScale} scale\n * @param {number} numTicks\n * @param {Unit} minUnit\n * @param {number} min\n * @param {number} max\n * @return {Unit}\n */\nfunction determineUnitForFormatting(scale, numTicks, minUnit, min, max) {\n for (let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {\n const unit = UNITS[i];\n if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {\n return unit;\n }\n }\n\n return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];\n}\n\n/**\n * @param {Unit} unit\n * @return {object}\n */\nfunction determineMajorUnit(unit) {\n for (let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {\n if (INTERVALS[UNITS[i]].common) {\n return UNITS[i];\n }\n }\n}\n\n/**\n * @param {object} ticks\n * @param {number} time\n * @param {number[]} [timestamps] - if defined, snap to these timestamps\n */\nfunction addTick(ticks, time, timestamps) {\n if (!timestamps) {\n ticks[time] = true;\n } else if (timestamps.length) {\n const {lo, hi} = _lookup(timestamps, time);\n const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];\n ticks[timestamp] = true;\n }\n}\n\n/**\n * @param {TimeScale} scale\n * @param {object[]} ticks\n * @param {object} map\n * @param {Unit} majorUnit\n * @return {object[]}\n */\nfunction setMajorTicks(scale, ticks, map, majorUnit) {\n const adapter = scale._adapter;\n const first = +adapter.startOf(ticks[0].value, majorUnit);\n const last = ticks[ticks.length - 1].value;\n let major, index;\n\n for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {\n index = map[major];\n if (index >= 0) {\n ticks[index].major = true;\n }\n }\n return ticks;\n}\n\n/**\n * @param {TimeScale} scale\n * @param {number[]} values\n * @param {Unit|undefined} [majorUnit]\n * @return {object[]}\n */\nfunction ticksFromTimestamps(scale, values, majorUnit) {\n const ticks = [];\n /** @type {Object} */\n const map = {};\n const ilen = values.length;\n let i, value;\n\n for (i = 0; i < ilen; ++i) {\n value = values[i];\n map[value] = i;\n\n ticks.push({\n value,\n major: false\n });\n }\n\n // We set the major ticks separately from the above loop because calling startOf for every tick\n // is expensive when there is a large number of ticks\n return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);\n}\n\nexport default class TimeScale extends Scale {\n\n static id = 'time';\n\n /**\n * @type {any}\n */\n static defaults = {\n /**\n * Scale boundary strategy (bypassed by min/max time options)\n * - `data`: make sure data are fully visible, ticks outside are removed\n * - `ticks`: make sure ticks are fully visible, data outside are truncated\n * @see https://github.com/chartjs/Chart.js/pull/4556\n * @since 2.7.0\n */\n bounds: 'data',\n\n adapters: {},\n time: {\n parser: false, // false == a pattern string from or a custom callback that converts its argument to a timestamp\n unit: false, // false == automatic or override with week, month, year, etc.\n round: false, // none, or override with week, month, year, etc.\n isoWeekday: false, // override week start day\n minUnit: 'millisecond',\n displayFormats: {}\n },\n ticks: {\n /**\n * Ticks generation input values:\n * - 'auto': generates \"optimal\" ticks based on scale size and time options.\n * - 'data': generates ticks from data (including labels from data {t|x|y} objects).\n * - 'labels': generates ticks from user given `data.labels` values ONLY.\n * @see https://github.com/chartjs/Chart.js/pull/4507\n * @since 2.7.0\n */\n source: 'auto',\n\n callback: false,\n\n major: {\n enabled: false\n }\n }\n };\n\n /**\n\t * @param {object} props\n\t */\n constructor(props) {\n super(props);\n\n /** @type {{data: number[], labels: number[], all: number[]}} */\n this._cache = {\n data: [],\n labels: [],\n all: []\n };\n\n /** @type {Unit} */\n this._unit = 'day';\n /** @type {Unit=} */\n this._majorUnit = undefined;\n this._offsets = {};\n this._normalized = false;\n this._parseOpts = undefined;\n }\n\n init(scaleOpts, opts = {}) {\n const time = scaleOpts.time || (scaleOpts.time = {});\n /** @type {DateAdapter} */\n const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);\n\n adapter.init(opts);\n\n // Backward compatibility: before introducing adapter, `displayFormats` was\n // supposed to contain *all* unit/string pairs but this can't be resolved\n // when loading the scale (adapters are loaded afterward), so let's populate\n // missing formats on update\n mergeIf(time.displayFormats, adapter.formats());\n\n this._parseOpts = {\n parser: time.parser,\n round: time.round,\n isoWeekday: time.isoWeekday\n };\n\n super.init(scaleOpts);\n\n this._normalized = opts.normalized;\n }\n\n /**\n\t * @param {*} raw\n\t * @param {number?} [index]\n\t * @return {number}\n\t */\n parse(raw, index) { // eslint-disable-line no-unused-vars\n if (raw === undefined) {\n return null;\n }\n return parse(this, raw);\n }\n\n beforeLayout() {\n super.beforeLayout();\n this._cache = {\n data: [],\n labels: [],\n all: []\n };\n }\n\n determineDataLimits() {\n const options = this.options;\n const adapter = this._adapter;\n const unit = options.time.unit || 'day';\n // eslint-disable-next-line prefer-const\n let {min, max, minDefined, maxDefined} = this.getUserBounds();\n\n /**\n\t\t * @param {object} bounds\n\t\t */\n function _applyBounds(bounds) {\n if (!minDefined && !isNaN(bounds.min)) {\n min = Math.min(min, bounds.min);\n }\n if (!maxDefined && !isNaN(bounds.max)) {\n max = Math.max(max, bounds.max);\n }\n }\n\n // If we have user provided `min` and `max` labels / data bounds can be ignored\n if (!minDefined || !maxDefined) {\n // Labels are always considered, when user did not force bounds\n _applyBounds(this._getLabelBounds());\n\n // If `bounds` is `'ticks'` and `ticks.source` is `'labels'`,\n // data bounds are ignored (and don't need to be determined)\n if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {\n _applyBounds(this.getMinMax(false));\n }\n }\n\n min = isFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);\n max = isFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;\n\n // Make sure that max is strictly higher than min (required by the timeseries lookup table)\n this.min = Math.min(min, max - 1);\n this.max = Math.max(min + 1, max);\n }\n\n /**\n\t * @private\n\t */\n _getLabelBounds() {\n const arr = this.getLabelTimestamps();\n let min = Number.POSITIVE_INFINITY;\n let max = Number.NEGATIVE_INFINITY;\n\n if (arr.length) {\n min = arr[0];\n max = arr[arr.length - 1];\n }\n return {min, max};\n }\n\n /**\n\t * @return {object[]}\n\t */\n buildTicks() {\n const options = this.options;\n const timeOpts = options.time;\n const tickOpts = options.ticks;\n const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate();\n\n if (options.bounds === 'ticks' && timestamps.length) {\n this.min = this._userMin || timestamps[0];\n this.max = this._userMax || timestamps[timestamps.length - 1];\n }\n\n const min = this.min;\n const max = this.max;\n\n const ticks = _filterBetween(timestamps, min, max);\n\n // PRIVATE\n // determineUnitForFormatting relies on the number of ticks so we don't use it when\n // autoSkip is enabled because we don't yet know what the final number of ticks will be\n this._unit = timeOpts.unit || (tickOpts.autoSkip\n ? determineUnitForAutoTicks(timeOpts.minUnit, this.min, this.max, this._getLabelCapacity(min))\n : determineUnitForFormatting(this, ticks.length, timeOpts.minUnit, this.min, this.max));\n this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined\n : determineMajorUnit(this._unit);\n this.initOffsets(timestamps);\n\n if (options.reverse) {\n ticks.reverse();\n }\n\n return ticksFromTimestamps(this, ticks, this._majorUnit);\n }\n\n afterAutoSkip() {\n // Offsets for bar charts need to be handled with the auto skipped\n // ticks. Once ticks have been skipped, we re-compute the offsets.\n if (this.options.offsetAfterAutoskip) {\n this.initOffsets(this.ticks.map(tick => +tick.value));\n }\n }\n\n /**\n\t * Returns the start and end offsets from edges in the form of {start, end}\n\t * where each value is a relative width to the scale and ranges between 0 and 1.\n\t * They add extra margins on the both sides by scaling down the original scale.\n\t * Offsets are added when the `offset` option is true.\n\t * @param {number[]} timestamps\n\t * @protected\n\t */\n initOffsets(timestamps = []) {\n let start = 0;\n let end = 0;\n let first, last;\n\n if (this.options.offset && timestamps.length) {\n first = this.getDecimalForValue(timestamps[0]);\n if (timestamps.length === 1) {\n start = 1 - first;\n } else {\n start = (this.getDecimalForValue(timestamps[1]) - first) / 2;\n }\n last = this.getDecimalForValue(timestamps[timestamps.length - 1]);\n if (timestamps.length === 1) {\n end = last;\n } else {\n end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;\n }\n }\n const limit = timestamps.length < 3 ? 0.5 : 0.25;\n start = _limitValue(start, 0, limit);\n end = _limitValue(end, 0, limit);\n\n this._offsets = {start, end, factor: 1 / (start + 1 + end)};\n }\n\n /**\n\t * Generates a maximum of `capacity` timestamps between min and max, rounded to the\n\t * `minor` unit using the given scale time `options`.\n\t * Important: this method can return ticks outside the min and max range, it's the\n\t * responsibility of the calling code to clamp values if needed.\n\t * @protected\n\t */\n _generate() {\n const adapter = this._adapter;\n const min = this.min;\n const max = this.max;\n const options = this.options;\n const timeOpts = options.time;\n // @ts-ignore\n const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min));\n const stepSize = valueOrDefault(options.ticks.stepSize, 1);\n const weekday = minor === 'week' ? timeOpts.isoWeekday : false;\n const hasWeekday = isNumber(weekday) || weekday === true;\n const ticks = {};\n let first = min;\n let time, count;\n\n // For 'week' unit, handle the first day of week option\n if (hasWeekday) {\n first = +adapter.startOf(first, 'isoWeek', weekday);\n }\n\n // Align first ticks on unit\n first = +adapter.startOf(first, hasWeekday ? 'day' : minor);\n\n // Prevent browser from freezing in case user options request millions of milliseconds\n if (adapter.diff(max, min, minor) > 100000 * stepSize) {\n throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);\n }\n\n const timestamps = options.ticks.source === 'data' && this.getDataTimestamps();\n for (time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++) {\n addTick(ticks, time, timestamps);\n }\n\n if (time === max || options.bounds === 'ticks' || count === 1) {\n addTick(ticks, time, timestamps);\n }\n\n // @ts-ignore\n return Object.keys(ticks).sort(sorter).map(x => +x);\n }\n\n /**\n\t * @param {number} value\n\t * @return {string}\n\t */\n getLabelForValue(value) {\n const adapter = this._adapter;\n const timeOpts = this.options.time;\n\n if (timeOpts.tooltipFormat) {\n return adapter.format(value, timeOpts.tooltipFormat);\n }\n return adapter.format(value, timeOpts.displayFormats.datetime);\n }\n\n /**\n\t * @param {number} value\n\t * @param {string|undefined} format\n\t * @return {string}\n\t */\n format(value, format) {\n const options = this.options;\n const formats = options.time.displayFormats;\n const unit = this._unit;\n const fmt = format || formats[unit];\n return this._adapter.format(value, fmt);\n }\n\n /**\n\t * Function to format an individual tick mark\n\t * @param {number} time\n\t * @param {number} index\n\t * @param {object[]} ticks\n\t * @param {string|undefined} [format]\n\t * @return {string}\n\t * @private\n\t */\n _tickFormatFunction(time, index, ticks, format) {\n const options = this.options;\n const formatter = options.ticks.callback;\n\n if (formatter) {\n return call(formatter, [time, index, ticks], this);\n }\n\n const formats = options.time.displayFormats;\n const unit = this._unit;\n const majorUnit = this._majorUnit;\n const minorFormat = unit && formats[unit];\n const majorFormat = majorUnit && formats[majorUnit];\n const tick = ticks[index];\n const major = majorUnit && majorFormat && tick && tick.major;\n\n return this._adapter.format(time, format || (major ? majorFormat : minorFormat));\n }\n\n /**\n\t * @param {object[]} ticks\n\t */\n generateTickLabels(ticks) {\n let i, ilen, tick;\n\n for (i = 0, ilen = ticks.length; i < ilen; ++i) {\n tick = ticks[i];\n tick.label = this._tickFormatFunction(tick.value, i, ticks);\n }\n }\n\n /**\n\t * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC)\n\t * @return {number}\n\t */\n getDecimalForValue(value) {\n return value === null ? NaN : (value - this.min) / (this.max - this.min);\n }\n\n /**\n\t * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC)\n\t * @return {number}\n\t */\n getPixelForValue(value) {\n const offsets = this._offsets;\n const pos = this.getDecimalForValue(value);\n return this.getPixelForDecimal((offsets.start + pos) * offsets.factor);\n }\n\n /**\n\t * @param {number} pixel\n\t * @return {number}\n\t */\n getValueForPixel(pixel) {\n const offsets = this._offsets;\n const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;\n return this.min + pos * (this.max - this.min);\n }\n\n /**\n\t * @param {string} label\n\t * @return {{w:number, h:number}}\n\t * @private\n\t */\n _getLabelSize(label) {\n const ticksOpts = this.options.ticks;\n const tickLabelWidth = this.ctx.measureText(label).width;\n const angle = toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);\n const cosRotation = Math.cos(angle);\n const sinRotation = Math.sin(angle);\n const tickFontSize = this._resolveTickFontOptions(0).size;\n\n return {\n w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),\n h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)\n };\n }\n\n /**\n\t * @param {number} exampleTime\n\t * @return {number}\n\t * @private\n\t */\n _getLabelCapacity(exampleTime) {\n const timeOpts = this.options.time;\n const displayFormats = timeOpts.displayFormats;\n\n // pick the longest format (milliseconds) for guesstimation\n const format = displayFormats[timeOpts.unit] || displayFormats.millisecond;\n const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [exampleTime], this._majorUnit), format);\n const size = this._getLabelSize(exampleLabel);\n // subtract 1 - if offset then there's one less label than tick\n // if not offset then one half label padding is added to each end leaving room for one less label\n const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1;\n return capacity > 0 ? capacity : 1;\n }\n\n /**\n\t * @protected\n\t */\n getDataTimestamps() {\n let timestamps = this._cache.data || [];\n let i, ilen;\n\n if (timestamps.length) {\n return timestamps;\n }\n\n const metas = this.getMatchingVisibleMetas();\n\n if (this._normalized && metas.length) {\n return (this._cache.data = metas[0].controller.getAllParsedValues(this));\n }\n\n for (i = 0, ilen = metas.length; i < ilen; ++i) {\n timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this));\n }\n\n return (this._cache.data = this.normalize(timestamps));\n }\n\n /**\n\t * @protected\n\t */\n getLabelTimestamps() {\n const timestamps = this._cache.labels || [];\n let i, ilen;\n\n if (timestamps.length) {\n return timestamps;\n }\n\n const labels = this.getLabels();\n for (i = 0, ilen = labels.length; i < ilen; ++i) {\n timestamps.push(parse(this, labels[i]));\n }\n\n return (this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps));\n }\n\n /**\n\t * @param {number[]} values\n\t * @protected\n\t */\n normalize(values) {\n // It seems to be somewhat faster to do sorting first\n return _arrayUnique(values.sort(sorter));\n }\n}\n","import TimeScale from './scale.time.js';\nimport {_lookupByKey} from '../helpers/helpers.collection.js';\n\n/**\n * Linearly interpolates the given source `val` using the table. If value is out of bounds, values\n * at edges are used for the interpolation.\n * @param {object} table\n * @param {number} val\n * @param {boolean} [reverse] lookup time based on position instead of vice versa\n * @return {object}\n */\nfunction interpolate(table, val, reverse) {\n let lo = 0;\n let hi = table.length - 1;\n let prevSource, nextSource, prevTarget, nextTarget;\n if (reverse) {\n if (val >= table[lo].pos && val <= table[hi].pos) {\n ({lo, hi} = _lookupByKey(table, 'pos', val));\n }\n ({pos: prevSource, time: prevTarget} = table[lo]);\n ({pos: nextSource, time: nextTarget} = table[hi]);\n } else {\n if (val >= table[lo].time && val <= table[hi].time) {\n ({lo, hi} = _lookupByKey(table, 'time', val));\n }\n ({time: prevSource, pos: prevTarget} = table[lo]);\n ({time: nextSource, pos: nextTarget} = table[hi]);\n }\n\n const span = nextSource - prevSource;\n return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;\n}\n\nclass TimeSeriesScale extends TimeScale {\n\n static id = 'timeseries';\n\n /**\n * @type {any}\n */\n static defaults = TimeScale.defaults;\n\n /**\n\t * @param {object} props\n\t */\n constructor(props) {\n super(props);\n\n /** @type {object[]} */\n this._table = [];\n /** @type {number} */\n this._minPos = undefined;\n /** @type {number} */\n this._tableRange = undefined;\n }\n\n /**\n\t * @protected\n\t */\n initOffsets() {\n const timestamps = this._getTimestampsForTable();\n const table = this._table = this.buildLookupTable(timestamps);\n this._minPos = interpolate(table, this.min);\n this._tableRange = interpolate(table, this.max) - this._minPos;\n super.initOffsets(timestamps);\n }\n\n /**\n\t * Returns an array of {time, pos} objects used to interpolate a specific `time` or position\n\t * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is\n\t * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other\n\t * extremity (left + width or top + height). Note that it would be more optimized to directly\n\t * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need\n\t * to create the lookup table. The table ALWAYS contains at least two items: min and max.\n\t * @param {number[]} timestamps\n\t * @return {object[]}\n\t * @protected\n\t */\n buildLookupTable(timestamps) {\n const {min, max} = this;\n const items = [];\n const table = [];\n let i, ilen, prev, curr, next;\n\n for (i = 0, ilen = timestamps.length; i < ilen; ++i) {\n curr = timestamps[i];\n if (curr >= min && curr <= max) {\n items.push(curr);\n }\n }\n\n if (items.length < 2) {\n // In case there is less that 2 timestamps between min and max, the scale is defined by min and max\n return [\n {time: min, pos: 0},\n {time: max, pos: 1}\n ];\n }\n\n for (i = 0, ilen = items.length; i < ilen; ++i) {\n next = items[i + 1];\n prev = items[i - 1];\n curr = items[i];\n\n // only add points that breaks the scale linearity\n if (Math.round((next + prev) / 2) !== curr) {\n table.push({time: curr, pos: i / (ilen - 1)});\n }\n }\n return table;\n }\n\n /**\n * Generates all timestamps defined in the data.\n * Important: this method can return ticks outside the min and max range, it's the\n * responsibility of the calling code to clamp values if needed.\n * @protected\n */\n _generate() {\n const min = this.min;\n const max = this.max;\n let timestamps = super.getDataTimestamps();\n if (!timestamps.includes(min) || !timestamps.length) {\n timestamps.splice(0, 0, min);\n }\n if (!timestamps.includes(max) || timestamps.length === 1) {\n timestamps.push(max);\n }\n return timestamps.sort((a, b) => a - b);\n }\n\n /**\n\t * Returns all timestamps\n\t * @return {number[]}\n\t * @private\n\t */\n _getTimestampsForTable() {\n let timestamps = this._cache.all || [];\n\n if (timestamps.length) {\n return timestamps;\n }\n\n const data = this.getDataTimestamps();\n const label = this.getLabelTimestamps();\n if (data.length && label.length) {\n // If combining labels and data (data might not contain all labels),\n // we need to recheck uniqueness and sort\n timestamps = this.normalize(data.concat(label));\n } else {\n timestamps = data.length ? data : label;\n }\n timestamps = this._cache.all = timestamps;\n\n return timestamps;\n }\n\n /**\n\t * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC)\n\t * @return {number}\n\t */\n getDecimalForValue(value) {\n return (interpolate(this._table, value) - this._minPos) / this._tableRange;\n }\n\n /**\n\t * @param {number} pixel\n\t * @return {number}\n\t */\n getValueForPixel(pixel) {\n const offsets = this._offsets;\n const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;\n return interpolate(this._table, decimal * this._tableRange + this._minPos, true);\n }\n}\n\nexport default TimeSeriesScale;\n","import {DoughnutController, PolarAreaController} from '../index.js';\nimport type {Chart, ChartDataset} from '../types.js';\n\nexport interface ColorsPluginOptions {\n enabled?: boolean;\n forceOverride?: boolean;\n}\n\ninterface ColorsDescriptor {\n backgroundColor?: unknown;\n borderColor?: unknown;\n}\n\nconst BORDER_COLORS = [\n 'rgb(54, 162, 235)', // blue\n 'rgb(255, 99, 132)', // red\n 'rgb(255, 159, 64)', // orange\n 'rgb(255, 205, 86)', // yellow\n 'rgb(75, 192, 192)', // green\n 'rgb(153, 102, 255)', // purple\n 'rgb(201, 203, 207)' // grey\n];\n\n// Border colors with 50% transparency\nconst BACKGROUND_COLORS = /* #__PURE__ */ BORDER_COLORS.map(color => color.replace('rgb(', 'rgba(').replace(')', ', 0.5)'));\n\nfunction getBorderColor(i: number) {\n return BORDER_COLORS[i % BORDER_COLORS.length];\n}\n\nfunction getBackgroundColor(i: number) {\n return BACKGROUND_COLORS[i % BACKGROUND_COLORS.length];\n}\n\nfunction colorizeDefaultDataset(dataset: ChartDataset, i: number) {\n dataset.borderColor = getBorderColor(i);\n dataset.backgroundColor = getBackgroundColor(i);\n\n return ++i;\n}\n\nfunction colorizeDoughnutDataset(dataset: ChartDataset, i: number) {\n dataset.backgroundColor = dataset.data.map(() => getBorderColor(i++));\n\n return i;\n}\n\nfunction colorizePolarAreaDataset(dataset: ChartDataset, i: number) {\n dataset.backgroundColor = dataset.data.map(() => getBackgroundColor(i++));\n\n return i;\n}\n\nfunction getColorizer(chart: Chart) {\n let i = 0;\n\n return (dataset: ChartDataset, datasetIndex: number) => {\n const controller = chart.getDatasetMeta(datasetIndex).controller;\n\n if (controller instanceof DoughnutController) {\n i = colorizeDoughnutDataset(dataset, i);\n } else if (controller instanceof PolarAreaController) {\n i = colorizePolarAreaDataset(dataset, i);\n } else if (controller) {\n i = colorizeDefaultDataset(dataset, i);\n }\n };\n}\n\nfunction containsColorsDefinitions(\n descriptors: ColorsDescriptor[] | Record\n) {\n let k: number | string;\n\n for (k in descriptors) {\n if (descriptors[k].borderColor || descriptors[k].backgroundColor) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction containsColorsDefinition(\n descriptor: ColorsDescriptor\n) {\n return descriptor && (descriptor.borderColor || descriptor.backgroundColor);\n}\n\nexport default {\n id: 'colors',\n\n defaults: {\n enabled: true,\n forceOverride: false\n } as ColorsPluginOptions,\n\n beforeLayout(chart: Chart, _args, options: ColorsPluginOptions) {\n if (!options.enabled) {\n return;\n }\n\n const {\n data: {datasets},\n options: chartOptions\n } = chart.config;\n const {elements} = chartOptions;\n\n if (!options.forceOverride && (containsColorsDefinitions(datasets) || containsColorsDefinition(chartOptions) || (elements && containsColorsDefinitions(elements)))) {\n return;\n }\n\n const colorizer = getColorizer(chart);\n\n datasets.forEach(colorizer);\n }\n};\n","import {_limitValue, _lookupByKey, isNullOrUndef, resolve} from '../helpers/index.js';\n\nfunction lttbDecimation(data, start, count, availableWidth, options) {\n /**\n * Implementation of the Largest Triangle Three Buckets algorithm.\n *\n * This implementation is based on the original implementation by Sveinn Steinarsson\n * in https://github.com/sveinn-steinarsson/flot-downsample/blob/master/jquery.flot.downsample.js\n *\n * The original implementation is MIT licensed.\n */\n const samples = options.samples || availableWidth;\n // There are less points than the threshold, returning the whole array\n if (samples >= count) {\n return data.slice(start, start + count);\n }\n\n const decimated = [];\n\n const bucketWidth = (count - 2) / (samples - 2);\n let sampledIndex = 0;\n const endIndex = start + count - 1;\n // Starting from offset\n let a = start;\n let i, maxAreaPoint, maxArea, area, nextA;\n\n decimated[sampledIndex++] = data[a];\n\n for (i = 0; i < samples - 2; i++) {\n let avgX = 0;\n let avgY = 0;\n let j;\n\n // Adding offset\n const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;\n const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;\n const avgRangeLength = avgRangeEnd - avgRangeStart;\n\n for (j = avgRangeStart; j < avgRangeEnd; j++) {\n avgX += data[j].x;\n avgY += data[j].y;\n }\n\n avgX /= avgRangeLength;\n avgY /= avgRangeLength;\n\n // Adding offset\n const rangeOffs = Math.floor(i * bucketWidth) + 1 + start;\n const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start;\n const {x: pointAx, y: pointAy} = data[a];\n\n // Note that this is changed from the original algorithm which initializes these\n // values to 1. The reason for this change is that if the area is small, nextA\n // would never be set and thus a crash would occur in the next loop as `a` would become\n // `undefined`. Since the area is always positive, but could be 0 in the case of a flat trace,\n // initializing with a negative number is the correct solution.\n maxArea = area = -1;\n\n for (j = rangeOffs; j < rangeTo; j++) {\n area = 0.5 * Math.abs(\n (pointAx - avgX) * (data[j].y - pointAy) -\n (pointAx - data[j].x) * (avgY - pointAy)\n );\n\n if (area > maxArea) {\n maxArea = area;\n maxAreaPoint = data[j];\n nextA = j;\n }\n }\n\n decimated[sampledIndex++] = maxAreaPoint;\n a = nextA;\n }\n\n // Include the last point\n decimated[sampledIndex++] = data[endIndex];\n\n return decimated;\n}\n\nfunction minMaxDecimation(data, start, count, availableWidth) {\n let avgX = 0;\n let countX = 0;\n let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;\n const decimated = [];\n const endIndex = start + count - 1;\n\n const xMin = data[start].x;\n const xMax = data[endIndex].x;\n const dx = xMax - xMin;\n\n for (i = start; i < start + count; ++i) {\n point = data[i];\n x = (point.x - xMin) / dx * availableWidth;\n y = point.y;\n const truncX = x | 0;\n\n if (truncX === prevX) {\n // Determine `minY` / `maxY` and `avgX` while we stay within same x-position\n if (y < minY) {\n minY = y;\n minIndex = i;\n } else if (y > maxY) {\n maxY = y;\n maxIndex = i;\n }\n // For first point in group, countX is `0`, so average will be `x` / 1.\n // Use point.x here because we're computing the average data `x` value\n avgX = (countX * avgX + point.x) / ++countX;\n } else {\n // Push up to 4 points, 3 for the last interval and the first point for this interval\n const lastIndex = i - 1;\n\n if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) {\n // The interval is defined by 4 points: start, min, max, end.\n // The starting point is already considered at this point, so we need to determine which\n // of the other points to add. We need to sort these points to ensure the decimated data\n // is still sorted and then ensure there are no duplicates.\n const intermediateIndex1 = Math.min(minIndex, maxIndex);\n const intermediateIndex2 = Math.max(minIndex, maxIndex);\n\n if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {\n decimated.push({\n ...data[intermediateIndex1],\n x: avgX,\n });\n }\n if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {\n decimated.push({\n ...data[intermediateIndex2],\n x: avgX\n });\n }\n }\n\n // lastIndex === startIndex will occur when a range has only 1 point which could\n // happen with very uneven data\n if (i > 0 && lastIndex !== startIndex) {\n // Last point in the previous interval\n decimated.push(data[lastIndex]);\n }\n\n // Start of the new interval\n decimated.push(point);\n prevX = truncX;\n countX = 0;\n minY = maxY = y;\n minIndex = maxIndex = startIndex = i;\n }\n }\n\n return decimated;\n}\n\nfunction cleanDecimatedDataset(dataset) {\n if (dataset._decimated) {\n const data = dataset._data;\n delete dataset._decimated;\n delete dataset._data;\n Object.defineProperty(dataset, 'data', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: data,\n });\n }\n}\n\nfunction cleanDecimatedData(chart) {\n chart.data.datasets.forEach((dataset) => {\n cleanDecimatedDataset(dataset);\n });\n}\n\nfunction getStartAndCountOfVisiblePointsSimplified(meta, points) {\n const pointCount = points.length;\n\n let start = 0;\n let count;\n\n const {iScale} = meta;\n const {min, max, minDefined, maxDefined} = iScale.getUserBounds();\n\n if (minDefined) {\n start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);\n }\n if (maxDefined) {\n count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;\n } else {\n count = pointCount - start;\n }\n\n return {start, count};\n}\n\nexport default {\n id: 'decimation',\n\n defaults: {\n algorithm: 'min-max',\n enabled: false,\n },\n\n beforeElementsUpdate: (chart, args, options) => {\n if (!options.enabled) {\n // The decimation plugin may have been previously enabled. Need to remove old `dataset._data` handlers\n cleanDecimatedData(chart);\n return;\n }\n\n // Assume the entire chart is available to show a few more points than needed\n const availableWidth = chart.width;\n\n chart.data.datasets.forEach((dataset, datasetIndex) => {\n const {_data, indexAxis} = dataset;\n const meta = chart.getDatasetMeta(datasetIndex);\n const data = _data || dataset.data;\n\n if (resolve([indexAxis, chart.options.indexAxis]) === 'y') {\n // Decimation is only supported for lines that have an X indexAxis\n return;\n }\n\n if (!meta.controller.supportsDecimation) {\n // Only line datasets are supported\n return;\n }\n\n const xAxis = chart.scales[meta.xAxisID];\n if (xAxis.type !== 'linear' && xAxis.type !== 'time') {\n // Only linear interpolation is supported\n return;\n }\n\n if (chart.options.parsing) {\n // Plugin only supports data that does not need parsing\n return;\n }\n\n let {start, count} = getStartAndCountOfVisiblePointsSimplified(meta, data);\n const threshold = options.threshold || 4 * availableWidth;\n if (count <= threshold) {\n // No decimation is required until we are above this threshold\n cleanDecimatedDataset(dataset);\n return;\n }\n\n if (isNullOrUndef(_data)) {\n // First time we are seeing this dataset\n // We override the 'data' property with a setter that stores the\n // raw data in _data, but reads the decimated data from _decimated\n dataset._data = data;\n delete dataset.data;\n Object.defineProperty(dataset, 'data', {\n configurable: true,\n enumerable: true,\n get: function() {\n return this._decimated;\n },\n set: function(d) {\n this._data = d;\n }\n });\n }\n\n // Point the chart to the decimated data\n let decimated;\n switch (options.algorithm) {\n case 'lttb':\n decimated = lttbDecimation(data, start, count, availableWidth, options);\n break;\n case 'min-max':\n decimated = minMaxDecimation(data, start, count, availableWidth);\n break;\n default:\n throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);\n }\n\n dataset._decimated = decimated;\n });\n },\n\n destroy(chart) {\n cleanDecimatedData(chart);\n }\n};\n","import {_boundSegment, _boundSegments, _normalizeAngle} from '../../helpers/index.js';\n\nexport function _segments(line, target, property) {\n const segments = line.segments;\n const points = line.points;\n const tpoints = target.points;\n const parts = [];\n\n for (const segment of segments) {\n let {start, end} = segment;\n end = _findSegmentEnd(start, end, points);\n\n const bounds = _getBounds(property, points[start], points[end], segment.loop);\n\n if (!target.segments) {\n // Special case for boundary not supporting `segments` (simpleArc)\n // Bounds are provided as `target` for partial circle, or undefined for full circle\n parts.push({\n source: segment,\n target: bounds,\n start: points[start],\n end: points[end]\n });\n continue;\n }\n\n // Get all segments from `target` that intersect the bounds of current segment of `line`\n const targetSegments = _boundSegments(target, bounds);\n\n for (const tgt of targetSegments) {\n const subBounds = _getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);\n const fillSources = _boundSegment(segment, points, subBounds);\n\n for (const fillSource of fillSources) {\n parts.push({\n source: fillSource,\n target: tgt,\n start: {\n [property]: _getEdge(bounds, subBounds, 'start', Math.max)\n },\n end: {\n [property]: _getEdge(bounds, subBounds, 'end', Math.min)\n }\n });\n }\n }\n }\n return parts;\n}\n\nexport function _getBounds(property, first, last, loop) {\n if (loop) {\n return;\n }\n let start = first[property];\n let end = last[property];\n\n if (property === 'angle') {\n start = _normalizeAngle(start);\n end = _normalizeAngle(end);\n }\n return {property, start, end};\n}\n\nexport function _pointsFromSegments(boundary, line) {\n const {x = null, y = null} = boundary || {};\n const linePoints = line.points;\n const points = [];\n line.segments.forEach(({start, end}) => {\n end = _findSegmentEnd(start, end, linePoints);\n const first = linePoints[start];\n const last = linePoints[end];\n if (y !== null) {\n points.push({x: first.x, y});\n points.push({x: last.x, y});\n } else if (x !== null) {\n points.push({x, y: first.y});\n points.push({x, y: last.y});\n }\n });\n return points;\n}\n\nexport function _findSegmentEnd(start, end, points) {\n for (;end > start; end--) {\n const point = points[end];\n if (!isNaN(point.x) && !isNaN(point.y)) {\n break;\n }\n }\n return end;\n}\n\nfunction _getEdge(a, b, prop, fn) {\n if (a && b) {\n return fn(a[prop], b[prop]);\n }\n return a ? a[prop] : b ? b[prop] : 0;\n}\n","/**\n * @typedef { import('../../core/core.controller.js').default } Chart\n * @typedef { import('../../core/core.scale.js').default } Scale\n * @typedef { import('../../elements/element.point.js').default } PointElement\n */\n\nimport {LineElement} from '../../elements/index.js';\nimport {isArray} from '../../helpers/index.js';\nimport {_pointsFromSegments} from './filler.segment.js';\n\n/**\n * @param {PointElement[] | { x: number; y: number; }} boundary\n * @param {LineElement} line\n * @return {LineElement?}\n */\nexport function _createBoundaryLine(boundary, line) {\n let points = [];\n let _loop = false;\n\n if (isArray(boundary)) {\n _loop = true;\n // @ts-ignore\n points = boundary;\n } else {\n points = _pointsFromSegments(boundary, line);\n }\n\n return points.length ? new LineElement({\n points,\n options: {tension: 0},\n _loop,\n _fullLoop: _loop\n }) : null;\n}\n\nexport function _shouldApplyFill(source) {\n return source && source.fill !== false;\n}\n","import {isObject, isFinite, valueOrDefault} from '../../helpers/helpers.core.js';\n\n/**\n * @typedef { import('../../core/core.scale.js').default } Scale\n * @typedef { import('../../elements/element.line.js').default } LineElement\n * @typedef { import('../../types/index.js').FillTarget } FillTarget\n * @typedef { import('../../types/index.js').ComplexFillTarget } ComplexFillTarget\n */\n\nexport function _resolveTarget(sources, index, propagate) {\n const source = sources[index];\n let fill = source.fill;\n const visited = [index];\n let target;\n\n if (!propagate) {\n return fill;\n }\n\n while (fill !== false && visited.indexOf(fill) === -1) {\n if (!isFinite(fill)) {\n return fill;\n }\n\n target = sources[fill];\n if (!target) {\n return false;\n }\n\n if (target.visible) {\n return fill;\n }\n\n visited.push(fill);\n fill = target.fill;\n }\n\n return false;\n}\n\n/**\n * @param {LineElement} line\n * @param {number} index\n * @param {number} count\n */\nexport function _decodeFill(line, index, count) {\n /** @type {string | {value: number}} */\n const fill = parseFillOption(line);\n\n if (isObject(fill)) {\n return isNaN(fill.value) ? false : fill;\n }\n\n let target = parseFloat(fill);\n\n if (isFinite(target) && Math.floor(target) === target) {\n return decodeTargetIndex(fill[0], index, target, count);\n }\n\n return ['origin', 'start', 'end', 'stack', 'shape'].indexOf(fill) >= 0 && fill;\n}\n\nfunction decodeTargetIndex(firstCh, index, target, count) {\n if (firstCh === '-' || firstCh === '+') {\n target = index + target;\n }\n\n if (target === index || target < 0 || target >= count) {\n return false;\n }\n\n return target;\n}\n\n/**\n * @param {FillTarget | ComplexFillTarget} fill\n * @param {Scale} scale\n * @returns {number | null}\n */\nexport function _getTargetPixel(fill, scale) {\n let pixel = null;\n if (fill === 'start') {\n pixel = scale.bottom;\n } else if (fill === 'end') {\n pixel = scale.top;\n } else if (isObject(fill)) {\n // @ts-ignore\n pixel = scale.getPixelForValue(fill.value);\n } else if (scale.getBasePixel) {\n pixel = scale.getBasePixel();\n }\n return pixel;\n}\n\n/**\n * @param {FillTarget | ComplexFillTarget} fill\n * @param {Scale} scale\n * @param {number} startValue\n * @returns {number | undefined}\n */\nexport function _getTargetValue(fill, scale, startValue) {\n let value;\n\n if (fill === 'start') {\n value = startValue;\n } else if (fill === 'end') {\n value = scale.options.reverse ? scale.min : scale.max;\n } else if (isObject(fill)) {\n // @ts-ignore\n value = fill.value;\n } else {\n value = scale.getBaseValue();\n }\n return value;\n}\n\n/**\n * @param {LineElement} line\n */\nfunction parseFillOption(line) {\n const options = line.options;\n const fillOption = options.fill;\n let fill = valueOrDefault(fillOption && fillOption.target, fillOption);\n\n if (fill === undefined) {\n fill = !!options.backgroundColor;\n }\n\n if (fill === false || fill === null) {\n return false;\n }\n\n if (fill === true) {\n return 'origin';\n }\n return fill;\n}\n","/**\n * @typedef { import('../../core/core.controller.js').default } Chart\n * @typedef { import('../../core/core.scale.js').default } Scale\n * @typedef { import('../../elements/element.point.js').default } PointElement\n */\n\nimport {LineElement} from '../../elements/index.js';\nimport {_isBetween} from '../../helpers/index.js';\nimport {_createBoundaryLine} from './filler.helper.js';\n\n/**\n * @param {{ chart: Chart; scale: Scale; index: number; line: LineElement; }} source\n * @return {LineElement}\n */\nexport function _buildStackLine(source) {\n const {scale, index, line} = source;\n const points = [];\n const segments = line.segments;\n const sourcePoints = line.points;\n const linesBelow = getLinesBelow(scale, index);\n linesBelow.push(_createBoundaryLine({x: null, y: scale.bottom}, line));\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n for (let j = segment.start; j <= segment.end; j++) {\n addPointsBelow(points, sourcePoints[j], linesBelow);\n }\n }\n return new LineElement({points, options: {}});\n}\n\n/**\n * @param {Scale} scale\n * @param {number} index\n * @return {LineElement[]}\n */\nfunction getLinesBelow(scale, index) {\n const below = [];\n const metas = scale.getMatchingVisibleMetas('line');\n\n for (let i = 0; i < metas.length; i++) {\n const meta = metas[i];\n if (meta.index === index) {\n break;\n }\n if (!meta.hidden) {\n below.unshift(meta.dataset);\n }\n }\n return below;\n}\n\n/**\n * @param {PointElement[]} points\n * @param {PointElement} sourcePoint\n * @param {LineElement[]} linesBelow\n */\nfunction addPointsBelow(points, sourcePoint, linesBelow) {\n const postponed = [];\n for (let j = 0; j < linesBelow.length; j++) {\n const line = linesBelow[j];\n const {first, last, point} = findPoint(line, sourcePoint, 'x');\n\n if (!point || (first && last)) {\n continue;\n }\n if (first) {\n // First point of an segment -> need to add another point before this,\n // from next line below.\n postponed.unshift(point);\n } else {\n points.push(point);\n if (!last) {\n // In the middle of an segment, no need to add more points.\n break;\n }\n }\n }\n points.push(...postponed);\n}\n\n/**\n * @param {LineElement} line\n * @param {PointElement} sourcePoint\n * @param {string} property\n * @returns {{point?: PointElement, first?: boolean, last?: boolean}}\n */\nfunction findPoint(line, sourcePoint, property) {\n const point = line.interpolate(sourcePoint, property);\n if (!point) {\n return {};\n }\n\n const pointValue = point[property];\n const segments = line.segments;\n const linePoints = line.points;\n let first = false;\n let last = false;\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n const firstValue = linePoints[segment.start][property];\n const lastValue = linePoints[segment.end][property];\n if (_isBetween(pointValue, firstValue, lastValue)) {\n first = pointValue === firstValue;\n last = pointValue === lastValue;\n break;\n }\n }\n return {first, last, point};\n}\n","import {TAU} from '../../helpers/index.js';\n\n// TODO: use elements.ArcElement instead\nexport class simpleArc {\n constructor(opts) {\n this.x = opts.x;\n this.y = opts.y;\n this.radius = opts.radius;\n }\n\n pathSegment(ctx, bounds, opts) {\n const {x, y, radius} = this;\n bounds = bounds || {start: 0, end: TAU};\n ctx.arc(x, y, radius, bounds.end, bounds.start, true);\n return !opts.bounds;\n }\n\n interpolate(point) {\n const {x, y, radius} = this;\n const angle = point.angle;\n return {\n x: x + Math.cos(angle) * radius,\n y: y + Math.sin(angle) * radius,\n angle\n };\n }\n}\n","import {isFinite} from '../../helpers/index.js';\nimport {_createBoundaryLine} from './filler.helper.js';\nimport {_getTargetPixel, _getTargetValue} from './filler.options.js';\nimport {_buildStackLine} from './filler.target.stack.js';\nimport {simpleArc} from './simpleArc.js';\n\n/**\n * @typedef { import('../../core/core.controller.js').default } Chart\n * @typedef { import('../../core/core.scale.js').default } Scale\n * @typedef { import('../../elements/element.point.js').default } PointElement\n */\n\nexport function _getTarget(source) {\n const {chart, fill, line} = source;\n\n if (isFinite(fill)) {\n return getLineByIndex(chart, fill);\n }\n\n if (fill === 'stack') {\n return _buildStackLine(source);\n }\n\n if (fill === 'shape') {\n return true;\n }\n\n const boundary = computeBoundary(source);\n\n if (boundary instanceof simpleArc) {\n return boundary;\n }\n\n return _createBoundaryLine(boundary, line);\n}\n\n/**\n * @param {Chart} chart\n * @param {number} index\n */\nfunction getLineByIndex(chart, index) {\n const meta = chart.getDatasetMeta(index);\n const visible = meta && chart.isDatasetVisible(index);\n return visible ? meta.dataset : null;\n}\n\nfunction computeBoundary(source) {\n const scale = source.scale || {};\n\n if (scale.getPointPositionForValue) {\n return computeCircularBoundary(source);\n }\n return computeLinearBoundary(source);\n}\n\n\nfunction computeLinearBoundary(source) {\n const {scale = {}, fill} = source;\n const pixel = _getTargetPixel(fill, scale);\n\n if (isFinite(pixel)) {\n const horizontal = scale.isHorizontal();\n\n return {\n x: horizontal ? pixel : null,\n y: horizontal ? null : pixel\n };\n }\n\n return null;\n}\n\nfunction computeCircularBoundary(source) {\n const {scale, fill} = source;\n const options = scale.options;\n const length = scale.getLabels().length;\n const start = options.reverse ? scale.max : scale.min;\n const value = _getTargetValue(fill, scale, start);\n const target = [];\n\n if (options.grid.circular) {\n const center = scale.getPointPositionForValue(0, start);\n return new simpleArc({\n x: center.x,\n y: center.y,\n radius: scale.getDistanceFromCenterForValue(value)\n });\n }\n\n for (let i = 0; i < length; ++i) {\n target.push(scale.getPointPositionForValue(i, value));\n }\n return target;\n}\n\n","import {clipArea, unclipArea} from '../../helpers/index.js';\nimport {_findSegmentEnd, _getBounds, _segments} from './filler.segment.js';\nimport {_getTarget} from './filler.target.js';\n\nexport function _drawfill(ctx, source, area) {\n const target = _getTarget(source);\n const {line, scale, axis} = source;\n const lineOpts = line.options;\n const fillOption = lineOpts.fill;\n const color = lineOpts.backgroundColor;\n const {above = color, below = color} = fillOption || {};\n if (target && line.points.length) {\n clipArea(ctx, area);\n doFill(ctx, {line, target, above, below, area, scale, axis});\n unclipArea(ctx);\n }\n}\n\nfunction doFill(ctx, cfg) {\n const {line, target, above, below, area, scale} = cfg;\n const property = line._loop ? 'angle' : cfg.axis;\n\n ctx.save();\n\n if (property === 'x' && below !== above) {\n clipVertical(ctx, target, area.top);\n fill(ctx, {line, target, color: above, scale, property});\n ctx.restore();\n ctx.save();\n clipVertical(ctx, target, area.bottom);\n }\n fill(ctx, {line, target, color: below, scale, property});\n\n ctx.restore();\n}\n\nfunction clipVertical(ctx, target, clipY) {\n const {segments, points} = target;\n let first = true;\n let lineLoop = false;\n\n ctx.beginPath();\n for (const segment of segments) {\n const {start, end} = segment;\n const firstPoint = points[start];\n const lastPoint = points[_findSegmentEnd(start, end, points)];\n if (first) {\n ctx.moveTo(firstPoint.x, firstPoint.y);\n first = false;\n } else {\n ctx.lineTo(firstPoint.x, clipY);\n ctx.lineTo(firstPoint.x, firstPoint.y);\n }\n lineLoop = !!target.pathSegment(ctx, segment, {move: lineLoop});\n if (lineLoop) {\n ctx.closePath();\n } else {\n ctx.lineTo(lastPoint.x, clipY);\n }\n }\n\n ctx.lineTo(target.first().x, clipY);\n ctx.closePath();\n ctx.clip();\n}\n\nfunction fill(ctx, cfg) {\n const {line, target, property, color, scale} = cfg;\n const segments = _segments(line, target, property);\n\n for (const {source: src, target: tgt, start, end} of segments) {\n const {style: {backgroundColor = color} = {}} = src;\n const notShape = target !== true;\n\n ctx.save();\n ctx.fillStyle = backgroundColor;\n\n clipBounds(ctx, scale, notShape && _getBounds(property, start, end));\n\n ctx.beginPath();\n\n const lineLoop = !!line.pathSegment(ctx, src);\n\n let loop;\n if (notShape) {\n if (lineLoop) {\n ctx.closePath();\n } else {\n interpolatedLineTo(ctx, target, end, property);\n }\n\n const targetLoop = !!target.pathSegment(ctx, tgt, {move: lineLoop, reverse: true});\n loop = lineLoop && targetLoop;\n if (!loop) {\n interpolatedLineTo(ctx, target, start, property);\n }\n }\n\n ctx.closePath();\n ctx.fill(loop ? 'evenodd' : 'nonzero');\n\n ctx.restore();\n }\n}\n\nfunction clipBounds(ctx, scale, bounds) {\n const {top, bottom} = scale.chart.chartArea;\n const {property, start, end} = bounds || {};\n if (property === 'x') {\n ctx.beginPath();\n ctx.rect(start, top, end - start, bottom - top);\n ctx.clip();\n }\n}\n\nfunction interpolatedLineTo(ctx, target, point, property) {\n const interpolatedPoint = target.interpolate(point, property);\n if (interpolatedPoint) {\n ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);\n }\n}\n\n","/**\n * Plugin based on discussion from the following Chart.js issues:\n * @see https://github.com/chartjs/Chart.js/issues/2380#issuecomment-279961569\n * @see https://github.com/chartjs/Chart.js/issues/2440#issuecomment-256461897\n */\n\nimport LineElement from '../../elements/element.line.js';\nimport {_drawfill} from './filler.drawing.js';\nimport {_shouldApplyFill} from './filler.helper.js';\nimport {_decodeFill, _resolveTarget} from './filler.options.js';\n\nexport default {\n id: 'filler',\n\n afterDatasetsUpdate(chart, _args, options) {\n const count = (chart.data.datasets || []).length;\n const sources = [];\n let meta, i, line, source;\n\n for (i = 0; i < count; ++i) {\n meta = chart.getDatasetMeta(i);\n line = meta.dataset;\n source = null;\n\n if (line && line.options && line instanceof LineElement) {\n source = {\n visible: chart.isDatasetVisible(i),\n index: i,\n fill: _decodeFill(line, i, count),\n chart,\n axis: meta.controller.options.indexAxis,\n scale: meta.vScale,\n line,\n };\n }\n\n meta.$filler = source;\n sources.push(source);\n }\n\n for (i = 0; i < count; ++i) {\n source = sources[i];\n if (!source || source.fill === false) {\n continue;\n }\n\n source.fill = _resolveTarget(sources, i, options.propagate);\n }\n },\n\n beforeDraw(chart, _args, options) {\n const draw = options.drawTime === 'beforeDraw';\n const metasets = chart.getSortedVisibleDatasetMetas();\n const area = chart.chartArea;\n for (let i = metasets.length - 1; i >= 0; --i) {\n const source = metasets[i].$filler;\n if (!source) {\n continue;\n }\n\n source.line.updateControlPoints(area, source.axis);\n if (draw && source.fill) {\n _drawfill(chart.ctx, source, area);\n }\n }\n },\n\n beforeDatasetsDraw(chart, _args, options) {\n if (options.drawTime !== 'beforeDatasetsDraw') {\n return;\n }\n\n const metasets = chart.getSortedVisibleDatasetMetas();\n for (let i = metasets.length - 1; i >= 0; --i) {\n const source = metasets[i].$filler;\n\n if (_shouldApplyFill(source)) {\n _drawfill(chart.ctx, source, chart.chartArea);\n }\n }\n },\n\n beforeDatasetDraw(chart, args, options) {\n const source = args.meta.$filler;\n\n if (!_shouldApplyFill(source) || options.drawTime !== 'beforeDatasetDraw') {\n return;\n }\n\n _drawfill(chart.ctx, source, chart.chartArea);\n },\n\n defaults: {\n propagate: true,\n drawTime: 'beforeDatasetDraw'\n }\n};\n","import defaults from '../core/core.defaults.js';\nimport Element from '../core/core.element.js';\nimport layouts from '../core/core.layouts.js';\nimport {addRoundedRectPath, drawPointLegend, renderText} from '../helpers/helpers.canvas.js';\nimport {\n _isBetween,\n callback as call,\n clipArea,\n getRtlAdapter,\n overrideTextDirection,\n restoreTextDirection,\n toFont,\n toPadding,\n unclipArea,\n valueOrDefault,\n} from '../helpers/index.js';\nimport {_alignStartEnd, _textX, _toLeftRightCenter} from '../helpers/helpers.extras.js';\nimport {toTRBLCorners} from '../helpers/helpers.options.js';\n\n/**\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n */\n\nconst getBoxSize = (labelOpts, fontSize) => {\n let {boxHeight = fontSize, boxWidth = fontSize} = labelOpts;\n\n if (labelOpts.usePointStyle) {\n boxHeight = Math.min(boxHeight, fontSize);\n boxWidth = labelOpts.pointStyleWidth || Math.min(boxWidth, fontSize);\n }\n\n return {\n boxWidth,\n boxHeight,\n itemHeight: Math.max(fontSize, boxHeight)\n };\n};\n\nconst itemsEqual = (a, b) => a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;\n\nexport class Legend extends Element {\n\n /**\n\t * @param {{ ctx: any; options: any; chart: any; }} config\n\t */\n constructor(config) {\n super();\n\n this._added = false;\n\n // Contains hit boxes for each dataset (in dataset order)\n this.legendHitBoxes = [];\n\n /**\n \t\t * @private\n \t\t */\n this._hoveredItem = null;\n\n // Are we in doughnut mode which has a different data type\n this.doughnutMode = false;\n\n this.chart = config.chart;\n this.options = config.options;\n this.ctx = config.ctx;\n this.legendItems = undefined;\n this.columnSizes = undefined;\n this.lineWidths = undefined;\n this.maxHeight = undefined;\n this.maxWidth = undefined;\n this.top = undefined;\n this.bottom = undefined;\n this.left = undefined;\n this.right = undefined;\n this.height = undefined;\n this.width = undefined;\n this._margins = undefined;\n this.position = undefined;\n this.weight = undefined;\n this.fullSize = undefined;\n }\n\n update(maxWidth, maxHeight, margins) {\n this.maxWidth = maxWidth;\n this.maxHeight = maxHeight;\n this._margins = margins;\n\n this.setDimensions();\n this.buildLabels();\n this.fit();\n }\n\n setDimensions() {\n if (this.isHorizontal()) {\n this.width = this.maxWidth;\n this.left = this._margins.left;\n this.right = this.width;\n } else {\n this.height = this.maxHeight;\n this.top = this._margins.top;\n this.bottom = this.height;\n }\n }\n\n buildLabels() {\n const labelOpts = this.options.labels || {};\n let legendItems = call(labelOpts.generateLabels, [this.chart], this) || [];\n\n if (labelOpts.filter) {\n legendItems = legendItems.filter((item) => labelOpts.filter(item, this.chart.data));\n }\n\n if (labelOpts.sort) {\n legendItems = legendItems.sort((a, b) => labelOpts.sort(a, b, this.chart.data));\n }\n\n if (this.options.reverse) {\n legendItems.reverse();\n }\n\n this.legendItems = legendItems;\n }\n\n fit() {\n const {options, ctx} = this;\n\n // The legend may not be displayed for a variety of reasons including\n // the fact that the defaults got set to `false`.\n // When the legend is not displayed, there are no guarantees that the options\n // are correctly formatted so we need to bail out as early as possible.\n if (!options.display) {\n this.width = this.height = 0;\n return;\n }\n\n const labelOpts = options.labels;\n const labelFont = toFont(labelOpts.font);\n const fontSize = labelFont.size;\n const titleHeight = this._computeTitleHeight();\n const {boxWidth, itemHeight} = getBoxSize(labelOpts, fontSize);\n\n let width, height;\n\n ctx.font = labelFont.string;\n\n if (this.isHorizontal()) {\n width = this.maxWidth; // fill all the width\n height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;\n } else {\n height = this.maxHeight; // fill all the height\n width = this._fitCols(titleHeight, labelFont, boxWidth, itemHeight) + 10;\n }\n\n this.width = Math.min(width, options.maxWidth || this.maxWidth);\n this.height = Math.min(height, options.maxHeight || this.maxHeight);\n }\n\n /**\n\t * @private\n\t */\n _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {\n const {ctx, maxWidth, options: {labels: {padding}}} = this;\n const hitboxes = this.legendHitBoxes = [];\n // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one\n const lineWidths = this.lineWidths = [0];\n const lineHeight = itemHeight + padding;\n let totalHeight = titleHeight;\n\n ctx.textAlign = 'left';\n ctx.textBaseline = 'middle';\n\n let row = -1;\n let top = -lineHeight;\n this.legendItems.forEach((legendItem, i) => {\n const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;\n\n if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {\n totalHeight += lineHeight;\n lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;\n top += lineHeight;\n row++;\n }\n\n hitboxes[i] = {left: 0, top, row, width: itemWidth, height: itemHeight};\n\n lineWidths[lineWidths.length - 1] += itemWidth + padding;\n });\n\n return totalHeight;\n }\n\n _fitCols(titleHeight, labelFont, boxWidth, _itemHeight) {\n const {ctx, maxHeight, options: {labels: {padding}}} = this;\n const hitboxes = this.legendHitBoxes = [];\n const columnSizes = this.columnSizes = [];\n const heightLimit = maxHeight - titleHeight;\n\n let totalWidth = padding;\n let currentColWidth = 0;\n let currentColHeight = 0;\n\n let left = 0;\n let col = 0;\n\n this.legendItems.forEach((legendItem, i) => {\n const {itemWidth, itemHeight} = calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight);\n\n // If too tall, go to new column\n if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) {\n totalWidth += currentColWidth + padding;\n columnSizes.push({width: currentColWidth, height: currentColHeight}); // previous column size\n left += currentColWidth + padding;\n col++;\n currentColWidth = currentColHeight = 0;\n }\n\n // Store the hitbox width and height here. Final position will be updated in `draw`\n hitboxes[i] = {left, top: currentColHeight, col, width: itemWidth, height: itemHeight};\n\n // Get max width\n currentColWidth = Math.max(currentColWidth, itemWidth);\n currentColHeight += itemHeight + padding;\n });\n\n totalWidth += currentColWidth;\n columnSizes.push({width: currentColWidth, height: currentColHeight}); // previous column size\n\n return totalWidth;\n }\n\n adjustHitBoxes() {\n if (!this.options.display) {\n return;\n }\n const titleHeight = this._computeTitleHeight();\n const {legendHitBoxes: hitboxes, options: {align, labels: {padding}, rtl}} = this;\n const rtlHelper = getRtlAdapter(rtl, this.left, this.width);\n if (this.isHorizontal()) {\n let row = 0;\n let left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);\n for (const hitbox of hitboxes) {\n if (row !== hitbox.row) {\n row = hitbox.row;\n left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);\n }\n hitbox.top += this.top + titleHeight + padding;\n hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width);\n left += hitbox.width + padding;\n }\n } else {\n let col = 0;\n let top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);\n for (const hitbox of hitboxes) {\n if (hitbox.col !== col) {\n col = hitbox.col;\n top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);\n }\n hitbox.top = top;\n hitbox.left += this.left + padding;\n hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width);\n top += hitbox.height + padding;\n }\n }\n }\n\n isHorizontal() {\n return this.options.position === 'top' || this.options.position === 'bottom';\n }\n\n draw() {\n if (this.options.display) {\n const ctx = this.ctx;\n clipArea(ctx, this);\n\n this._draw();\n\n unclipArea(ctx);\n }\n }\n\n /**\n\t * @private\n\t */\n _draw() {\n const {options: opts, columnSizes, lineWidths, ctx} = this;\n const {align, labels: labelOpts} = opts;\n const defaultColor = defaults.color;\n const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);\n const labelFont = toFont(labelOpts.font);\n const {padding} = labelOpts;\n const fontSize = labelFont.size;\n const halfFontSize = fontSize / 2;\n let cursor;\n\n this.drawTitle();\n\n // Canvas setup\n ctx.textAlign = rtlHelper.textAlign('left');\n ctx.textBaseline = 'middle';\n ctx.lineWidth = 0.5;\n ctx.font = labelFont.string;\n\n const {boxWidth, boxHeight, itemHeight} = getBoxSize(labelOpts, fontSize);\n\n // current position\n const drawLegendBox = function(x, y, legendItem) {\n if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {\n return;\n }\n\n // Set the ctx for the box\n ctx.save();\n\n const lineWidth = valueOrDefault(legendItem.lineWidth, 1);\n ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);\n ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt');\n ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0);\n ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter');\n ctx.lineWidth = lineWidth;\n ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor);\n\n ctx.setLineDash(valueOrDefault(legendItem.lineDash, []));\n\n if (labelOpts.usePointStyle) {\n // Recalculate x and y for drawPoint() because its expecting\n // x and y to be center of figure (instead of top left)\n const drawOptions = {\n radius: boxHeight * Math.SQRT2 / 2,\n pointStyle: legendItem.pointStyle,\n rotation: legendItem.rotation,\n borderWidth: lineWidth\n };\n const centerX = rtlHelper.xPlus(x, boxWidth / 2);\n const centerY = y + halfFontSize;\n\n // Draw pointStyle as legend symbol\n drawPointLegend(ctx, drawOptions, centerX, centerY, labelOpts.pointStyleWidth && boxWidth);\n } else {\n // Draw box as legend symbol\n // Adjust position when boxHeight < fontSize (want it centered)\n const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);\n const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);\n const borderRadius = toTRBLCorners(legendItem.borderRadius);\n\n ctx.beginPath();\n\n if (Object.values(borderRadius).some(v => v !== 0)) {\n addRoundedRectPath(ctx, {\n x: xBoxLeft,\n y: yBoxTop,\n w: boxWidth,\n h: boxHeight,\n radius: borderRadius,\n });\n } else {\n ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);\n }\n\n ctx.fill();\n if (lineWidth !== 0) {\n ctx.stroke();\n }\n }\n\n ctx.restore();\n };\n\n const fillText = function(x, y, legendItem) {\n renderText(ctx, legendItem.text, x, y + (itemHeight / 2), labelFont, {\n strikethrough: legendItem.hidden,\n textAlign: rtlHelper.textAlign(legendItem.textAlign)\n });\n };\n\n // Horizontal\n const isHorizontal = this.isHorizontal();\n const titleHeight = this._computeTitleHeight();\n if (isHorizontal) {\n cursor = {\n x: _alignStartEnd(align, this.left + padding, this.right - lineWidths[0]),\n y: this.top + padding + titleHeight,\n line: 0\n };\n } else {\n cursor = {\n x: this.left + padding,\n y: _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height),\n line: 0\n };\n }\n\n overrideTextDirection(this.ctx, opts.textDirection);\n\n const lineHeight = itemHeight + padding;\n this.legendItems.forEach((legendItem, i) => {\n ctx.strokeStyle = legendItem.fontColor; // for strikethrough effect\n ctx.fillStyle = legendItem.fontColor; // render in correct colour\n\n const textWidth = ctx.measureText(legendItem.text).width;\n const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));\n const width = boxWidth + halfFontSize + textWidth;\n let x = cursor.x;\n let y = cursor.y;\n\n rtlHelper.setWidth(this.width);\n\n if (isHorizontal) {\n if (i > 0 && x + width + padding > this.right) {\n y = cursor.y += lineHeight;\n cursor.line++;\n x = cursor.x = _alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]);\n }\n } else if (i > 0 && y + lineHeight > this.bottom) {\n x = cursor.x = x + columnSizes[cursor.line].width + padding;\n cursor.line++;\n y = cursor.y = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height);\n }\n\n const realX = rtlHelper.x(x);\n\n drawLegendBox(realX, y, legendItem);\n\n x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl);\n\n // Fill the actual label\n fillText(rtlHelper.x(x), y, legendItem);\n\n if (isHorizontal) {\n cursor.x += width + padding;\n } else if (typeof legendItem.text !== 'string') {\n const fontLineHeight = labelFont.lineHeight;\n cursor.y += calculateLegendItemHeight(legendItem, fontLineHeight) + padding;\n } else {\n cursor.y += lineHeight;\n }\n });\n\n restoreTextDirection(this.ctx, opts.textDirection);\n }\n\n /**\n\t * @protected\n\t */\n drawTitle() {\n const opts = this.options;\n const titleOpts = opts.title;\n const titleFont = toFont(titleOpts.font);\n const titlePadding = toPadding(titleOpts.padding);\n\n if (!titleOpts.display) {\n return;\n }\n\n const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);\n const ctx = this.ctx;\n const position = titleOpts.position;\n const halfFontSize = titleFont.size / 2;\n const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;\n let y;\n\n // These defaults are used when the legend is vertical.\n // When horizontal, they are computed below.\n let left = this.left;\n let maxWidth = this.width;\n\n if (this.isHorizontal()) {\n // Move left / right so that the title is above the legend lines\n maxWidth = Math.max(...this.lineWidths);\n y = this.top + topPaddingPlusHalfFontSize;\n left = _alignStartEnd(opts.align, left, this.right - maxWidth);\n } else {\n // Move down so that the title is above the legend stack in every alignment\n const maxHeight = this.columnSizes.reduce((acc, size) => Math.max(acc, size.height), 0);\n y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight());\n }\n\n // Now that we know the left edge of the inner legend box, compute the correct\n // X coordinate from the title alignment\n const x = _alignStartEnd(position, left, left + maxWidth);\n\n // Canvas setup\n ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position));\n ctx.textBaseline = 'middle';\n ctx.strokeStyle = titleOpts.color;\n ctx.fillStyle = titleOpts.color;\n ctx.font = titleFont.string;\n\n renderText(ctx, titleOpts.text, x, y, titleFont);\n }\n\n /**\n\t * @private\n\t */\n _computeTitleHeight() {\n const titleOpts = this.options.title;\n const titleFont = toFont(titleOpts.font);\n const titlePadding = toPadding(titleOpts.padding);\n return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;\n }\n\n /**\n\t * @private\n\t */\n _getLegendItemAt(x, y) {\n let i, hitBox, lh;\n\n if (_isBetween(x, this.left, this.right)\n && _isBetween(y, this.top, this.bottom)) {\n // See if we are touching one of the dataset boxes\n lh = this.legendHitBoxes;\n for (i = 0; i < lh.length; ++i) {\n hitBox = lh[i];\n\n if (_isBetween(x, hitBox.left, hitBox.left + hitBox.width)\n && _isBetween(y, hitBox.top, hitBox.top + hitBox.height)) {\n // Touching an element\n return this.legendItems[i];\n }\n }\n }\n\n return null;\n }\n\n /**\n\t * Handle an event\n\t * @param {ChartEvent} e - The event to handle\n\t */\n handleEvent(e) {\n const opts = this.options;\n if (!isListened(e.type, opts)) {\n return;\n }\n\n // Chart event already has relative position in it\n const hoveredItem = this._getLegendItemAt(e.x, e.y);\n\n if (e.type === 'mousemove' || e.type === 'mouseout') {\n const previous = this._hoveredItem;\n const sameItem = itemsEqual(previous, hoveredItem);\n if (previous && !sameItem) {\n call(opts.onLeave, [e, previous, this], this);\n }\n\n this._hoveredItem = hoveredItem;\n\n if (hoveredItem && !sameItem) {\n call(opts.onHover, [e, hoveredItem, this], this);\n }\n } else if (hoveredItem) {\n call(opts.onClick, [e, hoveredItem, this], this);\n }\n }\n}\n\nfunction calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight) {\n const itemWidth = calculateItemWidth(legendItem, boxWidth, labelFont, ctx);\n const itemHeight = calculateItemHeight(_itemHeight, legendItem, labelFont.lineHeight);\n return {itemWidth, itemHeight};\n}\n\nfunction calculateItemWidth(legendItem, boxWidth, labelFont, ctx) {\n let legendItemText = legendItem.text;\n if (legendItemText && typeof legendItemText !== 'string') {\n legendItemText = legendItemText.reduce((a, b) => a.length > b.length ? a : b);\n }\n return boxWidth + (labelFont.size / 2) + ctx.measureText(legendItemText).width;\n}\n\nfunction calculateItemHeight(_itemHeight, legendItem, fontLineHeight) {\n let itemHeight = _itemHeight;\n if (typeof legendItem.text !== 'string') {\n itemHeight = calculateLegendItemHeight(legendItem, fontLineHeight);\n }\n return itemHeight;\n}\n\nfunction calculateLegendItemHeight(legendItem, fontLineHeight) {\n const labelHeight = legendItem.text ? legendItem.text.length : 0;\n return fontLineHeight * labelHeight;\n}\n\nfunction isListened(type, opts) {\n if ((type === 'mousemove' || type === 'mouseout') && (opts.onHover || opts.onLeave)) {\n return true;\n }\n if (opts.onClick && (type === 'click' || type === 'mouseup')) {\n return true;\n }\n return false;\n}\n\nexport default {\n id: 'legend',\n\n /**\n\t * For tests\n\t * @private\n\t */\n _element: Legend,\n\n start(chart, _args, options) {\n const legend = chart.legend = new Legend({ctx: chart.ctx, options, chart});\n layouts.configure(chart, legend, options);\n layouts.addBox(chart, legend);\n },\n\n stop(chart) {\n layouts.removeBox(chart, chart.legend);\n delete chart.legend;\n },\n\n // During the beforeUpdate step, the layout configuration needs to run\n // This ensures that if the legend position changes (via an option update)\n // the layout system respects the change. See https://github.com/chartjs/Chart.js/issues/7527\n beforeUpdate(chart, _args, options) {\n const legend = chart.legend;\n layouts.configure(chart, legend, options);\n legend.options = options;\n },\n\n // The labels need to be built after datasets are updated to ensure that colors\n // and other styling are correct. See https://github.com/chartjs/Chart.js/issues/6968\n afterUpdate(chart) {\n const legend = chart.legend;\n legend.buildLabels();\n legend.adjustHitBoxes();\n },\n\n\n afterEvent(chart, args) {\n if (!args.replay) {\n chart.legend.handleEvent(args.event);\n }\n },\n\n defaults: {\n display: true,\n position: 'top',\n align: 'center',\n fullSize: true,\n reverse: false,\n weight: 1000,\n\n // a callback that will handle\n onClick(e, legendItem, legend) {\n const index = legendItem.datasetIndex;\n const ci = legend.chart;\n if (ci.isDatasetVisible(index)) {\n ci.hide(index);\n legendItem.hidden = true;\n } else {\n ci.show(index);\n legendItem.hidden = false;\n }\n },\n\n onHover: null,\n onLeave: null,\n\n labels: {\n color: (ctx) => ctx.chart.options.color,\n boxWidth: 40,\n padding: 10,\n // Generates labels shown in the legend\n // Valid properties to return:\n // text : text to display\n // fillStyle : fill of coloured box\n // strokeStyle: stroke of coloured box\n // hidden : if this legend item refers to a hidden item\n // lineCap : cap style for line\n // lineDash\n // lineDashOffset :\n // lineJoin :\n // lineWidth :\n generateLabels(chart) {\n const datasets = chart.data.datasets;\n const {labels: {usePointStyle, pointStyle, textAlign, color, useBorderRadius, borderRadius}} = chart.legend.options;\n\n return chart._getSortedDatasetMetas().map((meta) => {\n const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);\n const borderWidth = toPadding(style.borderWidth);\n\n return {\n text: datasets[meta.index].label,\n fillStyle: style.backgroundColor,\n fontColor: color,\n hidden: !meta.visible,\n lineCap: style.borderCapStyle,\n lineDash: style.borderDash,\n lineDashOffset: style.borderDashOffset,\n lineJoin: style.borderJoinStyle,\n lineWidth: (borderWidth.width + borderWidth.height) / 4,\n strokeStyle: style.borderColor,\n pointStyle: pointStyle || style.pointStyle,\n rotation: style.rotation,\n textAlign: textAlign || style.textAlign,\n borderRadius: useBorderRadius && (borderRadius || style.borderRadius),\n\n // Below is extra data used for toggling the datasets\n datasetIndex: meta.index\n };\n }, this);\n }\n },\n\n title: {\n color: (ctx) => ctx.chart.options.color,\n display: false,\n position: 'center',\n text: '',\n }\n },\n\n descriptors: {\n _scriptable: (name) => !name.startsWith('on'),\n labels: {\n _scriptable: (name) => !['generateLabels', 'filter', 'sort'].includes(name),\n }\n },\n};\n","import Element from '../core/core.element.js';\nimport layouts from '../core/core.layouts.js';\nimport {PI, isArray, toPadding, toFont} from '../helpers/index.js';\nimport {_toLeftRightCenter, _alignStartEnd} from '../helpers/helpers.extras.js';\nimport {renderText} from '../helpers/helpers.canvas.js';\n\nexport class Title extends Element {\n /**\n\t * @param {{ ctx: any; options: any; chart: any; }} config\n\t */\n constructor(config) {\n super();\n\n this.chart = config.chart;\n this.options = config.options;\n this.ctx = config.ctx;\n this._padding = undefined;\n this.top = undefined;\n this.bottom = undefined;\n this.left = undefined;\n this.right = undefined;\n this.width = undefined;\n this.height = undefined;\n this.position = undefined;\n this.weight = undefined;\n this.fullSize = undefined;\n }\n\n update(maxWidth, maxHeight) {\n const opts = this.options;\n\n this.left = 0;\n this.top = 0;\n\n if (!opts.display) {\n this.width = this.height = this.right = this.bottom = 0;\n return;\n }\n\n this.width = this.right = maxWidth;\n this.height = this.bottom = maxHeight;\n\n const lineCount = isArray(opts.text) ? opts.text.length : 1;\n this._padding = toPadding(opts.padding);\n const textSize = lineCount * toFont(opts.font).lineHeight + this._padding.height;\n\n if (this.isHorizontal()) {\n this.height = textSize;\n } else {\n this.width = textSize;\n }\n }\n\n isHorizontal() {\n const pos = this.options.position;\n return pos === 'top' || pos === 'bottom';\n }\n\n _drawArgs(offset) {\n const {top, left, bottom, right, options} = this;\n const align = options.align;\n let rotation = 0;\n let maxWidth, titleX, titleY;\n\n if (this.isHorizontal()) {\n titleX = _alignStartEnd(align, left, right);\n titleY = top + offset;\n maxWidth = right - left;\n } else {\n if (options.position === 'left') {\n titleX = left + offset;\n titleY = _alignStartEnd(align, bottom, top);\n rotation = PI * -0.5;\n } else {\n titleX = right - offset;\n titleY = _alignStartEnd(align, top, bottom);\n rotation = PI * 0.5;\n }\n maxWidth = bottom - top;\n }\n return {titleX, titleY, maxWidth, rotation};\n }\n\n draw() {\n const ctx = this.ctx;\n const opts = this.options;\n\n if (!opts.display) {\n return;\n }\n\n const fontOpts = toFont(opts.font);\n const lineHeight = fontOpts.lineHeight;\n const offset = lineHeight / 2 + this._padding.top;\n const {titleX, titleY, maxWidth, rotation} = this._drawArgs(offset);\n\n renderText(ctx, opts.text, 0, 0, fontOpts, {\n color: opts.color,\n maxWidth,\n rotation,\n textAlign: _toLeftRightCenter(opts.align),\n textBaseline: 'middle',\n translation: [titleX, titleY],\n });\n }\n}\n\nfunction createTitle(chart, titleOpts) {\n const title = new Title({\n ctx: chart.ctx,\n options: titleOpts,\n chart\n });\n\n layouts.configure(chart, title, titleOpts);\n layouts.addBox(chart, title);\n chart.titleBlock = title;\n}\n\nexport default {\n id: 'title',\n\n /**\n\t * For tests\n\t * @private\n\t */\n _element: Title,\n\n start(chart, _args, options) {\n createTitle(chart, options);\n },\n\n stop(chart) {\n const titleBlock = chart.titleBlock;\n layouts.removeBox(chart, titleBlock);\n delete chart.titleBlock;\n },\n\n beforeUpdate(chart, _args, options) {\n const title = chart.titleBlock;\n layouts.configure(chart, title, options);\n title.options = options;\n },\n\n defaults: {\n align: 'center',\n display: false,\n font: {\n weight: 'bold',\n },\n fullSize: true,\n padding: 10,\n position: 'top',\n text: '',\n weight: 2000 // by default greater than legend (1000) to be above\n },\n\n defaultRoutes: {\n color: 'color'\n },\n\n descriptors: {\n _scriptable: true,\n _indexable: false,\n },\n};\n","import {Title} from './plugin.title.js';\nimport layouts from '../core/core.layouts.js';\n\nconst map = new WeakMap();\n\nexport default {\n id: 'subtitle',\n\n start(chart, _args, options) {\n const title = new Title({\n ctx: chart.ctx,\n options,\n chart\n });\n\n layouts.configure(chart, title, options);\n layouts.addBox(chart, title);\n map.set(chart, title);\n },\n\n stop(chart) {\n layouts.removeBox(chart, map.get(chart));\n map.delete(chart);\n },\n\n beforeUpdate(chart, _args, options) {\n const title = map.get(chart);\n layouts.configure(chart, title, options);\n title.options = options;\n },\n\n defaults: {\n align: 'center',\n display: false,\n font: {\n weight: 'normal',\n },\n fullSize: true,\n padding: 0,\n position: 'top',\n text: '',\n weight: 1500 // by default greater than legend (1000) and smaller than title (2000)\n },\n\n defaultRoutes: {\n color: 'color'\n },\n\n descriptors: {\n _scriptable: true,\n _indexable: false,\n },\n};\n","import Animations from '../core/core.animations.js';\nimport Element from '../core/core.element.js';\nimport {addRoundedRectPath} from '../helpers/helpers.canvas.js';\nimport {each, noop, isNullOrUndef, isArray, _elementsEqual, isObject} from '../helpers/helpers.core.js';\nimport {toFont, toPadding, toTRBLCorners} from '../helpers/helpers.options.js';\nimport {getRtlAdapter, overrideTextDirection, restoreTextDirection} from '../helpers/helpers.rtl.js';\nimport {distanceBetweenPoints, _limitValue} from '../helpers/helpers.math.js';\nimport {createContext, drawPoint} from '../helpers/index.js';\n\n/**\n * @typedef { import('../platform/platform.base.js').Chart } Chart\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n * @typedef { import('../types/index.js').ActiveElement } ActiveElement\n * @typedef { import('../core/core.interaction.js').InteractionItem } InteractionItem\n */\n\nconst positioners = {\n /**\n\t * Average mode places the tooltip at the average position of the elements shown\n\t */\n average(items) {\n if (!items.length) {\n return false;\n }\n\n let i, len;\n let x = 0;\n let y = 0;\n let count = 0;\n\n for (i = 0, len = items.length; i < len; ++i) {\n const el = items[i].element;\n if (el && el.hasValue()) {\n const pos = el.tooltipPosition();\n x += pos.x;\n y += pos.y;\n ++count;\n }\n }\n\n return {\n x: x / count,\n y: y / count\n };\n },\n\n /**\n\t * Gets the tooltip position nearest of the item nearest to the event position\n\t */\n nearest(items, eventPosition) {\n if (!items.length) {\n return false;\n }\n\n let x = eventPosition.x;\n let y = eventPosition.y;\n let minDistance = Number.POSITIVE_INFINITY;\n let i, len, nearestElement;\n\n for (i = 0, len = items.length; i < len; ++i) {\n const el = items[i].element;\n if (el && el.hasValue()) {\n const center = el.getCenterPoint();\n const d = distanceBetweenPoints(eventPosition, center);\n\n if (d < minDistance) {\n minDistance = d;\n nearestElement = el;\n }\n }\n }\n\n if (nearestElement) {\n const tp = nearestElement.tooltipPosition();\n x = tp.x;\n y = tp.y;\n }\n\n return {\n x,\n y\n };\n }\n};\n\n// Helper to push or concat based on if the 2nd parameter is an array or not\nfunction pushOrConcat(base, toPush) {\n if (toPush) {\n if (isArray(toPush)) {\n // base = base.concat(toPush);\n Array.prototype.push.apply(base, toPush);\n } else {\n base.push(toPush);\n }\n }\n\n return base;\n}\n\n/**\n * Returns array of strings split by newline\n * @param {*} str - The value to split by newline.\n * @returns {string|string[]} value if newline present - Returned from String split() method\n * @function\n */\nfunction splitNewlines(str) {\n if ((typeof str === 'string' || str instanceof String) && str.indexOf('\\n') > -1) {\n return str.split('\\n');\n }\n return str;\n}\n\n\n/**\n * Private helper to create a tooltip item model\n * @param {Chart} chart\n * @param {ActiveElement} item - {element, index, datasetIndex} to create the tooltip item for\n * @return new tooltip item\n */\nfunction createTooltipItem(chart, item) {\n const {element, datasetIndex, index} = item;\n const controller = chart.getDatasetMeta(datasetIndex).controller;\n const {label, value} = controller.getLabelAndValue(index);\n\n return {\n chart,\n label,\n parsed: controller.getParsed(index),\n raw: chart.data.datasets[datasetIndex].data[index],\n formattedValue: value,\n dataset: controller.getDataset(),\n dataIndex: index,\n datasetIndex,\n element\n };\n}\n\n/**\n * Get the size of the tooltip\n */\nfunction getTooltipSize(tooltip, options) {\n const ctx = tooltip.chart.ctx;\n const {body, footer, title} = tooltip;\n const {boxWidth, boxHeight} = options;\n const bodyFont = toFont(options.bodyFont);\n const titleFont = toFont(options.titleFont);\n const footerFont = toFont(options.footerFont);\n const titleLineCount = title.length;\n const footerLineCount = footer.length;\n const bodyLineItemCount = body.length;\n\n const padding = toPadding(options.padding);\n let height = padding.height;\n let width = 0;\n\n // Count of all lines in the body\n let combinedBodyLength = body.reduce((count, bodyItem) => count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);\n combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;\n\n if (titleLineCount) {\n height += titleLineCount * titleFont.lineHeight\n\t\t\t+ (titleLineCount - 1) * options.titleSpacing\n\t\t\t+ options.titleMarginBottom;\n }\n if (combinedBodyLength) {\n // Body lines may include some extra height depending on boxHeight\n const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;\n height += bodyLineItemCount * bodyLineHeight\n\t\t\t+ (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight\n\t\t\t+ (combinedBodyLength - 1) * options.bodySpacing;\n }\n if (footerLineCount) {\n height += options.footerMarginTop\n\t\t\t+ footerLineCount * footerFont.lineHeight\n\t\t\t+ (footerLineCount - 1) * options.footerSpacing;\n }\n\n // Title width\n let widthPadding = 0;\n const maxLineWidth = function(line) {\n width = Math.max(width, ctx.measureText(line).width + widthPadding);\n };\n\n ctx.save();\n\n ctx.font = titleFont.string;\n each(tooltip.title, maxLineWidth);\n\n // Body width\n ctx.font = bodyFont.string;\n each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);\n\n // Body lines may include some extra width due to the color box\n widthPadding = options.displayColors ? (boxWidth + 2 + options.boxPadding) : 0;\n each(body, (bodyItem) => {\n each(bodyItem.before, maxLineWidth);\n each(bodyItem.lines, maxLineWidth);\n each(bodyItem.after, maxLineWidth);\n });\n\n // Reset back to 0\n widthPadding = 0;\n\n // Footer width\n ctx.font = footerFont.string;\n each(tooltip.footer, maxLineWidth);\n\n ctx.restore();\n\n // Add padding\n width += padding.width;\n\n return {width, height};\n}\n\nfunction determineYAlign(chart, size) {\n const {y, height} = size;\n\n if (y < height / 2) {\n return 'top';\n } else if (y > (chart.height - height / 2)) {\n return 'bottom';\n }\n return 'center';\n}\n\nfunction doesNotFitWithAlign(xAlign, chart, options, size) {\n const {x, width} = size;\n const caret = options.caretSize + options.caretPadding;\n if (xAlign === 'left' && x + width + caret > chart.width) {\n return true;\n }\n\n if (xAlign === 'right' && x - width - caret < 0) {\n return true;\n }\n}\n\nfunction determineXAlign(chart, options, size, yAlign) {\n const {x, width} = size;\n const {width: chartWidth, chartArea: {left, right}} = chart;\n let xAlign = 'center';\n\n if (yAlign === 'center') {\n xAlign = x <= (left + right) / 2 ? 'left' : 'right';\n } else if (x <= width / 2) {\n xAlign = 'left';\n } else if (x >= chartWidth - width / 2) {\n xAlign = 'right';\n }\n\n if (doesNotFitWithAlign(xAlign, chart, options, size)) {\n xAlign = 'center';\n }\n\n return xAlign;\n}\n\n/**\n * Helper to get the alignment of a tooltip given the size\n */\nfunction determineAlignment(chart, options, size) {\n const yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size);\n\n return {\n xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign),\n yAlign\n };\n}\n\nfunction alignX(size, xAlign) {\n let {x, width} = size;\n if (xAlign === 'right') {\n x -= width;\n } else if (xAlign === 'center') {\n x -= (width / 2);\n }\n return x;\n}\n\nfunction alignY(size, yAlign, paddingAndSize) {\n // eslint-disable-next-line prefer-const\n let {y, height} = size;\n if (yAlign === 'top') {\n y += paddingAndSize;\n } else if (yAlign === 'bottom') {\n y -= height + paddingAndSize;\n } else {\n y -= (height / 2);\n }\n return y;\n}\n\n/**\n * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment\n */\nfunction getBackgroundPoint(options, size, alignment, chart) {\n const {caretSize, caretPadding, cornerRadius} = options;\n const {xAlign, yAlign} = alignment;\n const paddingAndSize = caretSize + caretPadding;\n const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(cornerRadius);\n\n let x = alignX(size, xAlign);\n const y = alignY(size, yAlign, paddingAndSize);\n\n if (yAlign === 'center') {\n if (xAlign === 'left') {\n x += paddingAndSize;\n } else if (xAlign === 'right') {\n x -= paddingAndSize;\n }\n } else if (xAlign === 'left') {\n x -= Math.max(topLeft, bottomLeft) + caretSize;\n } else if (xAlign === 'right') {\n x += Math.max(topRight, bottomRight) + caretSize;\n }\n\n return {\n x: _limitValue(x, 0, chart.width - size.width),\n y: _limitValue(y, 0, chart.height - size.height)\n };\n}\n\nfunction getAlignedX(tooltip, align, options) {\n const padding = toPadding(options.padding);\n\n return align === 'center'\n ? tooltip.x + tooltip.width / 2\n : align === 'right'\n ? tooltip.x + tooltip.width - padding.right\n : tooltip.x + padding.left;\n}\n\n/**\n * Helper to build before and after body lines\n */\nfunction getBeforeAfterBodyLines(callback) {\n return pushOrConcat([], splitNewlines(callback));\n}\n\nfunction createTooltipContext(parent, tooltip, tooltipItems) {\n return createContext(parent, {\n tooltip,\n tooltipItems,\n type: 'tooltip'\n });\n}\n\nfunction overrideCallbacks(callbacks, context) {\n const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;\n return override ? callbacks.override(override) : callbacks;\n}\n\nconst defaultCallbacks = {\n // Args are: (tooltipItems, data)\n beforeTitle: noop,\n title(tooltipItems) {\n if (tooltipItems.length > 0) {\n const item = tooltipItems[0];\n const labels = item.chart.data.labels;\n const labelCount = labels ? labels.length : 0;\n\n if (this && this.options && this.options.mode === 'dataset') {\n return item.dataset.label || '';\n } else if (item.label) {\n return item.label;\n } else if (labelCount > 0 && item.dataIndex < labelCount) {\n return labels[item.dataIndex];\n }\n }\n\n return '';\n },\n afterTitle: noop,\n\n // Args are: (tooltipItems, data)\n beforeBody: noop,\n\n // Args are: (tooltipItem, data)\n beforeLabel: noop,\n label(tooltipItem) {\n if (this && this.options && this.options.mode === 'dataset') {\n return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;\n }\n\n let label = tooltipItem.dataset.label || '';\n\n if (label) {\n label += ': ';\n }\n const value = tooltipItem.formattedValue;\n if (!isNullOrUndef(value)) {\n label += value;\n }\n return label;\n },\n labelColor(tooltipItem) {\n const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);\n const options = meta.controller.getStyle(tooltipItem.dataIndex);\n return {\n borderColor: options.borderColor,\n backgroundColor: options.backgroundColor,\n borderWidth: options.borderWidth,\n borderDash: options.borderDash,\n borderDashOffset: options.borderDashOffset,\n borderRadius: 0,\n };\n },\n labelTextColor() {\n return this.options.bodyColor;\n },\n labelPointStyle(tooltipItem) {\n const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);\n const options = meta.controller.getStyle(tooltipItem.dataIndex);\n return {\n pointStyle: options.pointStyle,\n rotation: options.rotation,\n };\n },\n afterLabel: noop,\n\n // Args are: (tooltipItems, data)\n afterBody: noop,\n\n // Args are: (tooltipItems, data)\n beforeFooter: noop,\n footer: noop,\n afterFooter: noop\n};\n\n/**\n * Invoke callback from object with context and arguments.\n * If callback returns `undefined`, then will be invoked default callback.\n * @param {Record} callbacks\n * @param {keyof typeof defaultCallbacks} name\n * @param {*} ctx\n * @param {*} arg\n * @returns {any}\n */\nfunction invokeCallbackWithFallback(callbacks, name, ctx, arg) {\n const result = callbacks[name].call(ctx, arg);\n\n if (typeof result === 'undefined') {\n return defaultCallbacks[name].call(ctx, arg);\n }\n\n return result;\n}\n\nexport class Tooltip extends Element {\n\n /**\n * @namespace Chart.Tooltip.positioners\n */\n static positioners = positioners;\n\n constructor(config) {\n super();\n\n this.opacity = 0;\n this._active = [];\n this._eventPosition = undefined;\n this._size = undefined;\n this._cachedAnimations = undefined;\n this._tooltipItems = [];\n this.$animations = undefined;\n this.$context = undefined;\n this.chart = config.chart;\n this.options = config.options;\n this.dataPoints = undefined;\n this.title = undefined;\n this.beforeBody = undefined;\n this.body = undefined;\n this.afterBody = undefined;\n this.footer = undefined;\n this.xAlign = undefined;\n this.yAlign = undefined;\n this.x = undefined;\n this.y = undefined;\n this.height = undefined;\n this.width = undefined;\n this.caretX = undefined;\n this.caretY = undefined;\n // TODO: V4, make this private, rename to `_labelStyles`, and combine with `labelPointStyles`\n // and `labelTextColors` to create a single variable\n this.labelColors = undefined;\n this.labelPointStyles = undefined;\n this.labelTextColors = undefined;\n }\n\n initialize(options) {\n this.options = options;\n this._cachedAnimations = undefined;\n this.$context = undefined;\n }\n\n /**\n\t * @private\n\t */\n _resolveAnimations() {\n const cached = this._cachedAnimations;\n\n if (cached) {\n return cached;\n }\n\n const chart = this.chart;\n const options = this.options.setContext(this.getContext());\n const opts = options.enabled && chart.options.animation && options.animations;\n const animations = new Animations(this.chart, opts);\n if (opts._cacheable) {\n this._cachedAnimations = Object.freeze(animations);\n }\n\n return animations;\n }\n\n /**\n\t * @protected\n\t */\n getContext() {\n return this.$context ||\n\t\t\t(this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems));\n }\n\n getTitle(context, options) {\n const {callbacks} = options;\n\n const beforeTitle = invokeCallbackWithFallback(callbacks, 'beforeTitle', this, context);\n const title = invokeCallbackWithFallback(callbacks, 'title', this, context);\n const afterTitle = invokeCallbackWithFallback(callbacks, 'afterTitle', this, context);\n\n let lines = [];\n lines = pushOrConcat(lines, splitNewlines(beforeTitle));\n lines = pushOrConcat(lines, splitNewlines(title));\n lines = pushOrConcat(lines, splitNewlines(afterTitle));\n\n return lines;\n }\n\n getBeforeBody(tooltipItems, options) {\n return getBeforeAfterBodyLines(\n invokeCallbackWithFallback(options.callbacks, 'beforeBody', this, tooltipItems)\n );\n }\n\n getBody(tooltipItems, options) {\n const {callbacks} = options;\n const bodyItems = [];\n\n each(tooltipItems, (context) => {\n const bodyItem = {\n before: [],\n lines: [],\n after: []\n };\n const scoped = overrideCallbacks(callbacks, context);\n pushOrConcat(bodyItem.before, splitNewlines(invokeCallbackWithFallback(scoped, 'beforeLabel', this, context)));\n pushOrConcat(bodyItem.lines, invokeCallbackWithFallback(scoped, 'label', this, context));\n pushOrConcat(bodyItem.after, splitNewlines(invokeCallbackWithFallback(scoped, 'afterLabel', this, context)));\n\n bodyItems.push(bodyItem);\n });\n\n return bodyItems;\n }\n\n getAfterBody(tooltipItems, options) {\n return getBeforeAfterBodyLines(\n invokeCallbackWithFallback(options.callbacks, 'afterBody', this, tooltipItems)\n );\n }\n\n // Get the footer and beforeFooter and afterFooter lines\n getFooter(tooltipItems, options) {\n const {callbacks} = options;\n\n const beforeFooter = invokeCallbackWithFallback(callbacks, 'beforeFooter', this, tooltipItems);\n const footer = invokeCallbackWithFallback(callbacks, 'footer', this, tooltipItems);\n const afterFooter = invokeCallbackWithFallback(callbacks, 'afterFooter', this, tooltipItems);\n\n let lines = [];\n lines = pushOrConcat(lines, splitNewlines(beforeFooter));\n lines = pushOrConcat(lines, splitNewlines(footer));\n lines = pushOrConcat(lines, splitNewlines(afterFooter));\n\n return lines;\n }\n\n /**\n\t * @private\n\t */\n _createItems(options) {\n const active = this._active;\n const data = this.chart.data;\n const labelColors = [];\n const labelPointStyles = [];\n const labelTextColors = [];\n let tooltipItems = [];\n let i, len;\n\n for (i = 0, len = active.length; i < len; ++i) {\n tooltipItems.push(createTooltipItem(this.chart, active[i]));\n }\n\n // If the user provided a filter function, use it to modify the tooltip items\n if (options.filter) {\n tooltipItems = tooltipItems.filter((element, index, array) => options.filter(element, index, array, data));\n }\n\n // If the user provided a sorting function, use it to modify the tooltip items\n if (options.itemSort) {\n tooltipItems = tooltipItems.sort((a, b) => options.itemSort(a, b, data));\n }\n\n // Determine colors for boxes\n each(tooltipItems, (context) => {\n const scoped = overrideCallbacks(options.callbacks, context);\n labelColors.push(invokeCallbackWithFallback(scoped, 'labelColor', this, context));\n labelPointStyles.push(invokeCallbackWithFallback(scoped, 'labelPointStyle', this, context));\n labelTextColors.push(invokeCallbackWithFallback(scoped, 'labelTextColor', this, context));\n });\n\n this.labelColors = labelColors;\n this.labelPointStyles = labelPointStyles;\n this.labelTextColors = labelTextColors;\n this.dataPoints = tooltipItems;\n return tooltipItems;\n }\n\n update(changed, replay) {\n const options = this.options.setContext(this.getContext());\n const active = this._active;\n let properties;\n let tooltipItems = [];\n\n if (!active.length) {\n if (this.opacity !== 0) {\n properties = {\n opacity: 0\n };\n }\n } else {\n const position = positioners[options.position].call(this, active, this._eventPosition);\n tooltipItems = this._createItems(options);\n\n this.title = this.getTitle(tooltipItems, options);\n this.beforeBody = this.getBeforeBody(tooltipItems, options);\n this.body = this.getBody(tooltipItems, options);\n this.afterBody = this.getAfterBody(tooltipItems, options);\n this.footer = this.getFooter(tooltipItems, options);\n\n const size = this._size = getTooltipSize(this, options);\n const positionAndSize = Object.assign({}, position, size);\n const alignment = determineAlignment(this.chart, options, positionAndSize);\n const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart);\n\n this.xAlign = alignment.xAlign;\n this.yAlign = alignment.yAlign;\n\n properties = {\n opacity: 1,\n x: backgroundPoint.x,\n y: backgroundPoint.y,\n width: size.width,\n height: size.height,\n caretX: position.x,\n caretY: position.y\n };\n }\n\n this._tooltipItems = tooltipItems;\n this.$context = undefined;\n\n if (properties) {\n this._resolveAnimations().update(this, properties);\n }\n\n if (changed && options.external) {\n options.external.call(this, {chart: this.chart, tooltip: this, replay});\n }\n }\n\n drawCaret(tooltipPoint, ctx, size, options) {\n const caretPosition = this.getCaretPosition(tooltipPoint, size, options);\n\n ctx.lineTo(caretPosition.x1, caretPosition.y1);\n ctx.lineTo(caretPosition.x2, caretPosition.y2);\n ctx.lineTo(caretPosition.x3, caretPosition.y3);\n }\n\n getCaretPosition(tooltipPoint, size, options) {\n const {xAlign, yAlign} = this;\n const {caretSize, cornerRadius} = options;\n const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(cornerRadius);\n const {x: ptX, y: ptY} = tooltipPoint;\n const {width, height} = size;\n let x1, x2, x3, y1, y2, y3;\n\n if (yAlign === 'center') {\n y2 = ptY + (height / 2);\n\n if (xAlign === 'left') {\n x1 = ptX;\n x2 = x1 - caretSize;\n\n // Left draws bottom -> top, this y1 is on the bottom\n y1 = y2 + caretSize;\n y3 = y2 - caretSize;\n } else {\n x1 = ptX + width;\n x2 = x1 + caretSize;\n\n // Right draws top -> bottom, thus y1 is on the top\n y1 = y2 - caretSize;\n y3 = y2 + caretSize;\n }\n\n x3 = x1;\n } else {\n if (xAlign === 'left') {\n x2 = ptX + Math.max(topLeft, bottomLeft) + (caretSize);\n } else if (xAlign === 'right') {\n x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize;\n } else {\n x2 = this.caretX;\n }\n\n if (yAlign === 'top') {\n y1 = ptY;\n y2 = y1 - caretSize;\n\n // Top draws left -> right, thus x1 is on the left\n x1 = x2 - caretSize;\n x3 = x2 + caretSize;\n } else {\n y1 = ptY + height;\n y2 = y1 + caretSize;\n\n // Bottom draws right -> left, thus x1 is on the right\n x1 = x2 + caretSize;\n x3 = x2 - caretSize;\n }\n y3 = y1;\n }\n return {x1, x2, x3, y1, y2, y3};\n }\n\n drawTitle(pt, ctx, options) {\n const title = this.title;\n const length = title.length;\n let titleFont, titleSpacing, i;\n\n if (length) {\n const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);\n\n pt.x = getAlignedX(this, options.titleAlign, options);\n\n ctx.textAlign = rtlHelper.textAlign(options.titleAlign);\n ctx.textBaseline = 'middle';\n\n titleFont = toFont(options.titleFont);\n titleSpacing = options.titleSpacing;\n\n ctx.fillStyle = options.titleColor;\n ctx.font = titleFont.string;\n\n for (i = 0; i < length; ++i) {\n ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);\n pt.y += titleFont.lineHeight + titleSpacing; // Line Height and spacing\n\n if (i + 1 === length) {\n pt.y += options.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing\n }\n }\n }\n }\n\n /**\n\t * @private\n\t */\n _drawColorBox(ctx, pt, i, rtlHelper, options) {\n const labelColor = this.labelColors[i];\n const labelPointStyle = this.labelPointStyles[i];\n const {boxHeight, boxWidth} = options;\n const bodyFont = toFont(options.bodyFont);\n const colorX = getAlignedX(this, 'left', options);\n const rtlColorX = rtlHelper.x(colorX);\n const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;\n const colorY = pt.y + yOffSet;\n\n if (options.usePointStyle) {\n const drawOptions = {\n radius: Math.min(boxWidth, boxHeight) / 2, // fit the circle in the box\n pointStyle: labelPointStyle.pointStyle,\n rotation: labelPointStyle.rotation,\n borderWidth: 1\n };\n // Recalculate x and y for drawPoint() because its expecting\n // x and y to be center of figure (instead of top left)\n const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;\n const centerY = colorY + boxHeight / 2;\n\n // Fill the point with white so that colours merge nicely if the opacity is < 1\n ctx.strokeStyle = options.multiKeyBackground;\n ctx.fillStyle = options.multiKeyBackground;\n drawPoint(ctx, drawOptions, centerX, centerY);\n\n // Draw the point\n ctx.strokeStyle = labelColor.borderColor;\n ctx.fillStyle = labelColor.backgroundColor;\n drawPoint(ctx, drawOptions, centerX, centerY);\n } else {\n // Border\n ctx.lineWidth = isObject(labelColor.borderWidth) ? Math.max(...Object.values(labelColor.borderWidth)) : (labelColor.borderWidth || 1); // TODO, v4 remove fallback\n ctx.strokeStyle = labelColor.borderColor;\n ctx.setLineDash(labelColor.borderDash || []);\n ctx.lineDashOffset = labelColor.borderDashOffset || 0;\n\n // Fill a white rect so that colours merge nicely if the opacity is < 1\n const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth);\n const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2);\n const borderRadius = toTRBLCorners(labelColor.borderRadius);\n\n if (Object.values(borderRadius).some(v => v !== 0)) {\n ctx.beginPath();\n ctx.fillStyle = options.multiKeyBackground;\n addRoundedRectPath(ctx, {\n x: outerX,\n y: colorY,\n w: boxWidth,\n h: boxHeight,\n radius: borderRadius,\n });\n ctx.fill();\n ctx.stroke();\n\n // Inner square\n ctx.fillStyle = labelColor.backgroundColor;\n ctx.beginPath();\n addRoundedRectPath(ctx, {\n x: innerX,\n y: colorY + 1,\n w: boxWidth - 2,\n h: boxHeight - 2,\n radius: borderRadius,\n });\n ctx.fill();\n } else {\n // Normal rect\n ctx.fillStyle = options.multiKeyBackground;\n ctx.fillRect(outerX, colorY, boxWidth, boxHeight);\n ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);\n // Inner square\n ctx.fillStyle = labelColor.backgroundColor;\n ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);\n }\n }\n\n // restore fillStyle\n ctx.fillStyle = this.labelTextColors[i];\n }\n\n drawBody(pt, ctx, options) {\n const {body} = this;\n const {bodySpacing, bodyAlign, displayColors, boxHeight, boxWidth, boxPadding} = options;\n const bodyFont = toFont(options.bodyFont);\n let bodyLineHeight = bodyFont.lineHeight;\n let xLinePadding = 0;\n\n const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);\n\n const fillLineOfText = function(line) {\n ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);\n pt.y += bodyLineHeight + bodySpacing;\n };\n\n const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);\n let bodyItem, textColor, lines, i, j, ilen, jlen;\n\n ctx.textAlign = bodyAlign;\n ctx.textBaseline = 'middle';\n ctx.font = bodyFont.string;\n\n pt.x = getAlignedX(this, bodyAlignForCalculation, options);\n\n // Before body lines\n ctx.fillStyle = options.bodyColor;\n each(this.beforeBody, fillLineOfText);\n\n xLinePadding = displayColors && bodyAlignForCalculation !== 'right'\n ? bodyAlign === 'center' ? (boxWidth / 2 + boxPadding) : (boxWidth + 2 + boxPadding)\n : 0;\n\n // Draw body lines now\n for (i = 0, ilen = body.length; i < ilen; ++i) {\n bodyItem = body[i];\n textColor = this.labelTextColors[i];\n\n ctx.fillStyle = textColor;\n each(bodyItem.before, fillLineOfText);\n\n lines = bodyItem.lines;\n // Draw Legend-like boxes if needed\n if (displayColors && lines.length) {\n this._drawColorBox(ctx, pt, i, rtlHelper, options);\n bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);\n }\n\n for (j = 0, jlen = lines.length; j < jlen; ++j) {\n fillLineOfText(lines[j]);\n // Reset for any lines that don't include colorbox\n bodyLineHeight = bodyFont.lineHeight;\n }\n\n each(bodyItem.after, fillLineOfText);\n }\n\n // Reset back to 0 for after body\n xLinePadding = 0;\n bodyLineHeight = bodyFont.lineHeight;\n\n // After body lines\n each(this.afterBody, fillLineOfText);\n pt.y -= bodySpacing; // Remove last body spacing\n }\n\n drawFooter(pt, ctx, options) {\n const footer = this.footer;\n const length = footer.length;\n let footerFont, i;\n\n if (length) {\n const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);\n\n pt.x = getAlignedX(this, options.footerAlign, options);\n pt.y += options.footerMarginTop;\n\n ctx.textAlign = rtlHelper.textAlign(options.footerAlign);\n ctx.textBaseline = 'middle';\n\n footerFont = toFont(options.footerFont);\n\n ctx.fillStyle = options.footerColor;\n ctx.font = footerFont.string;\n\n for (i = 0; i < length; ++i) {\n ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);\n pt.y += footerFont.lineHeight + options.footerSpacing;\n }\n }\n }\n\n drawBackground(pt, ctx, tooltipSize, options) {\n const {xAlign, yAlign} = this;\n const {x, y} = pt;\n const {width, height} = tooltipSize;\n const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(options.cornerRadius);\n\n ctx.fillStyle = options.backgroundColor;\n ctx.strokeStyle = options.borderColor;\n ctx.lineWidth = options.borderWidth;\n\n ctx.beginPath();\n ctx.moveTo(x + topLeft, y);\n if (yAlign === 'top') {\n this.drawCaret(pt, ctx, tooltipSize, options);\n }\n ctx.lineTo(x + width - topRight, y);\n ctx.quadraticCurveTo(x + width, y, x + width, y + topRight);\n if (yAlign === 'center' && xAlign === 'right') {\n this.drawCaret(pt, ctx, tooltipSize, options);\n }\n ctx.lineTo(x + width, y + height - bottomRight);\n ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height);\n if (yAlign === 'bottom') {\n this.drawCaret(pt, ctx, tooltipSize, options);\n }\n ctx.lineTo(x + bottomLeft, y + height);\n ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft);\n if (yAlign === 'center' && xAlign === 'left') {\n this.drawCaret(pt, ctx, tooltipSize, options);\n }\n ctx.lineTo(x, y + topLeft);\n ctx.quadraticCurveTo(x, y, x + topLeft, y);\n ctx.closePath();\n\n ctx.fill();\n\n if (options.borderWidth > 0) {\n ctx.stroke();\n }\n }\n\n /**\n\t * Update x/y animation targets when _active elements are animating too\n\t * @private\n\t */\n _updateAnimationTarget(options) {\n const chart = this.chart;\n const anims = this.$animations;\n const animX = anims && anims.x;\n const animY = anims && anims.y;\n if (animX || animY) {\n const position = positioners[options.position].call(this, this._active, this._eventPosition);\n if (!position) {\n return;\n }\n const size = this._size = getTooltipSize(this, options);\n const positionAndSize = Object.assign({}, position, this._size);\n const alignment = determineAlignment(chart, options, positionAndSize);\n const point = getBackgroundPoint(options, positionAndSize, alignment, chart);\n if (animX._to !== point.x || animY._to !== point.y) {\n this.xAlign = alignment.xAlign;\n this.yAlign = alignment.yAlign;\n this.width = size.width;\n this.height = size.height;\n this.caretX = position.x;\n this.caretY = position.y;\n this._resolveAnimations().update(this, point);\n }\n }\n }\n\n /**\n * Determine if the tooltip will draw anything\n * @returns {boolean} True if the tooltip will render\n */\n _willRender() {\n return !!this.opacity;\n }\n\n draw(ctx) {\n const options = this.options.setContext(this.getContext());\n let opacity = this.opacity;\n\n if (!opacity) {\n return;\n }\n\n this._updateAnimationTarget(options);\n\n const tooltipSize = {\n width: this.width,\n height: this.height\n };\n const pt = {\n x: this.x,\n y: this.y\n };\n\n // IE11/Edge does not like very small opacities, so snap to 0\n opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;\n\n const padding = toPadding(options.padding);\n\n // Truthy/falsey value for empty tooltip\n const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length;\n\n if (options.enabled && hasTooltipContent) {\n ctx.save();\n ctx.globalAlpha = opacity;\n\n // Draw Background\n this.drawBackground(pt, ctx, tooltipSize, options);\n\n overrideTextDirection(ctx, options.textDirection);\n\n pt.y += padding.top;\n\n // Titles\n this.drawTitle(pt, ctx, options);\n\n // Body\n this.drawBody(pt, ctx, options);\n\n // Footer\n this.drawFooter(pt, ctx, options);\n\n restoreTextDirection(ctx, options.textDirection);\n\n ctx.restore();\n }\n }\n\n /**\n\t * Get active elements in the tooltip\n\t * @returns {Array} Array of elements that are active in the tooltip\n\t */\n getActiveElements() {\n return this._active || [];\n }\n\n /**\n\t * Set active elements in the tooltip\n\t * @param {array} activeElements Array of active datasetIndex/index pairs.\n\t * @param {object} eventPosition Synthetic event position used in positioning\n\t */\n setActiveElements(activeElements, eventPosition) {\n const lastActive = this._active;\n const active = activeElements.map(({datasetIndex, index}) => {\n const meta = this.chart.getDatasetMeta(datasetIndex);\n\n if (!meta) {\n throw new Error('Cannot find a dataset at index ' + datasetIndex);\n }\n\n return {\n datasetIndex,\n element: meta.data[index],\n index,\n };\n });\n const changed = !_elementsEqual(lastActive, active);\n const positionChanged = this._positionChanged(active, eventPosition);\n\n if (changed || positionChanged) {\n this._active = active;\n this._eventPosition = eventPosition;\n this._ignoreReplayEvents = true;\n this.update(true);\n }\n }\n\n /**\n\t * Handle an event\n\t * @param {ChartEvent} e - The event to handle\n\t * @param {boolean} [replay] - This is a replayed event (from update)\n\t * @param {boolean} [inChartArea] - The event is inside chartArea\n\t * @returns {boolean} true if the tooltip changed\n\t */\n handleEvent(e, replay, inChartArea = true) {\n if (replay && this._ignoreReplayEvents) {\n return false;\n }\n this._ignoreReplayEvents = false;\n\n const options = this.options;\n const lastActive = this._active || [];\n const active = this._getActiveElements(e, lastActive, replay, inChartArea);\n\n // When there are multiple items shown, but the tooltip position is nearest mode\n // an update may need to be made because our position may have changed even though\n // the items are the same as before.\n const positionChanged = this._positionChanged(active, e);\n\n // Remember Last Actives\n const changed = replay || !_elementsEqual(active, lastActive) || positionChanged;\n\n // Only handle target event on tooltip change\n if (changed) {\n this._active = active;\n\n if (options.enabled || options.external) {\n this._eventPosition = {\n x: e.x,\n y: e.y\n };\n\n this.update(true, replay);\n }\n }\n\n return changed;\n }\n\n /**\n\t * Helper for determining the active elements for event\n\t * @param {ChartEvent} e - The event to handle\n\t * @param {InteractionItem[]} lastActive - Previously active elements\n\t * @param {boolean} [replay] - This is a replayed event (from update)\n\t * @param {boolean} [inChartArea] - The event is inside chartArea\n\t * @returns {InteractionItem[]} - Active elements\n\t * @private\n\t */\n _getActiveElements(e, lastActive, replay, inChartArea) {\n const options = this.options;\n\n if (e.type === 'mouseout') {\n return [];\n }\n\n if (!inChartArea) {\n // Let user control the active elements outside chartArea. Eg. using Legend.\n // But make sure that active elements are still valid.\n return lastActive.filter(i =>\n this.chart.data.datasets[i.datasetIndex] &&\n this.chart.getDatasetMeta(i.datasetIndex).controller.getParsed(i.index) !== undefined\n );\n }\n\n // Find Active Elements for tooltips\n const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay);\n\n if (options.reverse) {\n active.reverse();\n }\n\n return active;\n }\n\n /**\n\t * Determine if the active elements + event combination changes the\n\t * tooltip position\n\t * @param {array} active - Active elements\n\t * @param {ChartEvent} e - Event that triggered the position change\n\t * @returns {boolean} True if the position has changed\n\t */\n _positionChanged(active, e) {\n const {caretX, caretY, options} = this;\n const position = positioners[options.position].call(this, active, e);\n return position !== false && (caretX !== position.x || caretY !== position.y);\n }\n}\n\nexport default {\n id: 'tooltip',\n _element: Tooltip,\n positioners,\n\n afterInit(chart, _args, options) {\n if (options) {\n chart.tooltip = new Tooltip({chart, options});\n }\n },\n\n beforeUpdate(chart, _args, options) {\n if (chart.tooltip) {\n chart.tooltip.initialize(options);\n }\n },\n\n reset(chart, _args, options) {\n if (chart.tooltip) {\n chart.tooltip.initialize(options);\n }\n },\n\n afterDraw(chart) {\n const tooltip = chart.tooltip;\n\n if (tooltip && tooltip._willRender()) {\n const args = {\n tooltip\n };\n\n if (chart.notifyPlugins('beforeTooltipDraw', {...args, cancelable: true}) === false) {\n return;\n }\n\n tooltip.draw(chart.ctx);\n\n chart.notifyPlugins('afterTooltipDraw', args);\n }\n },\n\n afterEvent(chart, args) {\n if (chart.tooltip) {\n // If the event is replayed from `update`, we should evaluate with the final positions.\n const useFinalPosition = args.replay;\n if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) {\n // notify chart about the change, so it will render\n args.changed = true;\n }\n }\n },\n\n defaults: {\n enabled: true,\n external: null,\n position: 'average',\n backgroundColor: 'rgba(0,0,0,0.8)',\n titleColor: '#fff',\n titleFont: {\n weight: 'bold',\n },\n titleSpacing: 2,\n titleMarginBottom: 6,\n titleAlign: 'left',\n bodyColor: '#fff',\n bodySpacing: 2,\n bodyFont: {\n },\n bodyAlign: 'left',\n footerColor: '#fff',\n footerSpacing: 2,\n footerMarginTop: 6,\n footerFont: {\n weight: 'bold',\n },\n footerAlign: 'left',\n padding: 6,\n caretPadding: 2,\n caretSize: 5,\n cornerRadius: 6,\n boxHeight: (ctx, opts) => opts.bodyFont.size,\n boxWidth: (ctx, opts) => opts.bodyFont.size,\n multiKeyBackground: '#fff',\n displayColors: true,\n boxPadding: 0,\n borderColor: 'rgba(0,0,0,0)',\n borderWidth: 0,\n animation: {\n duration: 400,\n easing: 'easeOutQuart',\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'width', 'height', 'caretX', 'caretY'],\n },\n opacity: {\n easing: 'linear',\n duration: 200\n }\n },\n callbacks: defaultCallbacks\n },\n\n defaultRoutes: {\n bodyFont: 'font',\n footerFont: 'font',\n titleFont: 'font'\n },\n\n descriptors: {\n _scriptable: (name) => name !== 'filter' && name !== 'itemSort' && name !== 'external',\n _indexable: false,\n callbacks: {\n _scriptable: false,\n _indexable: false,\n },\n animation: {\n _fallback: false\n },\n animations: {\n _fallback: 'animation'\n }\n },\n\n // Resolve additionally from `interaction` options and defaults.\n additionalOptionScopes: ['interaction']\n};\n","// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-nocheck\n\n/**\n * @namespace Chart\n */\nimport Chart from './core/core.controller.js';\n\nimport * as helpers from './helpers/index.js';\nimport _adapters from './core/core.adapters.js';\nimport Animation from './core/core.animation.js';\nimport animator from './core/core.animator.js';\nimport Animations from './core/core.animations.js';\nimport * as controllers from './controllers/index.js';\nimport DatasetController from './core/core.datasetController.js';\nimport Element from './core/core.element.js';\nimport * as elements from './elements/index.js';\nimport Interaction from './core/core.interaction.js';\nimport layouts from './core/core.layouts.js';\nimport * as platforms from './platform/index.js';\nimport * as plugins from './plugins/index.js';\nimport registry from './core/core.registry.js';\nimport Scale from './core/core.scale.js';\nimport * as scales from './scales/index.js';\nimport Ticks from './core/core.ticks.js';\n\n// Register built-ins\nChart.register(controllers, scales, elements, plugins);\n\nChart.helpers = {...helpers};\nChart._adapters = _adapters;\nChart.Animation = Animation;\nChart.Animations = Animations;\nChart.animator = animator;\nChart.controllers = registry.controllers.items;\nChart.DatasetController = DatasetController;\nChart.Element = Element;\nChart.elements = elements;\nChart.Interaction = Interaction;\nChart.layouts = layouts;\nChart.platforms = platforms;\nChart.Scale = Scale;\nChart.Ticks = Ticks;\n\n// Compatibility with ESM extensions\nObject.assign(Chart, controllers, scales, elements, plugins, platforms);\nChart.Chart = Chart;\n\nif (typeof window !== 'undefined') {\n window.Chart = Chart;\n}\n\nexport default Chart;\n\n"],"names":["noop","uid","id","isNullOrUndef","value","isArray","Array","type","Object","prototype","toString","call","slice","isObject","isNumberFinite","Number","isFinite","finiteOrDefault","defaultValue","valueOrDefault","toPercentage","dimension","endsWith","parseFloat","toDimension","callback","fn","args","thisArg","apply","each","loopable","reverse","i","len","keys","length","_elementsEqual","a0","a1","ilen","v0","v1","datasetIndex","index","clone","source","map","target","create","klen","k","isValidKey","key","indexOf","_merger","options","tval","sval","merge","sources","merger","current","mergeIf","_mergerIf","hasOwnProperty","keyResolvers","v","x","o","y","_splitKey","parts","split","tmp","part","push","resolveObjectKey","obj","resolver","_getKeyResolver","_capitalize","str","charAt","toUpperCase","defined","isFunction","setsEqual","a","b","size","item","has","_isClickEvent","e","PI","Math","TAU","PITAU","INFINITY","POSITIVE_INFINITY","RAD_PER_DEG","HALF_PI","QUARTER_PI","TWO_THIRDS_PI","log10","sign","almostEquals","epsilon","abs","niceNum","range","roundedRange","round","niceRange","pow","floor","fraction","_factorize","result","sqrt","sort","pop","isNumber","n","isNaN","almostWhole","rounded","_setMinAndMaxByKey","array","property","min","max","toRadians","degrees","toDegrees","radians","_decimalPlaces","isFiniteNumber","p","getAngleFromPoint","centrePoint","anglePoint","distanceFromXCenter","distanceFromYCenter","radialDistanceFromCenter","angle","atan2","distance","distanceBetweenPoints","pt1","pt2","_angleDiff","_normalizeAngle","_angleBetween","start","end","sameAngleIsFullCircle","s","angleToStart","angleToEnd","startToAngle","endToAngle","_limitValue","_int16Range","_isBetween","_lookup","table","cmp","mid","hi","lo","_lookupByKey","last","ti","_rlookupByKey","_filterBetween","values","arrayEvents","listenArrayEvents","listener","_chartjs","listeners","defineProperty","configurable","enumerable","forEach","method","base","res","this","object","unlistenArrayEvents","stub","splice","_arrayUnique","items","set","Set","from","requestAnimFrame","window","requestAnimationFrame","throttled","argsToUse","ticking","debounce","delay","timeout","clearTimeout","setTimeout","_toLeftRightCenter","align","_alignStartEnd","_textX","left","right","rtl","_getStartAndCountOfVisiblePoints","meta","points","animationsDisabled","pointCount","count","_sorted","iScale","_parsed","axis","minDefined","maxDefined","getUserBounds","getPixelForValue","_scaleRangesChanged","xScale","yScale","_scaleRanges","newRanges","xmin","xmax","ymin","ymax","changed","assign","Animator","constructor","_request","_charts","Map","_running","_lastDate","undefined","_notify","chart","anims","date","callbacks","numSteps","duration","initial","currentStep","_refresh","_update","Date","now","remaining","running","draw","_active","_total","tick","_getAnims","charts","get","complete","progress","listen","event","cb","add","reduce","acc","cur","_duration","stop","cancel","remove","delete","animator","lim","l","h","p2b","n2b","b2n","n2p","map$1","A","B","C","D","E","F","c","d","f","hex","h1","h2","eq","hexString","r","g","isShort","alpha","HUE_RE","hsl2rgbn","hsv2rgbn","hwb2rgbn","w","rgb","rgb2hsl","hueValue","calln","hsl2rgb","hue","hueParse","m","exec","p1","p2","hwb2rgb","hsv2rgb","Z","Y","X","W","V","U","T","S","R","Q","P","O","N","M","L","K","G","H","I","J","names$1","OiceXe","antiquewEte","aqua","aquamarRe","azuY","beige","bisque","black","blanKedOmond","Xe","XeviTet","bPwn","burlywood","caMtXe","KartYuse","KocTate","cSO","cSnflowerXe","cSnsilk","crimson","cyan","xXe","xcyan","xgTMnPd","xWay","xgYF","xgYy","xkhaki","xmagFta","xTivegYF","xSange","xScEd","xYd","xsOmon","xsHgYF","xUXe","xUWay","xUgYy","xQe","xviTet","dAppRk","dApskyXe","dimWay","dimgYy","dodgerXe","fiYbrick","flSOwEte","foYstWAn","fuKsia","gaRsbSo","ghostwEte","gTd","gTMnPd","Way","gYF","gYFLw","gYy","honeyMw","hotpRk","RdianYd","Rdigo","ivSy","khaki","lavFMr","lavFMrXsh","lawngYF","NmoncEffon","ZXe","ZcSO","Zcyan","ZgTMnPdLw","ZWay","ZgYF","ZgYy","ZpRk","ZsOmon","ZsHgYF","ZskyXe","ZUWay","ZUgYy","ZstAlXe","ZLw","lime","limegYF","lRF","magFta","maPon","VaquamarRe","VXe","VScEd","VpurpN","VsHgYF","VUXe","VsprRggYF","VQe","VviTetYd","midnightXe","mRtcYam","mistyPse","moccasR","navajowEte","navy","Tdlace","Tive","TivedBb","Sange","SangeYd","ScEd","pOegTMnPd","pOegYF","pOeQe","pOeviTetYd","papayawEp","pHKpuff","peru","pRk","plum","powMrXe","purpN","YbeccapurpN","Yd","Psybrown","PyOXe","saddNbPwn","sOmon","sandybPwn","sHgYF","sHshell","siFna","silver","skyXe","UXe","UWay","UgYy","snow","sprRggYF","stAlXe","tan","teO","tEstN","tomato","Qe","viTet","JHt","wEte","wEtesmoke","Lw","LwgYF","names","nameParse","unpacked","tkeys","j","ok","nk","replace","parseInt","unpack","transparent","toLowerCase","RGB_RE","to","modHSL","ratio","proto","fromObject","input","functionParse","rgbParse","Color","ret","_rgb","_valid","valid","rgbString","hslString","mix","color","weight","c1","c2","w2","w1","interpolate","t","rgb1","rgb2","clearer","greyscale","val","opaquer","negate","lighten","darken","saturate","desaturate","rotate","deg","isPatternOrGradient","getHoverColor","numbers","colors","intlCache","formatNumber","num","locale","cacheKey","JSON","stringify","formatter","Intl","NumberFormat","getNumberFormat","format","formatters","numeric","tickValue","ticks","notation","delta","maxTick","calculateDelta","logDelta","numDecimal","minimumFractionDigits","maximumFractionDigits","logarithmic","remain","significand","includes","Ticks","overrides","descriptors","getScope","node","root","scope","Defaults","_descriptors","_appliers","animation","backgroundColor","borderColor","datasets","devicePixelRatio","context","platform","getDevicePixelRatio","elements","events","font","family","style","lineHeight","hover","hoverBackgroundColor","ctx","hoverBorderColor","hoverColor","indexAxis","interaction","mode","intersect","includeInvisible","maintainAspectRatio","onHover","onClick","parsing","plugins","responsive","scale","scales","showLine","drawActiveElementsOnTop","describe","override","route","name","targetScope","targetName","scopeObject","targetScopeObject","privateName","defineProperties","writable","local","appliers","defaults","_scriptable","startsWith","_indexable","_fallback","easing","loop","properties","active","resize","show","animations","visible","hide","autoPadding","padding","top","bottom","display","offset","beginAtZero","bounds","clip","grace","grid","lineWidth","drawOnChartArea","drawTicks","tickLength","tickWidth","_ctx","tickColor","border","dash","dashOffset","width","title","text","minRotation","maxRotation","mirror","textStrokeWidth","textStrokeColor","autoSkip","autoSkipPadding","labelOffset","minor","major","crossAlign","showLabelBackdrop","backdropColor","backdropPadding","_isDomSupported","document","_getParentNode","domNode","parent","parentNode","host","parseMaxStyle","styleValue","parentProperty","valueInPixels","getComputedStyle","element","ownerDocument","defaultView","getStyle","el","getPropertyValue","positions","getPositionedStyle","styles","suffix","pos","height","useOffsetPos","shadowRoot","getRelativePosition","canvas","currentDevicePixelRatio","borderBox","boxSizing","paddings","borders","box","touches","offsetX","offsetY","rect","getBoundingClientRect","clientX","clientY","getCanvasPosition","xOffset","yOffset","round1","getMaximumSize","bbWidth","bbHeight","aspectRatio","margins","maxWidth","maxHeight","containerSize","container","containerStyle","containerBorder","containerPadding","clientWidth","clientHeight","getContainerSize","retinaScale","forceRatio","forceStyle","pixelRatio","deviceHeight","deviceWidth","setTransform","supportsEventListenerOptions","passiveSupported","passive","addEventListener","removeEventListener","readUsedSize","matches","match","toFontString","_measureText","data","gc","longest","string","textWidth","measureText","_longestText","arrayOfThings","cache","garbageCollect","save","jlen","thing","nestedThing","restore","gcLen","_alignPixel","pixel","halfWidth","clearCanvas","getContext","resetTransform","clearRect","drawPoint","drawPointLegend","cornerRadius","xOffsetW","yOffsetW","pointStyle","rotation","radius","rad","translate","drawImage","beginPath","ellipse","arc","closePath","moveTo","sin","cos","lineTo","SQRT1_2","fill","borderWidth","stroke","_isPointInArea","point","area","margin","clipArea","unclipArea","_steppedLineTo","previous","flip","midpoint","_bezierCurveTo","bezierCurveTo","cp1x","cp2x","cp1y","cp2y","decorateText","line","opts","strikethrough","underline","metrics","actualBoundingBoxLeft","actualBoundingBoxRight","actualBoundingBoxAscent","actualBoundingBoxDescent","yDecoration","strokeStyle","fillStyle","decorationWidth","drawBackdrop","oldColor","fillRect","renderText","lines","strokeWidth","strokeColor","translation","textAlign","textBaseline","setRenderOpts","backdrop","strokeText","fillText","addRoundedRectPath","topLeft","bottomLeft","bottomRight","topRight","_createResolver","scopes","prefixes","rootScopes","fallback","getTarget","finalRootScopes","_resolve","Symbol","toStringTag","_cacheable","_scopes","_rootScopes","_getTarget","Proxy","deleteProperty","prop","_keys","_cached","proxy","prefix","readKey","needsSubResolver","createSubResolver","_resolveWithPrefixes","getOwnPropertyDescriptor","Reflect","getPrototypeOf","getKeysFromAllScopes","ownKeys","storage","_storage","_attachContext","subProxy","descriptorDefaults","_proxy","_context","_subProxy","_stack","setContext","receiver","isScriptable","getValue","Error","join","_resolveScriptable","isIndexable","arr","filter","_resolveArray","_resolveWithContext","allKeys","scriptable","indexable","_allKeys","resolve","resolveFallback","addScopes","parentScopes","parentFallback","allScopes","addScopesFromKey","subGetTarget","resolveKeysFromAllScopes","_parseObjectDataRadialScale","_parsing","parsed","parse","EPSILON","getPoint","skip","getValueAxis","splineCurve","firstPoint","middlePoint","afterPoint","next","d01","d12","s01","s12","fa","fb","splineCurveMonotone","valueAxis","pointsLen","deltaK","mK","pointBefore","pointCurrent","pointAfter","slopeDelta","alphaK","betaK","tauK","squaredMagnitude","monotoneAdjust","iPixel","vPixel","monotoneCompute","capControlPoint","pt","_updateBezierControlPoints","controlPoints","spanGaps","cubicInterpolationMode","prev","tension","capBezierPoints","inArea","inAreaPrev","inAreaNext","atEdge","elasticIn","elasticOut","effects","linear","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","easeOutCubic","easeInOutCubic","easeInQuart","easeOutQuart","easeInOutQuart","easeInQuint","easeOutQuint","easeInOutQuint","easeInSine","easeOutSine","easeInOutSine","easeInExpo","easeOutExpo","easeInOutExpo","easeInCirc","easeOutCirc","easeInOutCirc","easeInElastic","easeOutElastic","easeInOutElastic","easeInBack","easeOutBack","easeInOutBack","easeInBounce","easeOutBounce","easeInOutBounce","_pointInLine","_steppedInterpolation","_bezierInterpolation","cp1","cp2","LINE_HEIGHT","FONT_STYLE","toLineHeight","numberOrZero","_readValueToProps","props","objProps","read","toTRBL","toTRBLCorners","toPadding","toFont","console","warn","inputs","info","cacheable","_addGrace","minmax","change","keepZero","createContext","parentContext","getRtlAdapter","rectX","setWidth","xPlus","leftForLtr","itemWidth","getRightToLeftAdapter","_itemWidth","overrideTextDirection","direction","original","getPropertyPriority","setProperty","prevTextDirection","restoreTextDirection","propertyFn","between","compare","normalize","normalizeSegment","_boundSegment","segment","startBound","endBound","getSegment","prevValue","inside","subStart","shouldStart","shouldStop","_boundSegments","segments","sub","_computeSegments","segmentOptions","_loop","findStartAndEnd","splitByStyles","solidSegments","_fullLoop","chartContext","_chart","baseStyle","readStyle","_datasetIndex","prevStyle","addStyle","st","dir","p0","p0DataIndex","p1DataIndex","styleChanged","doSplitByStyles","borderCapStyle","borderDash","borderDashOffset","borderJoinStyle","replacer","pixelSize","fontStyle","fontFamily","binarySearch","metaset","controller","_cachedMeta","lookupMethod","_reversePixels","_sharedOptions","getRange","evaluateInteractionItems","position","handler","metasets","getSortedVisibleDatasetMetas","getIntersectItems","useFinalPosition","isPointInArea","chartArea","inRange","getNearestCartesianItems","distanceMetric","useX","useY","deltaX","deltaY","getDistanceMetricForAxis","minDistance","center","getCenterPoint","getNearestItems","startAngle","endAngle","getProps","getNearestRadialItems","getAxisItems","rangeMethod","intersectsItem","Interaction","modes","dataset","getDatasetMeta","nearest","STATIC_POSITIONS","filterByPosition","filterDynamicPositionByAxis","sortByWeight","setLayoutDims","layouts","params","stacks","wrap","stack","stackWeight","placed","buildStacks","vBoxMaxWidth","hBoxMaxHeight","layout","fullSize","factor","horizontal","availableWidth","availableHeight","getCombinedMax","maxPadding","updateMaxPadding","boxPadding","updateDims","getPadding","newWidth","outerWidth","newHeight","outerHeight","widthChanged","heightChanged","same","other","getMargins","marginForPositions","fitBoxes","boxes","refitBoxes","refit","update","setBoxDims","placeBoxes","userPadding","addBox","_layers","z","removeBox","layoutItem","configure","minPadding","layoutBoxes","isHorizontal","wrapBoxes","centerHorizontal","centerVertical","leftAndTop","concat","rightAndBottom","vertical","buildLayoutBoxes","verticalBoxes","horizontalBoxes","beforeLayout","visibleVerticalBoxCount","total","freeze","updatePos","handleMaxPadding","BasePlatform","acquireContext","releaseContext","isAttached","updateConfig","config","BasicPlatform","EXPANDO_KEY","EVENT_TYPES","touchstart","touchmove","touchend","pointerenter","pointerdown","pointermove","pointerup","pointerleave","pointerout","isNullOrEmpty","eventListenerOptions","removeListener","nodeListContains","nodeList","contains","createAttachObserver","observer","MutationObserver","entries","trigger","entry","addedNodes","removedNodes","observe","childList","subtree","createDetachObserver","drpListeningCharts","oldDevicePixelRatio","onWindowResize","dpr","createResizeObserver","ResizeObserver","contentRect","listenDevicePixelRatioChanges","releaseObserver","disconnect","unlistenDevicePixelRatioChanges","createProxyAndListen","native","fromNativeEvent","addListener","DomPlatform","renderHeight","getAttribute","renderWidth","displayWidth","displayHeight","initCanvas","removeAttribute","setAttribute","proxies","$proxies","attach","detach","isConnected","_detectPlatform","OffscreenCanvas","interpolators","boolean","c0","helpersColor","number","Animation","cfg","currentValue","_fn","_easing","_start","_target","_prop","_from","_to","_promises","elapsed","wait","promises","Promise","rej","resolved","Animations","_properties","animationOptions","animatedProps","getOwnPropertyNames","option","_animateOptions","newOptions","$shared","$animations","resolveTargetOptions","_createAnimations","anim","all","awaitAll","then","scaleClip","allowedOverflow","getSortedDatasetIndices","filterVisible","_getSortedDatasetMetas","applyStack","dsIndex","singleMode","otherValue","isStacked","stacked","getOrCreateStack","stackKey","indexValue","subStack","getLastIndexInStack","vScale","positive","getMatchingVisibleMetas","updateStacks","_stacks","iAxis","vAxis","indexScale","valueScale","getStackKey","_top","_bottom","_visualValues","getFirstScaleId","shift","clearStacks","isDirectUpdateMode","cloneIfNotShared","cached","shared","DatasetController","static","_cachedDataOpts","getMeta","_type","_data","_objectData","_drawStart","_drawCount","enableOptionSharing","supportsDecimation","$context","_syncList","datasetElementType","dataElementType","initialize","linkScales","_stacked","addElements","isPluginEnabled","updateIndex","getDataset","chooseId","xid","xAxisID","yid","yAxisID","rid","rAxisID","iid","iAxisID","vid","vAxisID","getScaleForId","rScale","scaleID","_getOtherScale","reset","_destroy","_dataCheck","adata","convertObjectDataToArray","isExtensible","buildOrUpdateElements","resetNewElements","stackChanged","oldStacked","_resyncElements","scopeKeys","datasetScopeKeys","getOptionScopes","createResolver","sorted","parseArrayData","parseObjectData","parsePrimitiveData","isNotInOrderComparedToPrev","labels","getLabels","singleScale","xAxisKey","yAxisKey","getParsed","getDataElement","updateRangeFromParsed","parsedValue","NaN","getMinMax","canStack","otherScale","hidden","createStack","NEGATIVE_INFINITY","otherMin","otherMax","_skip","getAllParsedValues","getMaxOverflow","getLabelAndValue","label","getLabelForValue","_clip","disabled","toClip","defaultClip","resolveDatasetElementOptions","resolveDataElementOptions","dataIndex","raw","createDataContext","createDatasetContext","_resolveElementOptions","elementType","sharing","datasetElementScopeKeys","resolveNamedOptions","_resolveAnimations","transition","datasetAnimationScopeKeys","getSharedOptions","includeOptions","sharedOptions","_animationsDisabled","_getSharedOptions","firstOpts","previouslySharedOptions","updateSharedOptions","updateElement","_setStyle","removeHoverStyle","setHoverStyle","_removeDatasetHoverStyle","_setDatasetHoverStyle","arg1","arg2","numMeta","numData","_insertElements","_removeElements","move","updateElements","removed","_sync","_dataChanges","_onDataPush","arguments","_onDataPop","_onDataShift","_onDataSplice","newCount","_onDataUnshift","Element","tooltipPosition","hasValue","final","tickOpts","determinedMaxTicks","_tickSize","maxScale","_length","maxChart","_maxLength","determineMaxTicks","ticksLimit","maxTicksLimit","majorIndices","enabled","getMajorIndices","numMajorIndices","first","newTicks","spacing","ceil","skipMajors","evenMajorSpacing","diff","getEvenSpacing","factors","calculateSpacing","avgMajorSpacing","majorStart","majorEnd","offsetFromEdge","edge","getTicksLimit","ticksLength","sample","numItems","increment","getPixelForGridLine","offsetGridLines","validIndex","_startPixel","_endPixel","lineValue","getPixelForTick","getTickMarkLength","getTitleHeight","titleAlign","reverseAlign","Scale","super","_margins","paddingTop","paddingBottom","paddingLeft","paddingRight","labelRotation","_range","_gridLineItems","_labelItems","_labelSizes","_longestTextCache","_userMax","_userMin","_suggestedMax","_suggestedMin","_ticksLength","_borderValue","_cache","_dataLimitsCached","init","suggestedMin","suggestedMax","metas","getTicks","xLabels","yLabels","getLabelItems","_computeLabelItems","beforeUpdate","sampleSize","beforeSetDimensions","setDimensions","afterSetDimensions","beforeDataLimits","determineDataLimits","afterDataLimits","beforeBuildTicks","buildTicks","afterBuildTicks","samplingEnabled","_convertTicksToLabels","beforeCalculateLabelRotation","calculateLabelRotation","afterCalculateLabelRotation","afterAutoSkip","beforeFit","fit","afterFit","afterUpdate","startPixel","endPixel","reversePixels","_alignToPixels","alignToPixels","_callHooks","notifyPlugins","beforeTickToLabelConversion","generateTickLabels","afterTickToLabelConversion","numTicks","maxLabelDiagonal","_isVisible","labelSizes","_getLabelSizes","maxLabelWidth","widest","maxLabelHeight","highest","asin","minSize","titleOpts","gridOpts","titleHeight","tickPadding","angleRadians","labelHeight","labelWidth","_calculatePadding","_handleMargins","isRotated","labelsBelowTicks","offsetLeft","offsetRight","isFullSize","_computeLabelSizes","caches","widths","heights","tickFont","fontString","nestedLabel","widestLabelSize","highestLabelSize","_resolveTickFontOptions","valueAt","idx","getValueForPixel","getPixelForDecimal","decimal","getDecimalForPixel","getBasePixel","getBaseValue","createTickContext","optionTicks","rot","_computeGridLineItems","tl","borderOpts","axisWidth","axisHalfWidth","alignBorderValue","borderValue","alignedLineValue","tx1","ty1","tx2","ty2","x1","y1","x2","y2","positionAxisID","limit","step","optsAtIndex","optsAtIndexBorder","lineColor","tickBorderDash","tickBorderDashOffset","tickAndPadding","hTickAndPadding","lineCount","textOffset","_getXAxisLabelAlignment","_getYAxisLabelAlignment","halfCount","tickTextAlign","labelPadding","_computeLabelArea","drawBackground","getLineWidthForValue","findIndex","drawGrid","drawLine","setLineDash","lineDashOffset","drawBorder","lastLineWidth","drawLabels","renderTextOptions","drawTitle","titleX","titleY","titleArgs","tz","gz","bz","axisID","_maxDigits","fontSize","TypedRegistry","isForType","isPrototypeOf","register","parentScope","isIChartComponent","itemDefaults","defaultRoutes","routes","propertyParts","sourceName","sourceScope","routeDefaults","registerDefaults","unregister","Registry","controllers","_typedRegistries","_each","addControllers","addPlugins","addScales","getController","_get","getElement","getPlugin","getScale","removeControllers","removeElements","removePlugins","removeScales","typedRegistry","arg","reg","_getRegistryForType","_exec","itemReg","registry","component","camelMethod","PluginService","_init","notify","hook","_createDescriptors","descriptor","plugin","callCallback","cancelable","invalidate","_oldCache","_notifyStateChanges","localIds","allPlugins","getOpts","pluginOpts","createDescriptors","previousDescriptors","some","pluginScopeKeys","getIndexAxis","datasetDefaults","idMatchesAxis","determineAxis","scaleOptions","getAxisFromDataset","mergeScaleConfig","chartDefaults","configScales","chartIndexAxis","scaleConf","error","boundDs","retrieveAxisFromDatasets","defaultId","getDefaultScaleIDFromAxis","defaultScaleOptions","defaultID","getAxisFromDefaultScaleID","initOptions","initData","keyCache","keysCached","cachedKeys","generate","addIfFound","Config","_config","initConfig","_scopeCache","_resolverCache","clearCache","clear","datasetType","additionalOptionScopes","_cachedScopes","mainScope","resetCache","keyLists","chartOptionScopes","subPrefixes","getResolver","hasFunction","needContext","resolverCache","KNOWN_POSITIONS","positionIsHorizontal","compare2Level","l1","l2","onAnimationsComplete","onComplete","onAnimationProgress","onProgress","getCanvas","getElementById","instances","getChart","moveNumericKeys","intKey","getSizeForArea","field","Chart","invalidatePlugins","userConfig","initialCanvas","existingChart","_options","_aspectRatio","_metasets","_lastEvent","_listeners","_responsiveListeners","_sortedMetasets","_plugins","_hiddenIndices","attached","_doResize","resizeDelay","_initialize","bindEvents","_resizeBeforeDraw","_resize","newSize","newRatio","onResize","render","ensureScalesHaveIDs","axisOptions","buildOrUpdateScales","scaleOpts","updated","isRadial","dposition","dtype","scaleType","hasUpdated","_updateMetasets","_destroyDatasetMeta","_removeUnreferencedMetasets","_dataset","buildOrUpdateControllers","newControllers","order","isDatasetVisible","ControllerClass","_resetElements","animsDisabled","_updateScales","_checkEventBindings","_updateHiddenIndices","_minPadding","_updateLayout","_updateDatasets","_eventHandler","_updateHoverStyles","existingEvents","newEvents","unbindEvents","changes","_getUniformDataChanges","datasetCount","makeSet","changeSet","noArea","_idx","_updateDataset","layers","_drawDatasets","_drawDataset","useClip","getDatasetArea","getElementsAtEventForMode","getVisibleDatasetCount","setDatasetVisibility","toggleDataVisibility","getDataVisibility","_updateVisibility","_stop","destroy","toBase64Image","toDataURL","bindUserEvents","bindResponsiveEvents","_add","_remove","detached","updateHoverStyle","getActiveElements","setActiveElements","activeElements","lastActive","pluginId","replay","hoverOptions","deactivated","activated","inChartArea","eventFilter","_handleEvent","_getActiveElements","isClick","lastEvent","determineLastEvent","abstract","DateAdapterBase","members","formats","startOf","endOf","_adapters","_date","computeMinSampleSize","$bar","visibleMetas","getAllScaleValues","curr","updateMinAndPrev","parseValue","startValue","endValue","barStart","barEnd","_custom","parseFloatBar","parseArrayOrPrimitive","isFloatBar","custom","setBorderSkipped","borderSkipped","borderProps","enableBorderRadius","parseEdge","orig","v2","startEnd","setInflateAmount","inflateAmount","DoughnutController","animateRotate","animateScale","cutout","circumference","legend","generateLabels","fontColor","legendItem","innerRadius","outerRadius","getter","_getRotation","_getCircumference","_getRotationExtents","arcs","getMaxBorderWidth","getMaxOffset","maxSize","chartWeight","_getRingWeight","ratioX","ratioY","startX","startY","endX","endY","calcMax","calcMin","maxX","maxY","minX","minY","getRatioAndOffset","maxRadius","radiusLength","_getVisibleDatasetWeightTotal","calculateTotal","_getRingWeightOffset","_circumference","calculateCircumference","animationOpts","centerX","centerY","metaData","borderAlign","hoverBorderWidth","hoverOffset","ringWeightOffset","PolarAreaController","angleLines","circular","pointLabels","bind","_updateRadius","cutoutPercentage","xCenter","yCenter","datasetStartAngle","getIndexAngle","defaultAngle","countVisibleElements","_computeAngle","getDistanceFromCenterForValue","categoryPercentage","barPercentage","grouped","_index_","_value_","iAxisKey","vAxisKey","bars","ruler","_getRuler","vpixels","head","_calculateBarValuePixels","ipixels","_calculateBarIndexPixels","_getStacks","skipNull","_getStackCount","_getStackIndex","pixels","barThickness","stackCount","baseValue","minBarLength","actualBase","floating","barSign","halfGrid","maxBarThickness","Infinity","percent","chunk","computeFlexCategoryTraits","thickness","computeFitCategoryTraits","stackIndex","rects","_decimated","animated","maxGapLength","directUpdate","pointsCount","prevParsed","nullData","lastPoint","updateControlPoints","pointPosition","getPointPositionForValue","parseBorderRadius","angleDelta","borderRadius","halfThickness","innerLimit","computeOuterLimit","outerArcLimit","outerStart","outerEnd","innerStart","innerEnd","rThetaToXY","theta","pathArc","pixelMargin","innerR","spacingOffset","avNogSpacingRadius","angleOffset","outerStartAdjustedRadius","outerEndAdjustedRadius","outerStartAdjustedAngle","outerEndAdjustedAngle","innerStartAdjustedRadius","innerEndAdjustedRadius","innerStartAdjustedAngle","innerEndAdjustedAngle","outerMidAdjustedAngle","pCenter","p4","innerMidAdjustedAngle","p8","outerStartX","outerStartY","outerEndX","outerEndY","fullCircles","inner","lineJoin","angleMargin","clipArc","setStyle","lineCap","pathVars","paramsStart","paramsEnd","segmentStart","segmentEnd","outside","pathSegment","lineMethod","stepped","getLineMethod","fastPathSegment","prevX","lastY","avgX","countX","pointIndex","drawX","truncX","_getSegmentMethod","usePath2D","Path2D","path","_path","strokePathWithCache","segmentMethod","strokePathDirect","LineElement","_points","_segments","_pointsUpdated","_interpolate","_getInterpolationMethod","interpolated","hitRadius","getBarBounds","bar","half","skipOrLimit","boundingRects","maxW","maxH","parseBorderWidth","maxR","enableBorder","outer","skipX","skipY","addNormalRectPath","inflateRect","amount","refRect","chartX","chartY","rAdjust","betweenAngles","withinRadius","halfAngle","halfRadius","radiusOffset","drawArc","addRectPath","mouseX","mouseY","inXRange","inYRange","hoverRadius","findOrAddLabel","addedLabels","unshift","addIfString","lastIndexOf","_getLabelForValue","relativeLabelSize","minSpacing","LinearScaleBase","_startValue","_endValue","_valueRange","handleTickRangeOptions","setMin","setMax","minSign","maxSign","getTickLimit","maxTicks","stepSize","computeTickLimit","generationOptions","dataRange","precision","maxDigits","includeBounds","unit","maxSpaces","rmin","rmax","countDefined","niceMin","niceMax","numSpaces","decimalPlaces","generateTicks","LinearScale","log10Floor","changeExponent","isMajor","tickVal","steps","rangeExp","rangeStep","minExp","exp","startExp","lastTick","LogarithmicScale","_zero","getTickBackdropHeight","determineLimits","fitWithPointLabels","_padding","limits","valueCount","_pointLabels","pointLabelOpts","additionalAngle","centerPointLabels","getPointLabelContext","getPointPosition","drawingArea","plFont","textSize","updateLimits","setCenterPoint","_pointLabelItems","itemOpts","extra","createPointLabelItem","isNotOverlapped","buildPointLabelItems","hLimits","vLimits","outerDistance","pointLabelPosition","yForAngle","getTextAlignForAngle","leftForTextAlign","drawPointLabelBox","backdropLeft","backdropTop","backdropWidth","backdropHeight","pathRadiusLine","labelCount","RadialLinearScale","animate","leftMovement","rightMovement","topMovement","bottomMovement","scalingFactor","getValueForDistanceFromCenter","scaledDistance","pointLabel","createPointLabelContext","distanceFromCenter","getBasePosition","getPointLabelPosition","drawPointLabels","gridLineOpts","drawRadiusLine","INTERVALS","millisecond","common","second","minute","hour","day","week","month","quarter","year","UNITS","sorter","adapter","_adapter","parser","isoWeekday","_parseOpts","determineUnitForAutoTicks","minUnit","capacity","interval","MAX_SAFE_INTEGER","addTick","time","timestamps","ticksFromTimestamps","majorUnit","setMajorTicks","TimeScale","adapters","displayFormats","_unit","_majorUnit","_offsets","_normalized","normalized","_applyBounds","_getLabelBounds","getLabelTimestamps","timeOpts","_generate","_getLabelCapacity","determineUnitForFormatting","determineMajorUnit","initOffsets","offsetAfterAutoskip","getDecimalForValue","weekday","hasWeekday","getDataTimestamps","tooltipFormat","datetime","fmt","_tickFormatFunction","minorFormat","majorFormat","offsets","_getLabelSize","ticksOpts","tickLabelWidth","cosRotation","sinRotation","tickFontSize","exampleTime","exampleLabel","prevSource","nextSource","prevTarget","nextTarget","span","_addedLabels","added","_table","_minPos","_tableRange","_getTimestampsForTable","buildLookupTable","BORDER_COLORS","BACKGROUND_COLORS","getBorderColor","getBackgroundColor","getColorizer","colorizeDoughnutDataset","colorizePolarAreaDataset","colorizeDefaultDataset","containsColorsDefinitions","plugin_colors","forceOverride","_args","chartOptions","colorizer","cleanDecimatedDataset","cleanDecimatedData","plugin_decimation","algorithm","beforeElementsUpdate","xAxis","getStartAndCountOfVisiblePointsSimplified","threshold","decimated","samples","bucketWidth","sampledIndex","endIndex","maxAreaPoint","maxArea","nextA","avgY","avgRangeStart","avgRangeEnd","avgRangeLength","rangeOffs","rangeTo","pointAx","pointAy","lttbDecimation","minIndex","maxIndex","startIndex","xMin","dx","lastIndex","intermediateIndex1","intermediateIndex2","minMaxDecimation","_getBounds","_findSegmentEnd","_getEdge","_createBoundaryLine","boundary","linePoints","_pointsFromSegments","_shouldApplyFill","_resolveTarget","propagate","visited","_decodeFill","fillOption","parseFillOption","firstCh","decodeTargetIndex","addPointsBelow","sourcePoint","linesBelow","postponed","findPoint","pointValue","firstValue","lastValue","simpleArc","getLineByIndex","sourcePoints","below","getLinesBelow","_buildStackLine","_getTargetValue","computeCircularBoundary","_getTargetPixel","computeLinearBoundary","computeBoundary","_drawfill","lineOpts","above","clipVertical","doFill","clipY","lineLoop","tpoints","targetSegments","tgt","subBounds","fillSources","fillSource","src","notShape","clipBounds","interpolatedLineTo","targetLoop","interpolatedPoint","afterDatasetsUpdate","$filler","beforeDraw","drawTime","beforeDatasetsDraw","beforeDatasetDraw","getBoxSize","labelOpts","boxHeight","boxWidth","usePointStyle","pointStyleWidth","itemHeight","Legend","_added","legendHitBoxes","_hoveredItem","doughnutMode","legendItems","columnSizes","lineWidths","buildLabels","labelFont","_computeTitleHeight","_fitRows","_fitCols","hitboxes","totalHeight","row","_itemHeight","heightLimit","totalWidth","currentColWidth","currentColHeight","col","legendItemText","calculateItemWidth","fontLineHeight","calculateLegendItemHeight","calculateItemHeight","calculateItemSize","adjustHitBoxes","rtlHelper","hitbox","_draw","defaultColor","halfFontSize","cursor","textDirection","lineDash","drawOptions","SQRT2","yBoxTop","xBoxLeft","drawLegendBox","titleFont","titlePadding","topPaddingPlusHalfFontSize","_getLegendItemAt","hitBox","lh","handleEvent","onLeave","isListened","hoveredItem","sameItem","plugin_legend","_element","afterEvent","ci","useBorderRadius","Title","_drawArgs","fontOpts","plugin_title","titleBlock","createTitle","WeakMap","plugin_subtitle","positioners","average","eventPosition","nearestElement","tp","pushOrConcat","toPush","splitNewlines","String","createTooltipItem","formattedValue","getTooltipSize","tooltip","body","footer","bodyFont","footerFont","titleLineCount","footerLineCount","bodyLineItemCount","combinedBodyLength","bodyItem","before","after","beforeBody","afterBody","titleSpacing","titleMarginBottom","displayColors","bodySpacing","footerMarginTop","footerSpacing","widthPadding","maxLineWidth","determineXAlign","yAlign","chartWidth","xAlign","caret","caretSize","caretPadding","doesNotFitWithAlign","determineAlignment","determineYAlign","getBackgroundPoint","alignment","paddingAndSize","alignX","alignY","getAlignedX","getBeforeAfterBodyLines","overrideCallbacks","defaultCallbacks","beforeTitle","tooltipItems","afterTitle","beforeLabel","tooltipItem","labelColor","labelTextColor","bodyColor","labelPointStyle","afterLabel","beforeFooter","afterFooter","invokeCallbackWithFallback","Tooltip","opacity","_eventPosition","_size","_cachedAnimations","_tooltipItems","dataPoints","caretX","caretY","labelColors","labelPointStyles","labelTextColors","getTitle","getBeforeBody","getBody","bodyItems","scoped","getAfterBody","getFooter","_createItems","itemSort","positionAndSize","backgroundPoint","external","drawCaret","tooltipPoint","caretPosition","getCaretPosition","x3","y3","ptX","ptY","titleColor","_drawColorBox","colorX","rtlColorX","yOffSet","colorY","multiKeyBackground","outerX","innerX","strokeRect","drawBody","bodyAlign","bodyLineHeight","xLinePadding","fillLineOfText","bodyAlignForCalculation","textColor","drawFooter","footerAlign","footerColor","tooltipSize","quadraticCurveTo","_updateAnimationTarget","animX","animY","_willRender","hasTooltipContent","globalAlpha","positionChanged","_positionChanged","_ignoreReplayEvents","plugin_tooltip","afterInit","afterDraw","helpers","platforms"],"mapp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AC1Bgd,GAAM7U,QAAUA,GAChB6U,GAAMhsC,SAAWA,GACjBgsC,GAAMxqB,YAAcA,GACpBwqB,GAAM9pB,QAAUA,GAChB8pB,GAAMq1B,UAAYA,GAClBr1B,GAAM5R,MAAQA,GACd4R,GAAMltC,MAAQA,GAGd/jB,OAAO0O,OAAOuiD,GAAO1G,GAAa/jC,GAAQvB,GAAUoB,EAASigE,IAC7Dr1B,GAAMA,MAAQA,GAEQ,oBAAXhlD,SACTA,OAAOglD,MAAQA","x_google_ignoreList":[5]} \ No newline at end of file diff --git a/primary/src/helpers/nav.ts b/primary/src/helpers/nav.ts index 00c9b743..1885a337 100644 --- a/primary/src/helpers/nav.ts +++ b/primary/src/helpers/nav.ts @@ -125,7 +125,7 @@ class NavHelpers { href: '/reports/allteammetrics', }, { - label: 'WIP - Browse data from other events', + label: '!reports.browsePastEvents', href: '/reports/browseevents', }, { diff --git a/primary/src/helpers/usefunctions.ts b/primary/src/helpers/usefunctions.ts index f6485d96..6179d0dd 100644 --- a/primary/src/helpers/usefunctions.ts +++ b/primary/src/helpers/usefunctions.ts @@ -221,6 +221,11 @@ class UseFunctions { // expose Luxon DateTime to views res.locals.DateTime = DateTime; + // When fetching something to show in a modal dialog, set a view variable with that + if (req.headers['in-modal-dialog'] === 'true') { + res.locals.inModalDialog = true; + } + // 2022-04-04 JL: Moving timezoneString calculations into initialMiddleware let timezoneString = req.timezoneString; let fixedZone = getFixedZone(timezoneString); diff --git a/primary/src/routes/dashboard.ts b/primary/src/routes/dashboard.ts index 19b081af..1fb4ccde 100644 --- a/primary/src/routes/dashboard.ts +++ b/primary/src/routes/dashboard.ts @@ -33,16 +33,33 @@ router.get('/driveteam', wrap(async (req, res) => { //set teamKey to query or org default // 2022-03-16 JL: Adding an "all" button + // 2024-04-04 JL: Added cookie to store which team key (of the team keys in the org) we think the user belongs to + let teamKeyCookie = req.cookies['selectedTeamKey']; if (typeof req.query.team_key === 'string' && !req.query.all) { teamKey = req.query.team_key; + if (thisUser.org.team_keys?.includes(teamKey)) { + logger.debug('Setting teamKey cookie from query parameter because it\'s in the org\'s list of team_keys'); + res.cookie('selectedTeamKey', teamKey); + } + } + else if (teamKeyCookie && thisUser.org.team_keys?.includes(teamKeyCookie)) { + logger.debug(`Setting teamKey to ${teamKeyCookie} from cookie`); + teamKey = teamKeyCookie; } else if (thisUser.org.team_key && !req.query.all) { + logger.debug(`Setting teamKey ${teamKey} from org team key`); teamKey = thisUser.org.team_key; } else { teamKey = 'all'; } + // Remove team key cookie if it's set but isn't inside the list of team_keys the org has + if (teamKeyCookie && !thisUser.org.team_keys?.includes(teamKeyCookie)) { + logger.info(`teamKeyCookie ${teamKeyCookie} not in list of org keys; removing cookie`); + res.clearCookie('selectedTeamKey'); + } + logger.debug(`eventKey=${eventKey} orgKey=${orgKey} teamKey=${teamKey}`); // Get upcoming match data for the specified team (or "all" if no default & none specified) @@ -215,6 +232,10 @@ router.get('/driveteam', wrap(async (req, res) => { } } + let orgTeamKeys = []; + if (req._user.org.team_key) orgTeamKeys.push(req._user.org.team_key); + if (req._user.org.team_keys) orgTeamKeys.push(...req._user.org.team_keys); + res.render('./dashboard/driveteam', { title: res.msg('driveDashboard.title'), teamList: teamList, @@ -227,6 +248,7 @@ router.get('/driveteam', wrap(async (req, res) => { teamRanks: teamRanks, selectedTeam: teamKey, teamNumbers: teamNumbers, + orgTeamKeys, noMatchesFoundForTeam: noMatchesFoundForTeam, dataForChartJS: JSON.stringify(dataForChartJS), pitData: pitData @@ -345,6 +367,8 @@ router.get('/', wrap(async (req, res) => { },{ sort: {'time': -1} }); + // 2024-04-04, M.O'C: Also get the *unresolved* matches (for 'comp_level') + let unresolvedMatches: Match[] = await utilities.find('matches', { event_key: eventKey, 'alliances.red.score': {$eq: -1} },{sort: {'time': -1}}); // 2024-02-06, M.O'C: Have to change 'latestTimestamp' to be *early* UNLESS matches have been played let latestTimestamp = 1234; @@ -360,10 +384,17 @@ router.get('/', wrap(async (req, res) => { //logger.debug('associating ' + matches[matchIdx].predicted_time + ' with ' + matches[matchIdx].key); matchLookup[matchDocs[matchIdx].key] = matchDocs[matchIdx]; } + // 2024-04-04, M.O'C - Also build a map of *unresolved* matches + let unresolvedMatchLookup: Dict = {}; + if (unresolvedMatches) + for (let matchIdx = 0; matchIdx < unresolvedMatches.length; matchIdx++) { + //logger.debug(`matches[matchIdx].key=${unresolvedMatches[matchIdx].key}`); + unresolvedMatchLookup[unresolvedMatches[matchIdx].key] = unresolvedMatches[matchIdx]; + } // Get all the UNRESOLVED matches where they're set to score // 2020-02-11, M.O'C: Renaming "scoringdata" to "matchscouting", adding "org_key": org_key, - let scoringMatches: MatchScouting[] = await utilities.find('matchscouting', { + let scoringMatches: (MatchScouting & {comp_level?: string, set_number?: number})[] = await utilities.find('matchscouting', { 'org_key': org_key, 'event_key': eventKey, 'assigned_scorer.id': thisUserId, @@ -381,6 +412,15 @@ router.get('/', wrap(async (req, res) => { if (scoringMatches[scoreIdx] && scoringMatches[scoreIdx] && matchLookup[scoringMatches[scoreIdx].match_key]) // @ts-ignore - JL note: don't wanna bother with this rn scoringMatches[scoreIdx].predicted_time = matchLookup[scoringMatches[scoreIdx].match_key].predicted_time; + // 2024-04-04, M.O'C: While we're here... also pass up the 'comp_level' of the match + if (scoringMatches[scoreIdx].match_key && unresolvedMatchLookup[scoringMatches[scoreIdx].match_key]) { + scoringMatches[scoreIdx].comp_level = unresolvedMatchLookup[scoringMatches[scoreIdx].match_key].comp_level; + scoringMatches[scoreIdx].set_number = unresolvedMatchLookup[scoringMatches[scoreIdx].match_key].set_number; + //logger.debug(`comp_level=${scoreData[i].comp_level}`); + } + else { + logger.debug(`scoringMatches[i].match_key=${scoringMatches[scoreIdx].match_key} & ${(scoringMatches[scoreIdx].match_key ? unresolvedMatchLookup[scoringMatches[scoreIdx].match_key] : '(nvrmind)')}`); + } } res.render('./dashboard/index',{ @@ -425,16 +465,19 @@ router.get('/allianceselection', wrap(async (req, res) => { let numRounds = typeof req.query.numRounds === 'string' ? parseInt(req.query.numRounds) : 3; logger.debug(`numAlliances: ${numAlliances}, numRounds: ${numRounds}`); - - // if (numAlliances < 2) throw new e.UserError('invalid numAlliances'); - // if (numRounds < 2 || 4 < numRounds) throw new e.UserError('invalid numRounds'); + + // 2024-04-04 JL: Added multiple picklists + // Check which team_key has been specified, if any, being one of the team_keys of the org + //- JL note: (maybe TODO between seasons): when picklist_key is undefined and team_keys.length > 1, it still loads orgteamvalues with picklist_key undefined, and loads data even though it wont' be displayed + let picklist_key: string|undefined = undefined; + if (typeof req.query.picklist_key === 'string') picklist_key = req.query.picklist_key; + if (picklist_key && !(req._user.org.team_keys?.includes(picklist_key))) throw new e.UserError(`Team key ${picklist_key} specified but it is not in your org's list of team_keys!`); // 2019-03-21, M.O'C: Utilize the currentaggranges // 2019-11-11 JL: Put everything inside a try/catch block with error conditionals throwing try { // 2020-02-08, M.O'C: Change 'currentrankings' into event-specific 'rankings' - //var rankings = await utilities.find("currentrankings", {}, {}); let rankings: Ranking[] = await utilities.find('rankings', {'event_key': event_key}, { sort: {'rank': 1} }); if(!rankings[0]) throw new e.InternalServerError('Couldn\'t find rankings in allianceselection'); @@ -453,7 +496,7 @@ router.get('/allianceselection', wrap(async (req, res) => { // numAlliances is ~usually~ 8, but in some cases - e.g. 2022bcvi - there are fewer let alliances: TeamKey[][] = []; for (let i = 0; i < numAlliances; i++) { - alliances[i] = new Array().fill(numRounds); + alliances[i] = [].fill(numRounds); alliances[i][0] = rankings[i].team_key; // preload first team } logger.debug(`alliances=${JSON.stringify(alliances)}`); @@ -525,7 +568,6 @@ router.get('/allianceselection', wrap(async (req, res) => { // 2022-03-13 JL: Unlike on other pages like allteammetrics, the main focus of these data are the averages (instead of being switchable). // Therefore, keeping the avg as .id and adding MAX as an "option" (to be displayed small on the table) // 2022-03-28, M.O'C: Replacing flat $avg with the exponential moving average - //groupClause[thisLayout.id + 'AVG'] = {$avg: '$data.' + thisLayout.id}; groupClause[thisLayout.id + 'AVG'] = {$last: '$' + thisLayout.id + 'EMA'}; groupClause[thisLayout.id + 'MAX'] = {$max: '$data.' + thisLayout.id}; } @@ -542,6 +584,7 @@ router.get('/allianceselection', wrap(async (req, res) => { {$eq: ['$team_key', '$$team_key']}, {$eq: ['$org_key', org_key]}, {$eq: ['$event_key', event_key]}, + {$eq: ['$picklist_key', picklist_key]}, // 2024-04-04 JL: added picklist_key ]}}}, {$project: {_id: 0, team_key: 0, event_key: 0, org_key: 0}} ], @@ -614,7 +657,6 @@ router.get('/allianceselection', wrap(async (req, res) => { // read in the current agg ranges // 2020-02-08, M.O'C: Tweaking agg ranges - // var currentAggRanges = await utilities.find("currentaggranges", {}, {}); let currentAggRanges: AggRange[] = await utilities.find('aggranges', {'org_key': org_key, 'event_key': event_key}); //logger.debug('aggArray=' + JSON.stringify(aggArray)); @@ -625,11 +667,13 @@ router.get('/allianceselection', wrap(async (req, res) => { numAlliances, numRounds, aggdata: aggArray, - currentAggRanges: currentAggRanges, + currentAggRanges, layout: scoreLayout, - sortedTeams: sortedTeams, - matchcountConsistent: matchcountConsistent, - matchDataHelper: matchDataHelper + sortedTeams, + matchcountConsistent, + matchDataHelper, + picklist_key, + orgTeamKeys: req._user.org.team_keys, }); } catch (err) { @@ -730,6 +774,8 @@ router.get('/matches', wrap(async (req, res) => { // Get the *min* time of the as-yet-unresolved matches [where alliance scores are still -1] // 2024-01-27, M.O'C: Switch to *max* time of *resolved* matches [where alliance scores != -1] let matches: Match[] = await utilities.find('matches', { event_key: eventKey, 'alliances.red.score': {$ne: -1} },{sort: {'time': -1}}); + // 2024-04-04, M.O'C: Also get the *unresolved* matches (for 'comp_level') + let unresolvedMatches: Match[] = await utilities.find('matches', { event_key: eventKey, 'alliances.red.score': {$eq: -1} },{sort: {'time': -1}}); // 2018-03-13, M.O'C - Fixing the bug where dashboard crashes the server if all matches at an event are done // 2024-02-06, M.O'C: Have to change 'latestTimestamp' to be *early* UNLESS matches have been played @@ -744,15 +790,23 @@ router.get('/matches', wrap(async (req, res) => { if (matches) for (let matchIdx = 0; matchIdx < matches.length; matchIdx++) { //logger.debug('associating ' + matches[matchIdx].predicted_time + ' with ' + matches[matchIdx].key); + //logger.debug(`matches[matchIdx].key=${matches[matchIdx].key}`); matchLookup[matches[matchIdx].key] = matches[matchIdx]; } + // 2024-04-04, M.O'C - Also build a map of *unresolved* matches + let unresolvedMatchLookup: Dict = {}; + if (unresolvedMatches) + for (let matchIdx = 0; matchIdx < unresolvedMatches.length; matchIdx++) { + //logger.debug(`matches[matchIdx].key=${unresolvedMatches[matchIdx].key}`); + unresolvedMatchLookup[unresolvedMatches[matchIdx].key] = unresolvedMatches[matchIdx]; + } logger.debug('latestTimestamp=' + latestTimestamp); // Get all the UNRESOLVED matches // 2020-02-11, M.O'C: Renaming "scoringdata" to "matchscouting", adding "org_key": org_key, // 2022-03-17 JL: Reversed alliance sorting order to show red first - let scoreData: MatchScouting[] = await utilities.find('matchscouting', {'org_key': org_key, 'event_key': eventKey, 'time': { $gte: latestTimestamp }}, { limit: 90, sort: {'time': 1, 'alliance': -1, 'team_key': 1} }); + let scoreData: (MatchScouting & {comp_level?: string, set_number?: number})[] = await utilities.find('matchscouting', {'org_key': org_key, 'event_key': eventKey, 'time': { $gte: latestTimestamp }}, { limit: 90, sort: {'time': 1, 'alliance': -1, 'team_key': 1} }); if(!scoreData) return logger.error('mongo error at dashboard/matches'); @@ -773,9 +827,10 @@ router.get('/matches', wrap(async (req, res) => { for (let scoreIdx = 0; scoreIdx < scoreData.length; scoreIdx++) { //logger.debug('getting for ' + scoreData[scoreIdx].match_key); - if (scoreData[scoreIdx] && matchLookup[scoreData[scoreIdx].match_key]) + if (scoreData[scoreIdx] && matchLookup[scoreData[scoreIdx].match_key]) { // @ts-ignore - JL note: don't wanna bother with this rn scoreData[scoreIdx].predicted_time = matchLookup[scoreData[scoreIdx].match_key].predicted_time; + } } logger.trace('DEBUG getting nicknames next?'); @@ -801,6 +856,15 @@ router.get('/matches', wrap(async (req, res) => { // @ts-ignore - JL note: don't wanna bother with this rn scoreData[i].team_nickname = res.msg('dashboard.none'); } + // 2024-04-04, M.O'C: While we're here... also pass up the 'comp_level' of the match + if (scoreData[i].match_key && unresolvedMatchLookup[scoreData[i].match_key]) { + scoreData[i].comp_level = unresolvedMatchLookup[scoreData[i].match_key].comp_level; + scoreData[i].set_number = unresolvedMatchLookup[scoreData[i].match_key].set_number; + //logger.debug(`comp_level=${scoreData[i].comp_level}`); + } + else { + logger.debug(`scoreData[i].match_key=${scoreData[i].match_key} & ${(scoreData[i].match_key ? unresolvedMatchLookup[scoreData[i].match_key] : '(nvrmind)')}`); + } } //this line has a definition problem ^ logger.debug('scoreData.length=' + scoreData.length); diff --git a/primary/src/routes/index.ts b/primary/src/routes/index.ts index 41efea0a..418c807b 100644 --- a/primary/src/routes/index.ts +++ b/primary/src/routes/index.ts @@ -1,8 +1,11 @@ import express from 'express'; import { getLogger } from 'log4js'; +import type Mathjs from 'mathjs'; import wrap from '../helpers/express-async-handler'; import utilities from 'scoutradioz-utilities'; +import type { AnyDict, Match, MatchFormData, Event, Org } from 'scoutradioz-types'; import e from 'scoutradioz-http-errors'; +const mathjs: Mathjs.MathJsStatic = require('mathjs'); const router = express.Router(); const logger = getLogger('index'); @@ -13,6 +16,14 @@ router.all('/*', wrap(async (req, res, next) => { next(); })); +// April fools 20224 +router.get('/try-video-scouting', wrap(async (req, res) => { + res.render('./aprilfools', { + title: 'Generative AI Scouting', + disableAIthing: true, + }); +})); + /** * The "index" page that loads is now a form to select an organization. */ @@ -73,6 +84,470 @@ router.get('/', wrap(async (req, res, next) => { } })); +/** + * Browse by event + */ +router.get('/browse', wrap(async (req, res, next) => { + logger.addContext('funcName', 'browse[get]'); + logger.debug('ENTER'); + + // for now, this only works with the current year. TODO: be able to browse past years + let current_year = (new Date()).getFullYear(); + + // + // Get the latest match played timestamp per year + // + let latest_match_time_per_year = [ + { + $match: { + 'actual_time': { $exists: true }, // Ensure "actual_time" field exists + 'alliances.red.score': { $ne: -1}, + 'comp_level': 'qm' + //"year": { $in: [2023, 2024] } // Match documents for the specified years + } + }, + { + $group: { + _id: '$year', // Group by year + max_actual_time: { $max: '$actual_time' } // Find the maximum value of "actual_time" for each year + } + } + ]; + let match_latest = await utilities.aggregate('matches', latest_match_time_per_year, {allowCache: true, maxCacheAge: 300}); + logger.debug(`match_latest=${JSON.stringify(match_latest)}`); + + // get counts of match scouting entries per event, per org + let events_and_orgs_agg = [ + { + $match: { 'year': current_year, 'data': {$ne: null} } + }, + { + $group: { + _id: { event_key: '$event_key', org_key: '$org_key' }, + count: { $sum: 1 } + } + }, + { + $sort: { '_id.event_key': 1, '_id.org_key': 1 } + } + ]; + let event_orgs = await utilities.aggregate('matchscouting', events_and_orgs_agg, {allowCache: true, maxCacheAge: 300}); + logger.debug(`event_orgs = ${JSON.stringify(event_orgs)}`); + + let eventDict: { [id: string]: string } = {}; + let eventToOrgsDict: { [id: string]: string[] } = {}; + let eventOrgCountDict: { [id: string]: number } = {}; + // build list of unique events, and map of event:[list of teams] + for (let i = 0; i < event_orgs.length; i++) { + let thisElem = event_orgs[i]._id; + let thisEvent = thisElem.event_key; + let thisOrg = thisElem.org_key; + + eventDict[thisEvent] = thisEvent; + let checkEvent = eventToOrgsDict[thisEvent]; + if (checkEvent) { + checkEvent.push(thisOrg); + eventToOrgsDict[thisEvent] = checkEvent; + } + else { + let newEventList: string[] = []; + newEventList.push(thisOrg); + eventToOrgsDict[thisEvent] = newEventList; + } + + let eventOrgKey = thisEvent + '|' + thisOrg; + eventOrgCountDict[eventOrgKey] = event_orgs[i].count; + } + let eventList = Object.keys(eventDict); + logger.debug(`eventList = ${JSON.stringify(eventList)}`); + logger.debug(`eventToOrgsDict = ${JSON.stringify(eventToOrgsDict)}`); + + // get info for events + let events: Event[] = await utilities.find('events', + {'year': current_year, 'key': { '$in': eventList }}, + {sort: {start_date: -1}}, + {allowCache: true, maxCacheAge: 300} + ); + let eventInfoDict: { [id: string]: Event } = {}; + for (let thisIdx in events) + eventInfoDict[events[thisIdx].key] = events[thisIdx]; + + // get info for orgs + let orgs: Org[] = await utilities.find('orgs', {}, {}, {allowCache: true, maxCacheAge: 300}); + let orgInfoDict: { [id: string]: Org } = {}; + for (let thisIdx in orgs) + orgInfoDict[orgs[thisIdx].org_key] = orgs[thisIdx]; + + // get counts of completed matches per event + let count_of_matches_by_event = [ + { + $match: { + 'event_key': { $in: eventList }, + 'alliances.red.score': { $ne: -1}, + 'comp_level': 'qm' + } + }, + { + $group: { + _id: '$event_key', + total_matches: { $sum: 1 } + } + }, + { + $project: { + _id: 0, + event_key: '$_id', + total_matches: 1 + } + }, + { + $sort: { + 'event_key': 1 + } + } + ]; + let matches_by_event = await utilities.aggregate('matches', count_of_matches_by_event, {allowCache: true, maxCacheAge: 300}); + logger.debug(`matches_by_event = ${JSON.stringify(matches_by_event)}`); + let eventMatchCountDict: { [id: string]: number } = {}; + for (let eventIdx = 0; eventIdx < matches_by_event.length; eventIdx++) { + let this_match_event = matches_by_event[eventIdx]; + eventMatchCountDict[this_match_event.event_key] = this_match_event.total_matches; + } + + let eventScoutingArray: EventScouting[] = []; + // Loop through each event + for (let eventIdx = 0; eventIdx < eventList.length; eventIdx++) { + let thisEventKey = eventList[eventIdx]; + let thisEventOrgs = eventToOrgsDict[thisEventKey]; + + // get the matches for this event + let matches: Match[] = await utilities.find('matches', + { 'event_key': thisEventKey, 'comp_level': 'qm', 'score_breakdown': { '$ne': undefined }, 'alliances.red.score': {$ne: -1} }, { sort: { match_number: 1 } }, + {allowCache: true, maxCacheAge: 300} + ); + let matchDict: { [id: string]: Match } = {}; + let debugFirstMatch = true; + for (let matchIdx = 0; matchIdx < matches.length; matchIdx++) { + if (debugFirstMatch) { + logger.trace(`matchIdx=${matchIdx}, matches[matchIdx]=${JSON.stringify(matches[matchIdx])}`); + debugFirstMatch = false; + } + //logger.debug(`matches[matchIdx].key=${matches[matchIdx].key}`); + matchDict[matches[matchIdx].key] = matches[matchIdx]; + } + + // Set event-level evaluation - possible # of match scouting reports (and) initial "eventMinSpr" + let thisEventMatchCount = matches.length * 6; + logger.debug(`### AT ${thisEventKey}: ${JSON.stringify(thisEventOrgs)} ~ has ${thisEventMatchCount} possible match reports`); + // Use some arbitrarily high number to start the 'event minimum SPR' with + const ARBITRARILY_HIGH_SPR = 99999.9; + let thisEventMinSpr = ARBITRARILY_HIGH_SPR; + // Keep track of teams with TSPS-possible data at the event + let tspsPossibleDataCount = 0; + // Array for storing org scouting info + let thisEventOrgScoutingArray: EventOrgScouting[] = []; + + // Loop through each team at this event + for (let teamIdx = 0; teamIdx < thisEventOrgs.length; teamIdx++) { + let thisOrgKey = thisEventOrgs[teamIdx]; + logger.debug(`-- Org ${thisOrgKey}:`); + + // track values per org: orgKey, numReports, medianSpr, minSpr, tsps + let thisNumReports = eventOrgCountDict[thisEventKey + '|' + thisOrgKey]; + let thisMedianSpr: number = NaN; + let thisMinSpr: number = NaN; + + let cp_per_match_per_alliance = [ + { + $match: { + 'event_key': thisEventKey, + 'org_key': thisOrgKey, + 'data': {'$ne': undefined} + } + }, + { + $group: { + _id: { + match_key: '$match_key', + alliance: '$alliance' + }, + count: { $sum: 1 }, + total_contributed_points: { $sum: '$data.contributedPoints' }, + actual_scorer_names: { $push: '$actual_scorer.name' }, + actual_scorer_ids: { $push: '$actual_scorer.id' } + } + }, + { + $project: { + _id: 0, + match_key: '$_id.match_key', + alliance: '$_id.alliance', + count: 1, + total_contributed_points: 1, + actual_scorer_names: 1, + actual_scorer_ids: 1 + } + }, + { + $sort: { + 'match_key': 1, + 'alliance': 1 + } + } + ]; + + let cpPerMatchPerAlliance = await utilities.aggregate('matchscouting', cp_per_match_per_alliance, {allowCache: true, maxCacheAge: 300}); + //logger.debug(`event=${thisEventKey}~org=${thisOrgKey}: ${JSON.stringify(cpPerMatchPerAlliance)}`); + + // + // Calculate SPRs & find the median + // + + // dictionary of scouts - each item should be keyed by scout name and contain (a) total matches scouted + (b) total error point diffs & ratios + let scoutScoreDict: Dict<{count: number, avgDiff: number, avgRatio: number, totDiff: number, totRatio: number, sprIndex: number, sprScore: number}> = {}; + + // SPR arrays setup + let scoutSprList:string[] = []; + let emptyRow:number[] = []; + let matrix:number[][] = []; + let vector:number[][] = []; + + let debugFirstMatch = true; + for (let cppmpaIdx = 0; cppmpaIdx < cpPerMatchPerAlliance.length; cppmpaIdx++) { + let thisCppmpa = cpPerMatchPerAlliance[cppmpaIdx]; + if (thisCppmpa.count === 3) { + if (debugFirstMatch) { + logger.trace(`thisCppmpa=${JSON.stringify(thisCppmpa)}`); + debugFirstMatch = false; + } + + let thisMatchKey = thisCppmpa.match_key; + let thisAlliance: 'red'|'blue' = thisCppmpa.alliance; + + let thisMatch = matchDict[thisMatchKey]; + if (!thisMatch) { + logger.warn(`No match found for thisMatchKey=${thisMatchKey}`); + } + else { + let thisScoreBreakdown = thisMatch.score_breakdown[thisAlliance]; + let totalPoints = getNumberFrom(thisScoreBreakdown, 'totalPoints'); + let foulPoints = getNumberFrom(thisScoreBreakdown, 'foulPoints'); + let frcTot = totalPoints - foulPoints; + + let orgTot = thisCppmpa.total_contributed_points; + + let errDiff = Math.abs(orgTot - frcTot); + let errRatio = errDiff / frcTot; + if (errRatio > 1.0) + errRatio = 1.0; + + logger.trace(`Match found for thisMatchKey=${thisMatchKey}: frcTot=${frcTot}, orgTot=${orgTot}`); + + for (let scoutIdx = 0; scoutIdx < 3; scoutIdx++ ) { + let thisScoutId = thisCppmpa.actual_scorer_ids[scoutIdx]; + let thisScoutName = thisCppmpa.actual_scorer_names[scoutIdx]; + let thisScoutRecord = scoutScoreDict[thisScoutId]; + if (!thisScoutRecord) { + // add rows & cols to matrix, and add an element to the vector + let thisScoutIndex = vector.length; + vector.push([0]); + logger.trace(`thisScoutName=${thisScoutName},thisScoutId=${thisScoutId},thisScoutIndex=${thisScoutIndex}`); + scoutSprList.push(thisScoutName); + + emptyRow = []; + for (let i = 0; i < matrix.length; i++) { + emptyRow.push(0); + matrix[i].push(0); + } + emptyRow.push(0); + matrix.push(emptyRow); + //logger.debug(`ADD vector=${JSON.stringify(vector)}`); + //logger.debug(`ADD matrix=${JSON.stringify(matrix)}`); + + scoutScoreDict[thisScoutId] = {count: 1, avgDiff: errDiff, avgRatio: errRatio, totDiff: errDiff, totRatio: errRatio, sprIndex: thisScoutIndex, sprScore: 0}; + } + else { + logger.trace(`updating ${JSON.stringify(thisScoutRecord)}`); + let newCount = thisScoutRecord.count + 1; + let newTotDiff = thisScoutRecord.totDiff + errDiff; + let avgDiff = newTotDiff / newCount; + let newTotRatio = thisScoutRecord.totRatio + errRatio; + let avgRatio = newTotRatio / newCount; + scoutScoreDict[thisScoutId] = {count: newCount, avgDiff: avgDiff, avgRatio: avgRatio, totDiff: newTotDiff, totRatio: newTotRatio, sprIndex: thisScoutRecord.sprIndex, sprScore: 0}; + } + } + + // SPR matrix & vector updates + for (let x = 0; x < thisCppmpa.actual_scorer_ids.length; x++) { + let thisScout = thisCppmpa.actual_scorer_ids[x]; + if (!thisScout) { + logger.debug('No actual_scorer for scout report idx=' + x); + continue; + } + // 2022-02-20 JL: renamed thisScoutName to thisScout, added thisScoutId + let thisScoutId = thisCppmpa.actual_scorer_ids[x]; + let thisScoutName = thisCppmpa.actual_scorer_names[x]; + // let thisScoutName = thisScout.name; + + let xIndex = scoutScoreDict[thisScoutId].sprIndex; + vector[xIndex][0] = vector[xIndex][0] + errDiff; + for (let y = 0; y < thisCppmpa.actual_scorer_ids.length; y++) { + let thisScout2 = thisCppmpa.actual_scorer_ids[y]; + if (!thisScout2) { + logger.trace('No actual_scorer 2 for scout report idx=' + y); + continue; + } + let thisScoutId2 = thisCppmpa.actual_scorer_ids[y]; + let thisScoutName2 = thisCppmpa.actual_scorer_names[x]; + + let yIndex = scoutScoreDict[thisScoutId2].sprIndex; + logger.trace(`scout1=${thisScoutName},scout2=${thisScoutName2},xIndex=${xIndex},yIndex=${yIndex}`); + + matrix[yIndex][xIndex] = matrix[yIndex][xIndex] + 1; + } + } + } + } + } + + // what is the determinant? + logger.trace(`matrix=${JSON.stringify(matrix)}`); + if (matrix.length > 0) + logger.trace(`...math.det(matrix)=${mathjs.det(matrix)}`); + else + logger.trace('...math.det(matrix)=matrix_is_zero_size'); + logger.trace(`vector=${JSON.stringify(vector)}`); + + // solve! + try { + let solution = mathjs.lusolve(matrix, vector) as Mathjs.MathNumericType[][]; + logger.trace(`solution=${JSON.stringify(solution)}`); + + for (let key in scoutScoreDict) { + let thisSprIndex:number = scoutScoreDict[key].sprIndex; + scoutScoreDict[key].sprScore = Number(solution[thisSprIndex][0]); + } + } + catch (err) { + logger.warn(`could not calculate solution! err=${err}`); + } + + // sort scoutScoreDict by sprScore + let sortedValues:Array<{count: number, avgDiff: number, avgRatio: number, totDiff: number, totRatio: number, sprIndex: number, sprScore: number}> = Object.values(scoutScoreDict); + // reverse sort! + sortedValues.sort((a, b) => a.sprScore - b.sprScore); + logger.trace('sortedValues=' + JSON.stringify(sortedValues)); + + // // reconstruct scoutScoreDict + // scoutScoreDict = {}; + // for (let thisIdx in sortedValues) { + // //logger.trace(`thisIdx=${thisIdx}`); + // let thisValue = sortedValues[thisIdx]; + // logger.trace(`thisValue=${thisValue}`); + // logger.trace(`thisValue.sprIndex=${thisValue.sprIndex}`); + // logger.trace(`scoutSprList[thisValue.sprIndex]=${scoutSprList[thisValue.sprIndex]}`); + // scoutScoreDict[scoutSprList[thisValue.sprIndex]] = thisValue; + // } + // // final results + // logger.trace('scoutScoreDict=' + JSON.stringify(scoutScoreDict)); + + let sprLength = sortedValues.length; + if (sprLength > 0) { + thisMinSpr = sortedValues[0].sprScore; + if (thisMinSpr < thisEventMinSpr) + thisEventMinSpr = thisMinSpr; + + thisMedianSpr = 0.0; + // do we have an odd number of items? + if (sprLength & 1) { + thisMedianSpr = sortedValues[Math.trunc(sprLength/2.0)].sprScore; + logger.trace(`thisNumReports=${thisNumReports} ~ thisMinSpr=${thisMinSpr} ~ sprLength ${sprLength} is odd, thisMedianSpr=${thisMedianSpr}`); + } + else { + thisMedianSpr = (sortedValues[Math.trunc(sprLength/2.0) - 1].sprScore + sortedValues[Math.trunc(sprLength/2.0)].sprScore) / 2.0; + logger.trace(`thisNumReports=${thisNumReports} ~ thisMinSpr=${thisMinSpr} ~ sprLength ${sprLength} is even, thisMedianSpr=${thisMedianSpr}`); + } + } + + let thisIsTspsElgibile: boolean = false; + // do we have TSPS-possible data? + if (!isNaN(thisMinSpr) && !isNaN(thisMedianSpr) && !(thisMinSpr === 0.0 && thisMedianSpr === 0.0)) { + logger.trace('Has TSPS possible!'); + thisIsTspsElgibile = true; + tspsPossibleDataCount += 1; + } + else { + logger.warn('Not TSPS possible data'); + } + + let thisEventOrgScouting: EventOrgScouting = { + countScoutingReports: thisNumReports, + orgKey: thisOrgKey, + orgName: orgInfoDict[thisOrgKey].nickname, + isTspsEligible: thisIsTspsElgibile + }; + if (thisIsTspsElgibile) { + thisEventOrgScouting.medianSpr = thisMedianSpr; + thisEventOrgScouting.minSpr = thisMinSpr; + } + + thisEventOrgScoutingArray.push(thisEventOrgScouting); + } + + // calculate Total Scouting Performance Scores **IF** there are at least 2 orgs with valid data + logger.trace(`thisEventMinSpr=${thisEventMinSpr}, tspsPossibleDataCount=${tspsPossibleDataCount}`); + if (tspsPossibleDataCount > 1) { + // normalization value + let thisSprNormalization = Math.abs(thisEventMinSpr); + + // find the 'best' normalized SPR + let thisBestSpr = ARBITRARILY_HIGH_SPR; + for (let thisTspsIdx in thisEventOrgScoutingArray) { + let thisScoutingBlob = thisEventOrgScoutingArray[thisTspsIdx]; + if (thisScoutingBlob.isTspsEligible && typeof(thisScoutingBlob.medianSpr) == 'number' && thisScoutingBlob.medianSpr < thisBestSpr) + thisBestSpr = thisScoutingBlob.medianSpr; + } + + // calculate TSPS + // thisEventMatchCount is total possible scouting reports + for (let thisTspsIdx in thisEventOrgScoutingArray) { + let thisScoutingBlob = thisEventOrgScoutingArray[thisTspsIdx]; + if (thisScoutingBlob.isTspsEligible && typeof(thisScoutingBlob.medianSpr) == 'number') { + let sprComponent = (thisBestSpr + thisSprNormalization) / (thisScoutingBlob.medianSpr + thisSprNormalization); + let thisMatchCount = thisScoutingBlob.countScoutingReports; + if (typeof(thisMatchCount) == 'number' && thisMatchCount > thisEventMatchCount) { + logger.warn(`for org=${thisScoutingBlob.orgKey} at event=${thisEventKey}, org match count ${thisMatchCount} > event match count ${thisEventMatchCount}`); + thisMatchCount = thisEventMatchCount; + } + let coverageComponent = thisMatchCount / thisEventMatchCount; + // Total Scouting Performance Score! + let thisTsps = (sprComponent + coverageComponent) / 2.0; + thisScoutingBlob.tsps = thisTsps; + } + } + } + + let thisEventScouting: EventScouting = { + eventKey: thisEventKey, + eventName: eventInfoDict[thisEventKey].name, + eventStart: eventInfoDict[thisEventKey].start_date, + possibleScoutingReports: thisEventMatchCount, + orgData: thisEventOrgScoutingArray + }; + logger.debug(`thisEventScouting=${JSON.stringify(thisEventScouting)}`); + eventScoutingArray.push(thisEventScouting); + } + + // sort the array by date + eventScoutingArray.sort((a, b) => (a.eventStart < b.eventStart ? 1 : -1)); + + res.render('./browse', { + fulltitle: res.msg('index.browse.title'), + year: current_year, + event_scouting: eventScoutingArray + }); +})); + /** * User submission to select an organization. */ @@ -238,4 +713,35 @@ async function doSelectOrg(req: express.Request, res: express.Response, cb: () = } -module.exports = router; \ No newline at end of file +module.exports = router; + +/** + * Get a number from an AnyDict, defaulting to 0. Easier than doing an inline ternary for each variable. + */ +function getNumberFrom(dict: AnyDict|MatchFormData|undefined, key: string): number { + if (!dict) return 0; + let thisItem = dict[key]; + if (typeof thisItem === 'number') return thisItem; + else return 0; +} + +/** + * Objects for browsing data by events + */ +export declare interface EventOrgScouting { + orgKey: string; + orgName: string; + countScoutingReports: number; + medianSpr?: number; + minSpr?: number; + isTspsEligible: boolean, + tsps?: number; +} + +export declare interface EventScouting { + eventKey: string; + eventName: string; + eventStart: string; + possibleScoutingReports: number, + orgData?: EventOrgScouting[]; +} diff --git a/primary/src/routes/manage/allianceselection.ts b/primary/src/routes/manage/allianceselection.ts index 45742f7a..69309cd4 100644 --- a/primary/src/routes/manage/allianceselection.ts +++ b/primary/src/routes/manage/allianceselection.ts @@ -4,7 +4,7 @@ import wrap from '../../helpers/express-async-handler'; import utilities from 'scoutradioz-utilities'; import Permissions from '../../helpers/permissions'; import { matchData as matchDataHelper } from 'scoutradioz-helpers'; -import e from 'scoutradioz-http-errors'; +import e, { assert } from 'scoutradioz-http-errors'; import type { MongoDocument } from 'scoutradioz-utilities'; import type { Ranking, AggRange, OrgTeamValue } from 'scoutradioz-types'; @@ -24,35 +24,30 @@ router.get('/', wrap(async (req, res) => { let org_key = req._user.org_key; logger.debug(thisFuncName + 'event_key=' + event_key); + // 2024-04-04 JL: Added multiple picklists + // Check which team_key has been specified, if any, being one of the team_keys of the org + //- JL note: (maybe TODO between seasons): when picklist_key is undefined and team_keys.length > 1, it still loads orgteamvalues with picklist_key undefined, and loads data even though it wont' be displayed + let picklist_key: string|undefined = undefined; + if (typeof req.query.picklist_key === 'string') picklist_key = req.query.picklist_key; + if (picklist_key && !(req._user.org.team_keys?.includes(picklist_key))) throw new e.UserError(`Team key ${picklist_key} specified but it is not in your org's list of team_keys!`); + // get the current rankings // 2020-02-08, M.O'C: Change 'currentrankings' into event-specific 'rankings' - //var rankings = await utilities.find("currentrankings", {}, {}); - let rankings: Ranking[] = await utilities.find('rankings', {'event_key': event_key}, {}); + let rankings: Ranking[] = await utilities.find('rankings', {event_key}, {}); let rankMap: Dict = {}; for (let rankIdx = 0; rankIdx < rankings.length; rankIdx++) { //logger.debug(thisFuncName + 'rankIdx=' + rankIdx + ', team_key=' + rankings[rankIdx].team_key + ', rank=' + rankings[rankIdx].rank); rankMap[rankings[rankIdx].team_key] = rankings[rankIdx]; } - //logger.debug(thisFuncName + 'rankMap=' + JSON.stringify(rankMap)); - // Match data layout - use to build dynamic Mongo aggregation query --- Comboing twice, on two sets of team keys: red alliance & blue alliance - // db.scoringdata.aggregate( [ - // { $match : { "team_key":{$in: [...]}, "event_key": event_key } }, - // { $group : { _id: "$event_key", - // "autoScaleAVG": {$avg: "$data.autoScale"}, - // "teleScaleAVG": {$avg: "$data.teleScale"}, - // } } - // ] ); // 2020-02-11, M.O'C: Combined "scoringlayout" into "layout" with an org_key & the type "matchscouting" - //var scorelayout = await utilities.find("scoringlayout", { "year": event_year }, {sort: {"order": 1}}); - //var scorelayout = await utilities.find("layout", {org_key: org_key, year: event_year, form_type: "matchscouting"}, {sort: {"order": 1}}) let cookie_key = org_key + '_' + event_year + '_cols'; let colCookie = req.cookies[cookie_key]; let scorelayout = await matchDataHelper.getModifiedMatchScoutingLayout(org_key, event_year, colCookie); let aggQuery = []; - aggQuery.push({ $match : { 'org_key': org_key, 'event_key': event_key } }); + aggQuery.push({ $match : { org_key, event_key } }); let groupClause: MongoDocument = {}; // group teams for 1 row per team groupClause['_id'] = '$team_key'; @@ -76,6 +71,7 @@ router.get('/', wrap(async (req, res) => { {$eq: ['$team_key', '$$team_key']}, {$eq: ['$org_key', org_key]}, {$eq: ['$event_key', event_key]}, + {$eq: ['$picklist_key', picklist_key]}, // 2024-04-04 JL: added picklist_key ]}}}, {$project: {_id: 0, team_key: 0, event_key: 0, org_key: 0}} ], @@ -119,9 +115,11 @@ router.get('/', wrap(async (req, res) => { res.render('./manage/allianceselection', { title: 'Alliance Selection', aggdata: aggArray, - currentAggRanges: currentAggRanges, + currentAggRanges, layout: scorelayout, - matchDataHelper: matchDataHelper + matchDataHelper, + picklist_key, + orgTeamKeys: req._user.org.team_keys, }); })); @@ -144,17 +142,21 @@ router.post('/updateteamvalue', wrap(async (req, res) => { const valueToAdd = parseInt(req.body.value); const org_key = req._user.org_key; const event_key = req.event.key; + // 2024-04-04 JL: Added picklist key + // Note: Behavior gets a little wonky if the list of team_keys changes at the same event *after* the picklist has been edited + let picklist_key = req.body.picklist_key; + if (picklist_key === 'undefined') picklist_key = undefined; if (!team_key || !valueToAdd) throw new e.UserError('Provide a team_key and a value.'); - let currentTeamValue: OrgTeamValue = await utilities.findOne('orgteamvalues', {org_key: org_key, team_key: team_key, event_key: event_key}); + let currentTeamValue: OrgTeamValue = await utilities.findOne('orgteamvalues', {org_key, team_key, event_key, picklist_key}); let newValue; if (currentTeamValue) { newValue = currentTeamValue.value + valueToAdd; - logger.debug(`Setting ${team_key}'s value to ${newValue} for org ${org_key}`); + logger.debug(`Setting ${team_key}'s value to ${newValue} for org ${org_key} and picklist ${picklist_key} and event ${event_key}`); // If the value to set is 0, then just delete the record if (newValue === 0) { logger.debug('Deleting record'); @@ -167,12 +169,13 @@ router.post('/updateteamvalue', wrap(async (req, res) => { // If there's no team in the values collection, create it else { newValue = valueToAdd; - logger.debug(`Creating entry for ${team_key} for org ${org_key}, value=${newValue}`); + logger.debug(`Creating entry for ${team_key} for org ${org_key}, value=${newValue}, picklist=${picklist_key}`); let newEntry = { - org_key: org_key, - team_key: team_key, - event_key: event_key, + org_key, + team_key, + event_key, + picklist_key, value: newValue }; diff --git a/primary/src/routes/manage/assignments.ts b/primary/src/routes/manage/assignments.ts index 2c65f72d..c6521710 100644 --- a/primary/src/routes/manage/assignments.ts +++ b/primary/src/routes/manage/assignments.ts @@ -195,19 +195,27 @@ router.post('/matches/generate', wrap(async (req, res) => { const availableArray: number[] = []; // User IDs let stoppingForBreaks = true; + let scoutPlayoffs = false; logger.trace('*** Tagged as available:'); for(let user in req.body) { const userId = user.split('|')[0]; // 2024-01-24, M.O'C: special case, checkbox to 'skipBreaks' - if (userId != 'skipBreaks') { + // 2024-04-04, M.O'C: Enable option to assign scouting to playoffs + if (userId != 'skipBreaks' && userId != 'scoutPlayoffs') { const userName = user.split('|')[1]; // unused logger.trace(`user: ${userId} | ${userName}`); assert(userId && userName, 'Could not find both userId and userName'); availableArray.push(Number(userId)); } else { - logger.debug('Assignments will continue past breaks!'); - stoppingForBreaks = false; + if (userId === 'skipBreaks') { + logger.debug('Assignments will continue past breaks!'); + stoppingForBreaks = false; + } + else if (userId === 'scoutPlayoffs') { + logger.debug('Assignments will be generated for playoffs!'); + scoutPlayoffs = true; + } } } @@ -215,11 +223,22 @@ router.post('/matches/generate', wrap(async (req, res) => { {org_key, event_key}, {sort: {time: 1}} ); - - const matchArray: Match[] = await utilities.find('matches', - {event_key, comp_level: 'qm'}, - {sort: {time: 1}} - ); + + let matchArray: Match[] = []; + if (scoutPlayoffs) { + // 2024-04-04, M.O'C: Do not filter on 'comp_level' + matchArray = await utilities.find('matches', + {event_key}, + {sort: {time: 1}} + ); + } + // most of the time only scout quals + else { + matchArray = await utilities.find('matches', + {event_key, comp_level: 'qm'}, + {sort: {time: 1}} + ); + } let outputNotes: string[] = []; // Notes to display to the scouting lead about what went on behind the scenes @@ -327,8 +346,11 @@ router.post('/matches/generate', wrap(async (req, res) => { logger.info('There are existing assignments in the DB, so we will attempt to re-populate existing data when re-generating...'); // Populate a dict of all the existing data for the match + // 2024-04-04, M.O'C: Carrying over assigned scorer (and) super_data const matchTeamKeyToSubmissionsMap: Dict<{ data: MatchFormData; + super_data?: MatchFormData; + assigned_scorer?: ScouterRecord; actual_scorer?: ScouterRecord; useragent?: UserAgent; }> = {}; @@ -337,6 +359,8 @@ router.post('/matches/generate', wrap(async (req, res) => { if (matchTeam.data) { matchTeamKeyToSubmissionsMap[matchTeam.match_team_key] = { data: matchTeam.data, + super_data: matchTeam.super_data, + assigned_scorer: matchTeam.assigned_scorer, actual_scorer: matchTeam.actual_scorer, useragent: matchTeam.useragent, }; @@ -356,6 +380,9 @@ router.post('/matches/generate', wrap(async (req, res) => { // JL note: actual_scouter and useragent could be undefined, so I'd rather not add the keys unless they're defined if (thisSubmission.actual_scorer) matchTeam.actual_scorer = thisSubmission.actual_scorer; if (thisSubmission.useragent) matchTeam.useragent = thisSubmission.useragent; + // 2024-04-04, M.O'C: Add in preserving assigned_scorer (and) super_data + if (thisSubmission.super_data) matchTeam.super_data = thisSubmission.super_data; + if (thisSubmission.assigned_scorer) matchTeam.assigned_scorer = thisSubmission.assigned_scorer; // Now, delete the key from the submissions map so we can keep track of which entries have NOT yet been repopulated into the new array delete matchTeamKeyToSubmissionsMap[matchTeam.match_team_key]; } @@ -487,6 +514,8 @@ router.post('/matches/generate', wrap(async (req, res) => { scoutsPerMatch = matchScoutsPlusScoutedCount.length; } + // 2024-03-20, M.O'C: The changes to "use latest timestamp" instead of "next unplayed timestamp" broke scheduling when you're doing the 2nd run past breaks + let notFirstMatch: boolean = false; for (let matchesIdx in comingMatches) { const thisMatch = comingMatches[matchesIdx]; const thisMatchKey = thisMatch.key; @@ -532,11 +561,13 @@ router.post('/matches/generate', wrap(async (req, res) => { matchGap = comingMatches[matchesIdx].time - lastMatchTimestamp; // Iterate until a "break" is found (or otherwise, if the loop is exhausted) // 2024-01-24, M.O'C: Might optionally not be stopping for breaks - if (stoppingForBreaks) + // 2024-03-20, M.O'C: Only check for breaks on the 2nd and later matches - 'notFirstMatch' is initially "false" + if (stoppingForBreaks && notFirstMatch) if (matchGap > matchGapBreakThreshold) { logger.trace('matchGap=' + matchGap + '... found a break'); break; } + notFirstMatch = true; let teamArray: TeamKey[] = []; if (redBlueToggle == 0) @@ -1055,7 +1086,7 @@ router.post('/swappitassignments', wrap(async (req, res) => { })); async function generateTeamAllocations(req: express.Request, res: express.Response) { - logger.addContext('funcName', 'generateTEAMallocations'); + logger.addContext('funcName', 'generateTeamAllocations'); const event_key = req.event.key; const year = req.event.year; @@ -1142,7 +1173,8 @@ async function generateTeamAllocations(req: express.Request, res: express.Respon const teamArray = req.teams; // 2023-02-12 JL: Added a query to get existing scouting data on a per-team basis - const existingScoutingData = await utilities.find('pitscouting', {event_key, org_key, data: {$ne: undefined}}); + // 2024-03-26 M.O'C: Include super-scouting data + const existingScoutingData = await utilities.find('pitscouting', {event_key, org_key, $or: [ {data: { $ne: undefined }}, {super_data: { $ne: undefined }} ]}); // // Cycle through teams, adding 1st 2nd 3rd to each based on array of 1st2nd3rds @@ -1185,10 +1217,14 @@ async function generateTeamAllocations(req: express.Request, res: express.Respon } // 2023-02-12 JL: Check for existing scouting data and insert it + // 2024-03-26 M.O'C: Adding super_data, plus checks for each type for (let thisEntry of existingScoutingData) { if (thisEntry.team_key === team_key) { logger.trace(`Appending data for team_key ${team_key}`); - thisAssignment.data = thisEntry.data; + if (thisEntry.data) + thisAssignment.data = thisEntry.data; + if (thisEntry.super_data) + thisAssignment.super_data = thisEntry.super_data; } } @@ -1202,7 +1238,8 @@ async function generateTeamAllocations(req: express.Request, res: express.Respon // Sanity check for data deletion let teamAssignmentsWithData = 0; - for (let assignment of teamAssignments) if (assignment.data) teamAssignmentsWithData++; + // 2024-03-26, M.O'C: Adding super_data to the check + for (let assignment of teamAssignments) if (assignment.data || assignment.super_data) teamAssignmentsWithData++; logger.info(`Generated team assignments with data inserted: ${teamAssignmentsWithData}. Previously found: ${existingScoutingData.length}`); if (teamAssignmentsWithData !== existingScoutingData.length) { logger.warn('Numbers do not match!!!'); diff --git a/primary/src/routes/manage/manualdata.ts b/primary/src/routes/manage/manualdata.ts index 5f214e89..0a9d8584 100644 --- a/primary/src/routes/manage/manualdata.ts +++ b/primary/src/routes/manage/manualdata.ts @@ -78,6 +78,64 @@ router.post('/teams', wrap(async (req, res) => { return res.redirect('/manage?alert=Updated team list successfully.'); })); +/** + * Admin page to manually edit rankings currently in the DB + * @url /manage/manualdata/rankings + * @views manualdata/rankings + */ +router.get('/rankings', wrap(async (req, res) => { + logger.addContext('funcName', 'rankings[get]'); + logger.info('ENTER'); + + let eventKey = req.event.key; + + // 2020-02-08, M.O'C: Change 'currentrankings' into event-specific 'rankings' + let rankings: Ranking[] = await utilities.find('rankings', + {'event_key': eventKey}, + {sort:{rank: 1}} + ); + + res.render('./manage/manualdata/rankings', { + title: 'Adjust Rankings', + rankings, + }); +})); + +/** + * POST Method that increments or decrements a team's ranking value at a given event + * @param team_key Team being modified + * @param valueToAdd The amount to change the current ranking by (usually 1 or -1) + * @return the team key and the new value + */ +router.post('/updateteamranking', wrap(async (req, res) => { + //Check authentication for team admin level + if( !await req.authenticate( Permissions.ACCESS_TEAM_ADMIN ) ) return; + + logger.addContext('funcName', 'updateteamranking[post]'); + logger.info('ENTER'); + + const team_key = req.body.key; + const valueToAdd = parseInt(req.body.value); + const event_key = req.event.key; + + if (!team_key || !valueToAdd) throw new e.UserError('Provide a team_key and a value.'); + + let currentTeamValue: Ranking = await utilities.findOne('rankings', {team_key: team_key, event_key: event_key}); + + let newValue; + + if (currentTeamValue) { + newValue = currentTeamValue.rank + valueToAdd; + + logger.debug(`Setting ${team_key}'s value to ${newValue} for event ${event_key}`); + await utilities.update('rankings', {team_key: team_key}, {$set: {rank: newValue}}); + } + res.send({ + team_key: team_key, + value: newValue + }); +})); + /** * POST Method that fetches info on a team from TheBlueAlliance. * @param team_number Team number to fetch @@ -304,7 +362,8 @@ router.get('/matchresults', wrap(async (req, res) => { */ router.post('/matchresults', wrap(async (req, res) => { logger.addContext('funcName', 'matchresults[post]'); - + logger.info('ENTER'); + let event_key = req.event.key; const year = req.event.year; let event_year = req.event.year; @@ -351,15 +410,6 @@ router.post('/matchresults', wrap(async (req, res) => { continue; } - //Modify winning alliance - switch (userInputThisMatch.WinningAlliance) { - case 'red': match.winning_alliance = 'red'; break; - case 'blue': match.winning_alliance = 'blue'; break; - case '': match.winning_alliance = ''; break; - default: - throw new e.UserError(`Match ${match_key} WinningAlliance invalid (input: ${userInputThisMatch.WinningAlliance})`); - } - //If score_brakdown has not yet been created, create it now. if(!match.score_breakdown){ match.score_breakdown = { @@ -372,15 +422,34 @@ router.post('/matchresults', wrap(async (req, res) => { //Modify blue score match.alliances.blue.score = isNaN(parseInt(userInputThisMatch.BlueScore)) ? -1 : parseInt(userInputThisMatch.BlueScore); match.score_breakdown.blue.totalPoints = isNaN(parseInt(userInputThisMatch.BlueScore)) ? -1 : parseInt(userInputThisMatch.BlueScore); + //Modify blue fouls + match.score_breakdown.blue.foulPoints = isNaN(parseInt(userInputThisMatch.BlueFouls)) ? -1 : parseInt(userInputThisMatch.BlueFouls); //Modify red score match.alliances.red.score = isNaN(parseInt(userInputThisMatch.RedScore)) ? -1 : parseInt(userInputThisMatch.RedScore); match.score_breakdown.red.totalPoints = isNaN(parseInt(userInputThisMatch.RedScore)) ? -1 : parseInt(userInputThisMatch.RedScore); + //Modify red fouls + match.score_breakdown.red.foulPoints = isNaN(parseInt(userInputThisMatch.RedFouls)) ? -1 : parseInt(userInputThisMatch.RedFouls); // Ranking points for (let rp of rankingpoints.attributes) { match.score_breakdown.blue[rp.name] = !!userInputThisMatch[`Blue${rp.name}`]; // ex: BluecompleteRocketRankingPoint match.score_breakdown.red[rp.name] = !!userInputThisMatch[`Red${rp.name}`]; } + //Modify winning alliance + // 2024-03-18, M.O'C: Calculating winning alliance based on the scores + // switch (userInputThisMatch.WinningAlliance) { + // case 'red': match.winning_alliance = 'red'; break; + // case 'blue': match.winning_alliance = 'blue'; break; + // case '': match.winning_alliance = ''; break; + // default: + // throw new e.UserError(`Match ${match_key} WinningAlliance invalid (input: ${userInputThisMatch.WinningAlliance})`); + // } + match.winning_alliance = ''; + if (match.alliances.blue.score > match.alliances.red.score) + match.winning_alliance = 'blue'; + if (match.alliances.red.score > match.alliances.blue.score) + match.winning_alliance = 'red'; + match.manually_entered = true; // 2023-02-20 JL: added manually entered } diff --git a/primary/src/routes/manage/orgconfig.ts b/primary/src/routes/manage/orgconfig.ts index b4d39541..ed1f38f3 100644 --- a/primary/src/routes/manage/orgconfig.ts +++ b/primary/src/routes/manage/orgconfig.ts @@ -5,7 +5,7 @@ import wrap from '../../helpers/express-async-handler'; import type { MongoDocument } from 'scoutradioz-utilities'; import utilities from 'scoutradioz-utilities'; import Permissions from '../../helpers/permissions'; -import e, { assert } from 'scoutradioz-http-errors'; +import e, { HttpError, assert } from 'scoutradioz-http-errors'; import type { Layout, LayoutEdit, MatchScouting, MatchFormData } from 'scoutradioz-types'; import type { DeleteResult, InsertManyResult } from 'mongodb'; import { getSubteamsAndClasses } from '../../helpers/orgconfig'; @@ -25,10 +25,17 @@ router.all('/*', wrap(async (req, res, next) => { router.get('/', wrap(async (req, res) => { const org = req._user.org; + + // Get a list of the team numbers at this org + let team_numbers: string[] = []; + if (org.team_key) team_numbers.push(org.team_key.substring(3)); + if (org.team_keys) team_numbers.push(...org.team_keys.map(key => key.substring(3))); + res.render('./manage/config/index', { - title: `Configure ${org.nickname}`, - org: org + title: req.msg('manage.config.title', {org: org.nickname}), + org, + team_numbers, }); })); @@ -36,58 +43,105 @@ router.get('/', wrap(async (req, res) => { router.post('/', wrap(async (req, res) => { logger.addContext('funcName', 'root[post]'); - const org_key = req.body.org_key; - const nickname = req.body.nickname; - - assert(org_key === req._user.org.org_key, new e.UnauthorizedError(`Unauthorized to edit org ${org_key}`)); - - logger.info(`Updating org ${org_key}, nickname=${nickname}`); - - let subteams, classes, uniqueClassKeys, uniqueSubteamKeys; try { - let ret = getSubteamsAndClasses(req.body); - subteams = ret.subteams; - classes = ret.classes; - uniqueClassKeys = ret.uniqueClassKeys; - uniqueSubteamKeys = ret.uniqueSubteamKeys; - } - catch (err) { - return res.redirect(`/manage/config?alert=${err}&type=error`); - } - logger.debug(`subteams=${JSON.stringify(subteams)} classes=${JSON.stringify(classes)}`); - - // Check for users which don't have a class key or subteam key in the list - let usersWithInvalidKeys = await utilities.find('users', { - org_key, - visible: true, - $or: [ - { 'org_info.class_key': { $not: { $in: uniqueClassKeys } } }, - { 'org_info.subteam_key': { $not: { $in: uniqueSubteamKeys } } } - ] - }); - //Create update query - let updateQuery: MongoDocument = { - $set: { - nickname: nickname, - 'config.members.subteams': subteams, - 'config.members.classes': classes, - }, - }; + const org_key = req.body.org_key; + const nickname = req.body.nickname; + + assert(org_key === req._user.org.org_key, new e.UnauthorizedError(`Unauthorized to edit org ${org_key}`)); + + logger.info(`Updating org ${org_key}, nickname=${nickname}`); + let { subteams, classes, uniqueClassKeys, uniqueSubteamKeys } = getSubteamsAndClasses(req.body); + logger.debug(`subteams=${JSON.stringify(subteams)} classes=${JSON.stringify(classes)}`); + + // Get the list of team numbers provided + let teamNumbersStr = req.body.team_numbers; + assert(typeof teamNumbersStr === 'string', new e.UserError('Team numbers not provided')); + + // Parse the team numbers provided. If an empty string is provided, then assume that means no teams on the org. + let teamNumbers: number[] = []; + if (teamNumbersStr.trim() !== '') { + teamNumbers = teamNumbersStr.split(',').map(str => parseInt(str.trim())); + // Make sure they're all valid ints + assert(!teamNumbers.some(number => isNaN(number)), new e.UserError('Please enter a comma-separated list of FRC team numbers.')); + assert(teamNumbers.length < 20, new e.UserError('Too many team numbers provided! (Max = 20)')); + for (let team_number of teamNumbers) { + let team = await utilities.findOne('teams', {team_number}); + assert(team, new e.UserError(req.msg('manage.config.invalidTeams', {number: team_number}))); + } + } + + // Check for users which don't have a class key or subteam key in the list + let usersWithInvalidKeys = await utilities.find('users', { + org_key, + visible: true, + $or: [ + { 'org_info.class_key': { $not: { $in: uniqueClassKeys } } }, + { 'org_info.subteam_key': { $not: { $in: uniqueSubteamKeys } } } + ] + }); + + //Create update query + let updateQuery: MongoDocument = { + $set: { + nickname: nickname, + 'config.members.subteams': subteams, + 'config.members.classes': classes, + }, + }; + + // 1 team key and team number + if (teamNumbers.length === 1) { + updateQuery.$set.team_number = teamNumbers[0]; + updateQuery.$set.team_key = 'frc'+teamNumbers[0]; + // Remove the team_numbers/team_keys field + updateQuery.$unset = { + team_numbers: true, + team_keys: true, + }; + } + // No teams / team_keys provided + else if (teamNumbers.length === 0) { + updateQuery.$unset = { + team_numbers: true, + team_keys: true, + team_number: true, + team_key: true, + }; + } + // Multiple team keys and team numbers + else { + updateQuery.$set.team_numbers = teamNumbers; + updateQuery.$set.team_keys = teamNumbers.map(number => 'frc'+number); + updateQuery.$unset = { + team_number: true, + team_key: true, + }; + } - logger.debug(`updateQuery=${JSON.stringify(updateQuery)}`); + logger.debug(`updateQuery=${JSON.stringify(updateQuery)}`); - const writeResult = await utilities.update('orgs', - { org_key }, updateQuery - ); + const writeResult = await utilities.update('orgs', + { org_key }, updateQuery + ); - logger.debug(`writeResult=${JSON.stringify(writeResult)}`); + logger.debug(`writeResult=${JSON.stringify(writeResult)}`); - if (usersWithInvalidKeys.length === 0) { - res.redirect('/manage/config?alert=Updated successfully.&type=good'); + // 2024-04-04 JL: Changed to AJAX + if (usersWithInvalidKeys.length === 0) { + return res.status(200).send(req.msg('manage.config.updatedSuccessfully')); + } + else { + return res.status(200).send(req.msg('manage.config.updatedButFixSubteams')); + } } - else { - res.redirect('/manage/members?alert=Org config has updated, but one or more users will need to be updated due to subteam / class keys changing.\n- *Go through the list of users and make sure everyone has a subteam and class.\n- Click \'Update\' for each user that has been updated.*&type=error'); + catch (err) { + logger.error(err); + // 2024-04-04 JL: Changed to AJAX + if (err instanceof HttpError) + return res.status(err.status).send(String(err)); + else + return res.status(400).send(String(err)); } })); diff --git a/primary/src/routes/manage/scoutingaudit.ts b/primary/src/routes/manage/scoutingaudit.ts index 465c308a..d82cd299 100644 --- a/primary/src/routes/manage/scoutingaudit.ts +++ b/primary/src/routes/manage/scoutingaudit.ts @@ -294,12 +294,12 @@ router.post('/uploads/delete', wrap(async (req, res) => { router.get('/bymatch', wrap(async (req, res) => { - let eventKey = req.event.key; + let event_key = req.event.key; let org_key = req._user.org_key; // Get the *min* time of the as-yet-unresolved matches [where alliance scores are still -1] // 2024-01-27, M.O'C: Switch to *max* time of *resolved* matches [where alliance scores != -1] - let matches: Match[] = await utilities.find('matches', {event_key: eventKey, 'alliances.red.score': {$ne: -1}}, {sort: {'time': -1}}); + let matches: Match[] = await utilities.find('matches', {event_key, 'alliances.red.score': {$ne: -1}}, {sort: {'time': -1}}); // 2018-03-13, M.O'C - Fixing the bug where dashboard crashes the server if all matches at an event are done // 2024-02-06, M.O'C: Have to change 'latestTimestamp' to be *early* UNLESS matches have been played @@ -313,7 +313,7 @@ router.get('/bymatch', wrap(async (req, res) => { logger.debug('Per-match audit: latestTimestamp=' + latestTimestamp); // 2020-02-11, M.O'C: Renaming "scoringdata" to "matchscouting", adding "org_key": org_key, - let scoreData: MatchScouting[] = await utilities.find('matchscouting', {'org_key': org_key, 'event_key': eventKey, 'time': { $lt: latestTimestamp }}, { sort: {'time': 1, 'alliance': 1, 'team_key': 1} }); + let scoreData: MatchScouting[] = await utilities.find('matchscouting', {org_key, event_key, 'time': { $lt: latestTimestamp }}, { sort: {'time': 1, 'alliance': 1, 'team_key': 1} }); //Create array of matches for audit, with each match-team inside each match let audit = []; @@ -422,9 +422,27 @@ router.get('/spr', wrap(async (req, res) => { { 'event_key': eventKey, 'match_number': { '$gt': lookbacktoIndex, '$lt': lookforwardtoIndex }, 'score_breakdown': { '$ne': undefined } }, { sort: { match_number: -1 } }, {allowCache: true, maxCacheAge: 10} ); + + interface CompareTableItem { + match: Match, + blue?: { + errDiff: number; + errRatio: number; + orgTot: number; + frcTot: number; + reports: MatchScouting[], + }; + red?: { + errDiff: number; + errRatio: number; + orgTot: number; + frcTot: number; + reports: MatchScouting[], + }; + } // set up the return data table - we'll add alternating rows of FRC & scouting data - let returnCompareTable = []; + let returnCompareTable: CompareTableItem[] = []; // dictionary of scouts - each item should be keyed by scout name and contain (a) total matches scouted + (b) total error point diffs & ratios let scoutScoreDict: Dict<{count: number, avgDiff: number, avgRatio: number, totDiff: number, totRatio: number, sprIndex: number, sprScore: number}> = {}; @@ -439,6 +457,10 @@ router.get('/spr', wrap(async (req, res) => { let allianceArray: Array<'red'|'blue'> = ['red', 'blue']; for (let matchIdx = 0; matchIdx < matches.length; matchIdx++) { let thisMatch = matches[matchIdx]; + // 2024-04-04 JL: Prettying up data presentation + let thisCompareTableItem: CompareTableItem = { + match: thisMatch, + }; for (let allianceIdx = 0; allianceIdx < allianceArray.length; allianceIdx++) { let thisAlliance = allianceArray[allianceIdx]; @@ -560,10 +582,21 @@ router.get('/spr', wrap(async (req, res) => { logger.trace('FRC=' + JSON.stringify(frcRow)); logger.trace('Org=' + JSON.stringify(orgRow)); - returnCompareTable.push(frcRow); - returnCompareTable.push(orgRow); + // returnCompareTable.push(frcRow); + // returnCompareTable.push(orgRow); + thisCompareTableItem[thisAlliance] = { + errDiff, + errRatio, + frcTot, + orgTot, + reports: matchScoutReports, + }; } } + // Only add this match to the list if we have processed 1 or both of the alliances. + if (thisCompareTableItem.red || thisCompareTableItem.blue) { + returnCompareTable.push(thisCompareTableItem); + } } // what is the determinant? logger.debug(`matrix=${JSON.stringify(matrix)}`); @@ -580,7 +613,7 @@ router.get('/spr', wrap(async (req, res) => { for (let key in scoutScoreDict) { let thisSprIndex:number = scoutScoreDict[key].sprIndex; - scoutScoreDict[key].sprScore = Number(solution[thisSprIndex][0]); + scoutScoreDict[key].sprScore = Math.round(+solution[thisSprIndex][0] * 10)/10; } } catch (err) { @@ -590,7 +623,7 @@ router.get('/spr', wrap(async (req, res) => { // sort scoutScoreDict by sprScore let sortedValues:Array<{count: number, avgDiff: number, avgRatio: number, totDiff: number, totRatio: number, sprIndex: number, sprScore: number}> = Object.values(scoutScoreDict); // reverse sort! - sortedValues.sort((a, b) => b.sprScore - a.sprScore); + sortedValues.sort((a, b) => a.sprScore - b.sprScore); logger.trace('sortedValues=' + JSON.stringify(sortedValues)); // reconstruct scoutScoreDict diff --git a/primary/src/routes/reports.ts b/primary/src/routes/reports.ts index 5cd25357..720dcac5 100644 --- a/primary/src/routes/reports.ts +++ b/primary/src/routes/reports.ts @@ -40,10 +40,10 @@ router.get('/browseevents', wrap(async (req, res) => { if (!event_keys.includes(key)) event_keys.push(key); }); - const events = await utilities.find('events', {key: {$in: event_keys}}); + const events = await utilities.find('events', {key: {$in: event_keys}}, {sort: {start_date: -1}}); res.render('./reports/browseevents', { - title: 'WIP - Browse events', + title: req.msg('reports.browsePastEvents'), events }); })); diff --git a/primary/src/routes/scouting.ts b/primary/src/routes/scouting.ts index b36cfc9f..f62c15ec 100644 --- a/primary/src/routes/scouting.ts +++ b/primary/src/routes/scouting.ts @@ -25,7 +25,7 @@ router.get('/match*', wrap(async (req, res) => { logger.info('ENTER'); let eventKey = req.event.key; - let eventYear = req.event.year; + let year = req.event.year; let thisUser = req._user; let thisUserName = thisUser.name; let match_team_key = req.query.key; @@ -45,17 +45,18 @@ router.get('/match*', wrap(async (req, res) => { //check if there is already data for this match // 2020-02-11, M.O'C: Renaming "scoringdata" to "matchscouting", adding "org_key": org_key, - let scoringdata: MatchScouting[] = await utilities.find('matchscouting', {'org_key': org_key, 'year' : eventYear, 'match_team_key': match_team_key}, {sort: {'order': 1}}); + let assignment = await utilities.findOne('matchscouting', {org_key, year, match_team_key}, {}); //scouting answers for this match are initialized as null for visibility let answers: MatchFormData|null = null; - if( scoringdata && scoringdata[0] ){ + if( assignment ){ + alliance = assignment.alliance; // 2024-04-06 JL: Pull alliance from matchscouting entry if possible to not rely on url //if we have data for this match, - let data = scoringdata[0].data; + let data = assignment.data; if(data){ - logger.debug(`data: ${JSON.stringify(scoringdata[0].data)}`); + logger.debug(`data: ${JSON.stringify(data)}`); //set answers to data if exists answers = data; } @@ -67,13 +68,14 @@ router.get('/match*', wrap(async (req, res) => { //load layout // 2020-02-11, M.O'C: Combined "scoringlayout" into "layout" with an org_key & the type "matchscouting" let layout: Layout[] = await utilities.find('layout', - {org_key: org_key, year: eventYear, form_type: 'matchscouting'}, + {org_key: org_key, year: year, form_type: 'matchscouting'}, {sort: {'order': 1}}, {allowCache: true} ); + + let groupedLayout = splitLayoutIntoGroups(layout); - - const images = await uploadHelper.findTeamImages(org_key, eventYear, teamKey); + const images = await uploadHelper.findTeamImages(org_key, year, teamKey); let team: Team = await utilities.findOne('teams', {key: teamKey}, {}, {allowCache: true}); // 2024-02-29, M.O'C: if the teamKey is the same as the demoTeamKey, set the 'team' @@ -102,7 +104,8 @@ router.get('/match*', wrap(async (req, res) => { if (!team) throw new e.UserError(req.msg('scouting.invalidTeam', {team: teamKey})); let allianceLocale = (alliance.toLowerCase().startsWith('b')) ? req.msg('alliance.blueShort') : req.msg('alliance.redShort'); - let title = `#${scoringdata[0]?.match_number} - ${teamKey.substring(3)} ${allianceLocale} | ${req.msg('scouting.match')}`; + let matchNumber = assignment?.match_number || match_team_key.split('_')[1]?.substring(2); // In case the matchscouting assignment isn't in the db + let title = `#${matchNumber} - ${teamKey.substring(3)} ${allianceLocale} | ${req.msg('scouting.match')}`; // 2024-02-05, M.O'C: Add super-scout pit text to page let pitFind = await utilities.findOne('pitscouting', { 'org_key': org_key, 'event_key' : eventKey, 'team_key' : teamKey }, {}); @@ -113,14 +116,15 @@ router.get('/match*', wrap(async (req, res) => { //render page res.render('./scouting/match', { title: title, - layout: layout, + layout, + groupedLayout, key: match_team_key, - alliance: alliance, - answers: answers, - teamKey: teamKey, - images: images, + alliance, + answers, + teamKey, + images, team: team, - pit_super_data: pit_super_data + pit_super_data, }); })); @@ -171,11 +175,13 @@ router.post('/testform', wrap(async (req, res) => { website: null }; - if (form_type == 'matchscouting') - //render page + //render page + if (form_type == 'matchscouting') { + let groupedLayout = splitLayoutIntoGroups(layout); res.render('./scouting/match', { title: req.msg('scouting.match'), layout: layout, + groupedLayout, key: match_team_key, alliance: alliance, answers: null, @@ -183,6 +189,7 @@ router.post('/testform', wrap(async (req, res) => { images: null, team: team, }); + } else res.render('./scouting/pit', { title: req.msg('scouting.pit'), @@ -651,4 +658,23 @@ router.post('/match/delete-data', wrap(async (req, res) => { } })); +// Split the layout into groups, based on the header, making it easier to do the dynamic scrolling +function splitLayoutIntoGroups(layout: Layout[]) { + + let groupedLayout = layout.reduce((list, current) => { + if (current.type === 'h2') { + list.push({ + label: current.label || 'unknown', + items: [current] + }); + } + else { + let idx = list.length - 1; + list[idx].items.push(current); + } + return list; + }, [{label: 'Unknown', items: []}] as Array<{label: string, items: Layout[]}>); + return groupedLayout; +} + module.exports = router; \ No newline at end of file diff --git a/primary/views/aprilfools.pug b/primary/views/aprilfools.pug new file mode 100644 index 00000000..f7feb3a6 --- /dev/null +++ b/primary/views/aprilfools.pug @@ -0,0 +1,27 @@ +extends layout +block content + style. + #container { + margin: auto; + max-width: 100%; + } + #img { + width: 560px; + max-width: 100%; + aspect-ratio: 1.7777; + } + h2 Fully Automated Scouting with Generative AI (April Fools 2024) + section(style="max-width: 1200px; margin: auto") + p.i Scouting in robotics competitions just got a whole lot easier with Scoutradioz' revolutionary new fully automated scouting feature. Powered by advanced AI technology, this game-changing addition takes the hassle out of data collection, allowing teams to focus on strategy and innovation. + p.i Our AI model, codenamed Scott, trained through generative AI and prompt engineering, analyzes match footage in real-time, extracting valuable insights effortlessly. From movement patterns to scoring capabilities, our system does it all, providing actionable insights and predictions to give teams a competitive edge. + p.i Customizable and rigorously tested for accuracy and reliability, our automated scouting feature is the future of robotics competition. Ready to revolutionize your scouting process? Try it today and elevate your game. + p.i Check out our video explaining how it works and join us in shaping the future of robotics competition! + + div#container + a(href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" target="_blank") + img#img(src=`${fileRoot}/images/april-fools-thumbnail.png`) + + h3 Try it out now! + + p.i You must watch the introductory video before proceeding! + button(class=`w3-btn theme-dim w3-btn disabled` disabled) Try generative AI match scouting \ No newline at end of file diff --git a/primary/views/browse.pug b/primary/views/browse.pug new file mode 100644 index 00000000..338f085a --- /dev/null +++ b/primary/views/browse.pug @@ -0,0 +1,54 @@ +//- + Browse Data by Event page (including scouting coverage & accuracy) + '/browse' + // +extends ./layout +include ./reports/mixins/metricTables +block content + style. + table { + margin: auto; + border-collapse: collapse; + overflow-x: scroll; + } + td, th { + padding: 8px; + text-align: left; + border-left: 1px solid rgba(255, 255, 255, 0.2); + } + th { + max-width: 80px; + } + tr:nth-child(odd) { + background: rgba(255, 255, 255, 0.2) + } + div(class="w3-auto") + h2!=msg('index.browse.title') + h6!=msgMarked('index.browse.pastEvents') + hr + i + h6!=msgMarked('index.browse.tspsExplained') + each event, i in event_scouting + div.w3-padding + h3= event.eventName + + table(class="W3-table") + tr + th(style="max-width: unset;")=msg('index.browse.orgKeyAndNickname') + th=msg('index.browse.matchScoutingEntries') + th=msg('index.browse.avgErrorRate') + th=msg('index.browse.tspsScore') + each org, i in event.orgData + tr + - let orgKeyAndNick = org.orgKey + ' - ' + org.orgName + td + u + a(href=`/${org.orgKey}/reports/allteammetrics`)=orgKeyAndNick + - let orgScout = org.countScoutingReports + ' (' + ((Math.round((100 * org.countScoutingReports/event.possibleScoutingReports) * 10)/10).toFixed(1)) + '%)' + td=orgScout + - let orgSpr = '------------------' + - if (!isNaN(org.medianSpr) && !isNaN(org.minSpr) && !(org.medianSpr == 0.0 && org.minSpr == 0.0)) orgSpr = ((Math.round(org.medianSpr * 100)/100).toFixed(2)) + ' (' + ((Math.round(org.minSpr * 100)/100).toFixed(2)) + ')' + td=orgSpr + - let orgTsps = '---' + - if (org.tsps) orgTsps = (Math.round(org.tsps * 1000)/1000).toFixed(3) + td=orgTsps diff --git a/primary/views/dashboard/allianceselection-info.pug b/primary/views/dashboard/allianceselection-info.pug index 8f8d1063..e4328b62 100644 --- a/primary/views/dashboard/allianceselection-info.pug +++ b/primary/views/dashboard/allianceselection-info.pug @@ -22,6 +22,7 @@ if (aggdata) for scoreItem in currentAggRanges - aggRangeMap[scoreItem.key] = scoreItem; + p.i=msg('allianceselection.tapForPopup') +metricSwitcher() p each key in ['AVG', 'MAX'] @@ -44,7 +45,8 @@ if (aggdata) td(class="w3-center")= row.value - var style = ''; // class to add to the team number; strikethrough if less than 0, bold if 1, bolder if >1 - if (row.value < 0) style = 'strike'; else if (row.value > 1) style = 'stronger'; else if (row.value > 0) style = 'strong'; - td(class=("w3-center " + style))= row._id.substring(3) + //- Team number + td(class=("w3-center underline clickable " + style) team-key=row._id)= row._id.substring(3) td(class="w3-right-align")= row.rank for item in layout -//if (item.type == 'checkbox' || item.type == 'counter' || item.type == 'badcounter') diff --git a/primary/views/dashboard/allianceselection.pug b/primary/views/dashboard/allianceselection.pug index dc60c424..18c493a2 100644 --- a/primary/views/dashboard/allianceselection.pug +++ b/primary/views/dashboard/allianceselection.pug @@ -38,104 +38,123 @@ block content transition: 0s; } h2=title - div(class="w3-mobile w3-center") - p.i!=msg('allianceselection.intro') - p.i!=msgMarked('allianceselection.preferred') - if !matchcountConsistent - a(href="/manage/currentevent/matches") - div(class="w3-btn theme-red") WARNING: Rankings appear NOT to be up to date!
Click here, update FIRST data before using for selection - div(class="w3-row w3-padding-small") - div(class="w3-left") - div(id="btnUndo" class="w3-btn theme-submit")!=msg('allianceselection.undo') - div(class="w3-right") - div(id="btnOptions" class="w3-btn theme-input")!=msg('allianceselection.options', undefined, '\xa0') - section(class="w3-row") - div(id="allianceSelection") - each alliance, i in alliances - - var allianceNum = i + 1; - div(class="w3-padding-small w3-col s12 m6 l3") - div(class="theme-dim w3-padding-large w3-col") - div(class="w3-col s0 m12")!=msg('allianceselection.allianceNumber', {number: allianceNum}) - div(class="w3-col s2 m0") - p(class="w3-large") #{allianceNum} - div(class="w3-col s10 m12") - div(class="w3-col s4 w3-padding-small") - div(id=alliance[0] alliance=allianceNum available="true" class="alliance-team w3-border w3-border-white") - span=alliance[0].substring(3) - - var teamIndex = 1 // starts at 2 - while ++teamIndex <= numRounds - - team = alliance[teamIndex] + //- Dropdown to pick between team_keys at the org + if orgTeamKeys && orgTeamKeys.length > 1 + form#teamKeyForm(class="w3-container w3-padding-16" method="get" action="/dashboard/allianceselection") + label(class="w3-label") + span(class="sprite sp-help sp-inline sp-16 w3-tooltip")   + span(class="w3-tooltiptext")!=msg('allianceselection.tooltipPicklist') + span=msg('allianceselection.choosePicklist') + select(class="theme-input" name="picklist_key") + //- Show blank by default, require user to select their team from the dropdown + if !picklist_key + option(selected value="") + each thisTeamKey in orgTeamKeys + option(value=thisTeamKey selected=(picklist_key === thisTeamKey))=thisTeamKey.substring(3) + script. + $('select[name=picklist_key]').on('change', () => { + $('#teamKeyForm').trigger('submit'); + }); + //- Display the rest of the page only if picklist_key is specified OR if there's only 1 team on the org + if !orgTeamKeys || picklist_key + div(class="w3-mobile w3-center") + p.i!=msg('allianceselection.intro') + p.i!=msgMarked('allianceselection.preferred') + if !matchcountConsistent + a(href="/manage/currentevent/matches") + div(class="w3-btn theme-red") WARNING: Rankings appear NOT to be up to date!
Click here, update FIRST data before using for selection + div(class="w3-row w3-padding-small") + div(class="w3-left") + div(id="btnUndo" class="w3-btn theme-submit")!=msg('allianceselection.undo') + div(class="w3-right") + div(id="btnOptions" class="w3-btn theme-input")!=msg('allianceselection.options', undefined, '\xa0') + section(class="w3-row") + div(id="allianceSelection") + each alliance, i in alliances + - var allianceNum = i + 1; + div(class="w3-padding-small w3-col s12 m6 l3") + div(class="theme-dim w3-padding-large w3-col") + div(class="w3-col s0 m12")!=msg('allianceselection.allianceNumber', {number: allianceNum}) + div(class="w3-col s2 m0") + p(class="w3-large") #{allianceNum} + div(class="w3-col s10 m12") div(class="w3-col s4 w3-padding-small") - div(id=`all${allianceNum}team${teamIndex}` alliance=allianceNum class="alliance-team w3-border w3-border-white") - span=(team) ? team.substring(3) : `[${teamIndex}]` - hr(class="w3-col") - div(class="w3-col") - each team, i in sortedTeams - div(class="w3-col s4 m2 l1 w3-padding-small") - div(id=team.team_key available="true" class="theme-dim alliance-team w3-border w3-border-white") - span=team.team_key.substring(3) - hr(class="") - - div(class="w3-section") - input(class="w3-check w3-margin-right" type="checkbox" checked id="showHideData") - label(for="showHideData")!=msg('allianceselection.showData') - div#data() - include allianceselection-info + div(id=alliance[0] alliance=allianceNum available="true" class="alliance-team w3-border w3-border-white") + span=alliance[0].substring(3) + - var teamIndex = 1 // starts at 2 + while ++teamIndex <= numRounds + - team = alliance[teamIndex] + div(class="w3-col s4 w3-padding-small") + div(id=`all${allianceNum}team${teamIndex}` alliance=allianceNum class="alliance-team w3-border w3-border-white") + span=(team) ? team.substring(3) : `[${teamIndex}]` + hr(class="w3-col") + div(class="w3-col") + each team, i in sortedTeams + div(class="w3-col s4 m2 l1 w3-padding-small") + div(id=team.team_key available="true" class="theme-dim alliance-team w3-border w3-border-white") + span=team.team_key.substring(3) + hr + + div(class="w3-section") + input(class="w3-check w3-margin-right" type="checkbox" checked id="showHideData") + label(for="showHideData")!=msg('allianceselection.showData') + div#data() + include allianceselection-info - hr - div(id="options") - div(class="w3-margin-top w3-show-inline-block w3-mobile") - label(class="w3-label" style="padding-right: 8px")!=msg('allianceselection.numAlliances') - select(class="theme-input" style="min-width: 100;" name="numAlliances" id="numAlliances") - - var n = 1; // starts at 2 - while ++n <= 8 - option(selected=(n == numAlliances) value=n)=n - span(class="w3-hide-small")   - div(class="w3-margin-top w3-show-inline-block w3-mobile") - label(class="w3-label" style="padding-right: 8px")!=msg('allianceselection.numRounds') - select(class="theme-input" style="min-width: 100;" name="numRounds" id="numRounds") - - var n = 1; // starts at 2 - while ++n <= 4 - option(selected=(n == numRounds) value=n)=n + hr + div(id="options") + div(class="w3-margin-top w3-show-inline-block w3-mobile") + label(class="w3-label" style="padding-right: 8px")!=msg('allianceselection.numAlliances') + select(class="theme-input" style="min-width: 100;" name="numAlliances" id="numAlliances") + - var n = 1; // starts at 2 + while ++n <= 8 + option(selected=(n == numAlliances) value=n)=n + span(class="w3-hide-small")   + div(class="w3-margin-top w3-show-inline-block w3-mobile") + label(class="w3-label" style="padding-right: 8px")!=msg('allianceselection.numRounds') + select(class="theme-input" style="min-width: 100;" name="numRounds" id="numRounds") + - var n = 1; // starts at 2 + while ++n <= 4 + option(selected=(n == numRounds) value=n)=n - script. - //create selection state - window.state = {}; - numAlliances = parseInt(#{numAlliances}); - console.log(`numAlliances=${numAlliances}`); - numRounds = parseInt(#{numRounds}); - //CURRENTLY UNUSED - //state.alliances = [["#{alliances[0][0]}""]]; - //Starting alliance 1 captain, before any user input - window.startingCaptain = "#{alliances[0][0]}"; + script. + //create selection state + window.state = {}; + numAlliances = parseInt(#{numAlliances}); + console.log(`numAlliances=${numAlliances}`); + numRounds = parseInt(#{numRounds}); + //CURRENTLY UNUSED + //state.alliances = [["#{alliances[0][0]}""]]; + //Starting alliance 1 captain, before any user input + window.startingCaptain = "#{alliances[0][0]}"; + + state.rankings = [null]; + //currently selected team + state.currentSelectedTeam = null; + //history of selected teams + /* + [ + { + "teamKey": "frc102", + "previousSpot": rank before selected, + "allianceSpot": 2 or 3 + } + ] + */ + state.moveHistory = []; + //round 0 goes from alliance 1 to 8; round 1 goes from alliance 8 to 1 + state.currentRound = 0; + //current alliance that is choosing a team + state.currentAlliance = 1; + //Previous states of allianceSelection + var previousStates = []; - state.rankings = [null]; - //currently selected team - state.currentSelectedTeam = null; - //history of selected teams - /* - [ - { - "teamKey": "frc102", - "previousSpot": rank before selected, - "allianceSpot": 2 or 3 - } - ] - */ - state.moveHistory = []; - //round 0 goes from alliance 1 to 8; round 1 goes from alliance 8 to 1 - state.currentRound = 0; - //current alliance that is choosing a team - state.currentAlliance = 1; - //Previous states of allianceSelection - var previousStates = []; - - // i18n messages used by client script - window.i18n = {}; - | - script(src=`${fileRoot}/js/script-allianceselection.js?v`) \ No newline at end of file + // i18n messages used by client script + window.i18n = {}; + | + script(src=`${fileRoot}/js/script-allianceselection.js?v${functionVersion}`) \ No newline at end of file diff --git a/primary/views/dashboard/driveteam.pug b/primary/views/dashboard/driveteam.pug index 47b26844..8d83c6de 100644 --- a/primary/views/dashboard/driveteam.pug +++ b/primary/views/dashboard/driveteam.pug @@ -1,285 +1,296 @@ -//- - Drive team dashboard shows upcoming matches for a particular team, - and shows alliance stats for the first match. - dashboard.js - '/dashboard/driveteam' - QUERY: [optional] team_key (team key; defaults to org's team) - // -extends ../layout -block content - script(src=`${fileRoot}/lib/chart.min.js?v=1`) - style. - html{ - overflow-x: visible; - } - .radar-canvas{ - /* 2022-03-19 JL: Not sure what changed from chartjs v2.9 to v3.7, but to keep the same - aspect ratio as before, we need to give the canvases some horizontal padding */ - margin: 0 6%; - } - include ../reports/templates/heatmap - include ../reports/mixins/upcomingMatch - - if !teams || !teams[0] - h3!=msg('driveDashboard.noTeams') - else - h3=title - if noMatchesFoundForTeam - p.i!=msg('driveDashboard.noMatchesTeam', {team: selectedTeam.substring(3)}) - - selectedTeam = 'all'; - else - br - //- Dashboard for other teams - div(class="w3-section") - form(name="driveDashboardTeam" method="get" action="/dashboard/driveteam") - span(class="w3-mobile w3-margin-top") - label(class="w3-label" style="padding-right: 8px")!=msg('driveDashboard.viewFor') - select(class="theme-input" style="min-width: 100;" name="team_key") - noscript - if selectedTeam == 'all' - option(selected value='all')!=msg('driveDashboard.chooseTeam') - //- else - option(value='all') All teams - each team in teams - if team.key == selectedTeam - option(selected value=team.key)=team.team_number - else - option(value=team.key)=team.team_number - noscript - //- JL: I made the multiselect auto-submit on change, but to make it still work in browsers with JS disabled, this submit button will act in its place. - button(class="w3-btn theme-submit w3-margin-left" type="submit" name="selected" value="true")!=msg('driveDashboard.selectedTeam') - span(class="w3-mobile w3-margin-top") - label(class="w3-label w3-margin-left" style="padding-right: 8px")!=msg('driveDashboard.viewOr') - button(class="w3-btn theme-submit" type="submit" name="all" value="true")!=msg('driveDashboard.allTeams') - br - if selectedTeam == 'all' - h4!=msg('driveDashboard.nextMatch') - else - h4!=msg('driveDashboard.nextMatchTeam', {team: selectedTeam.substring(3)}) - //- Check if there are any matches - if !matches || !matches[0] - h3!=msg('driveDashboard.noMatches') - else - //- View first match - - var match = matches[0]; - +upcomingMatch(match, undefined, selectedTeam) - hr - //-Radar - div(class="w3-section w3-auto") - h4!=msg('driveDashboard.relativeStrengths') - h6 - i!=msg('driveDashboard.legendShowHide') - div - div(class="w3-mobile w3-show-inline-block" style="width: 50%;") - h5!=msg('alliance.red') - canvas(id="RadarRedAlliance" class="radar-canvas" width="250" height="215") - div(class="w3-mobile w3-show-inline-block" style="width: 50%;") - h5!=msg('alliance.blue') - canvas(id="RadarBlueAlliance" class="radar-canvas" width="250" height="215") - //-Table - div(class="w3-section") - h4!=msg('metrics.raw') - div - span!=msg('metrics.show') - input(type="radio" id="showAvg" name="sel" onclick="showAvg();" checked) - label(for="showAvg")!=msg('metrics.AVG') - input(type="radio" id="showMax" name="sel" onclick="showMax();") - label(for="showMax")!=msg('metrics.MAX') - p - - var aggRangeMap = []; - for scoreItem in currentAggRanges - - aggRangeMap[scoreItem.key] = scoreItem; - div#avgSect(class="w3-auto") - if (avgdata) - table(class="w3-table" style="max-width: 80%;") - tr - th(style="padding-left: 0; width: 25%;" class="w3-right-align")!=msg('metrics.metricAVG') - for team in teamList - if team == 0 - th - else - th(class="w3-center" style="padding: 8px 4px; width: 11%;") - u - a(href=`/reports/teamintel?team_key=${team}`)= team.substring(3) - each agg in avgdata - tr - - var text = agg.key; var result1 = text.replace( /([A-Z])/g, " $1" ); var result2 = result1.charAt(0).toUpperCase() + result1.slice(1) - td(class="w3-text-light-gray w3-small w3-right-align" style="padding-left: 0;") - a(href=`/reports/metricintel?key=${agg.key}`)= result2 - for team in teamList - if team == 0 - th - else - - var valueCol = 'w3-center w3-text-white' - - if (agg[team] == 0) valueCol = 'w3-center w3-text-gray' - if (aggRangeMap[agg.key]) - td(class=`${valueCol}` style=`padding: 8px 0px; background-color: rgb(${getValR(aggRangeMap[agg.key].AVGmin, aggRangeMap[agg.key].AVGmax, agg[team])},${getValG(aggRangeMap[agg.key].AVGmin, aggRangeMap[agg.key].AVGmax, agg[team])},${getValB(aggRangeMap[agg.key].AVGmin, aggRangeMap[agg.key].AVGmax, agg[team])})`)= agg[team] - else - td(class=`${valueCol}`)= agg[team] - div#maxSect(class="w3-auto") - if (maxdata) - table(class="w3-table" style="max-width: 80%;") - tr - th(style="padding-left: 0; width: 25%;" class="w3-right-align")!=msg('metrics.metricMAX') - for team in teamList - if team == 0 - th - else - th(class="w3-center" style="padding: 8px 4px; width: 11%;") - u - a(href=`/reports/teamintel?team_key=${team}`)= team.substring(3) - each agg in maxdata - tr - - var text = agg.key; var result1 = text.replace( /([A-Z])/g, " $1" ); var result2 = result1.charAt(0).toUpperCase() + result1.slice(1) - td(class="w3-text-light-gray w3-small w3-right-align" style="padding-left: 0;") - a(href=`/reports/metricintel?key=${agg.key}`)= result2 - for team in teamList - if team == 0 - td - else - - var valueCol = 'w3-center w3-text-white' - - if (agg[team] == 0) valueCol = 'w3-center w3-text-gray' - if (aggRangeMap[agg.key]) - td(class=`${valueCol}` style=`padding: 8px 0px; background-color: rgb(${getValR(aggRangeMap[agg.key].MAXmin, aggRangeMap[agg.key].MAXmax, agg[team])},${getValG(aggRangeMap[agg.key].MAXmin, aggRangeMap[agg.key].MAXmax, agg[team])},${getValB(aggRangeMap[agg.key].MAXmin, aggRangeMap[agg.key].MAXmax, agg[team])})`)= agg[team] - else - td(class=`${valueCol}`)= agg[team] - //-Super-scout notes - - if (user && user.role.access_level >= Permissions.ACCESS_SCOUTER) - if pitData && pitData[0] - each pit in pitData - div(style="white-space: pre-wrap;") - h4!=msg('scouting.supernotes', {team: pit.team_key.substring(3)}) - i - p= pit.super_data.otherNotes - - hr - if selectedTeam == 'all' - h4!=msg('driveDashboard.futureMatches') - else - h4!=msg('driveDashboard.futureMatchesTeam', {team: selectedTeam.substring(3)}) - each match, i in matches - //-Skip first match - if (i > 0) - +upcomingMatch(match, undefined, selectedTeam) - hr - - script var chartData = JSON.parse('!{dataForChartJS}'); - //- script. - console.log(JSON.parse(JSON.stringify(chartData))); - script. - //- Chart.defaults.global.defaultFontStyle = 'bold'; - //- Chart.defaults.global.defaultFontColor = '#DDD'; - Chart.defaults.font.weight = 'bold'; - Chart.defaults.color = '#DDD'; - - var redData = { - labels: chartData.labels, - datasets: [ - { - data: chartData.datasets.avg.red[0], - label: chartData.items.red[0].label, - backgroundColor: chartData.items.red[0].backgroundColor, - borderColor: chartData.items.red[0].borderColor, - }, - { - data: chartData.datasets.avg.red[1], - label: chartData.items.red[1].label, - backgroundColor: chartData.items.red[1].backgroundColor, - borderColor: chartData.items.red[1].borderColor, - }, - { - data: chartData.datasets.avg.red[2], - label: chartData.items.red[2].label, - backgroundColor: chartData.items.red[2].backgroundColor, - borderColor: chartData.items.red[2].borderColor, - }, - ], - }; - var blueData = { - labels: chartData.labels, - datasets: [ - { - data: chartData.datasets.avg.blue[0], - label: chartData.items.blue[0].label, - backgroundColor: chartData.items.blue[0].backgroundColor, - borderColor: chartData.items.blue[0].borderColor, - }, - { - data: chartData.datasets.avg.blue[1], - label: chartData.items.blue[1].label, - backgroundColor: chartData.items.blue[1].backgroundColor, - borderColor: chartData.items.blue[1].borderColor, - }, - { - data: chartData.datasets.avg.blue[2], - label: chartData.items.blue[2].label, - backgroundColor: chartData.items.blue[2].backgroundColor, - borderColor: chartData.items.blue[2].borderColor, - }, - ], - }; - - var redCtx = $('#RadarRedAlliance')[0].getContext('2d'); - var blueCtx = $('#RadarBlueAlliance')[0].getContext('2d'); - - var redRadar = new Chart(redCtx, { - type: 'radar', - data: redData, - options: chartData.options - }); - var blueRadar = new Chart(blueCtx, { - type: 'radar', - data: blueData, - options: chartData.options - }); - - showAvg(); - - function showAvg() { - var avg = document.getElementById('avgSect'); - avg.style.display = "block"; - var max = document.getElementById('maxSect'); - max.style.display = "none"; - - for (var i in redRadar.data.datasets) { - var set = redRadar.data.datasets[i]; - if (set.hasOwnProperty("data")) { - set.data = chartData.datasets.avg.red[i]; - } - } - redRadar.update(); - for (var i in blueRadar.data.datasets) { - var set = blueRadar.data.datasets[i]; - if (set.hasOwnProperty("data")) { - set.data = chartData.datasets.avg.blue[i]; - } - } - blueRadar.update(); - } - - function showMax() { - var avg = document.getElementById('avgSect'); - avg.style.display = "none"; - var max = document.getElementById('maxSect'); - max.style.display = "block"; - - for (var i in redRadar.data.datasets) { - var set = redRadar.data.datasets[i]; - if (set.hasOwnProperty("data")) { - set.data = chartData.datasets.max.red[i]; - } - } - redRadar.update(); - for (var i in blueRadar.data.datasets) { - var set = blueRadar.data.datasets[i]; - if (set.hasOwnProperty("data")) { - set.data = chartData.datasets.max.blue[i]; - } - } - blueRadar.update(); - } - - //- Multiselect for selecting team_key - Auto submit when it changes - $('select[name=team_key]').on('change', () => { - $('form[name=driveDashboardTeam]').submit(); +//- + Drive team dashboard shows upcoming matches for a particular team, + and shows alliance stats for the first match. + dashboard.js + '/dashboard/driveteam' + QUERY: [optional] team_key (team key; defaults to org's team) + // +extends ../layout +block content + script(src=`${fileRoot}/lib/chart.umd.js?v=0`) + style. + html{ + overflow-x: visible; + } + /* 2024-03-13 JL: Fixed charts displaying wrong on Firefox by changing the way they are positioned to use flexbox */ + .radar-canvas{ + max-width: 100%; + } + .radar-chart-parent { + display: flex; + flex-flow: row wrap; + } + .radar-chart { + flex: 1 0 50%; + } + @media(max-width: 600px) { + .radar-chart { + flex: 1 0 100%; + } + } + include ../reports/templates/heatmap + include ../reports/mixins/upcomingMatch + + if !teams || !teams[0] + h3!=msg('driveDashboard.noTeams') + else + h3=title + if noMatchesFoundForTeam + p.i!=msg('driveDashboard.noMatchesTeam', {team: selectedTeam.substring(3)}) + - selectedTeam = 'all'; + else + br + //- Dashboard for other teams + div(class="w3-section") + form(name="driveDashboardTeam" method="get" action="/dashboard/driveteam") + span(class="w3-mobile w3-margin-top") + label(class="w3-label" style="padding-right: 8px")!=msg('driveDashboard.viewFor') + select(class="theme-input" style="min-width: 100;" name="team_key") + if selectedTeam == 'all' + option(selected value='all')!=msg('driveDashboard.chooseTeam') + //- List of team keys in this org + if orgTeamKeys.length > 0 + each team_key in orgTeamKeys + option(value=team_key selected=(team_key === selectedTeam))=team_key.substring(3) + option ----- !{msg('driveDashboard.otherTeams')} ----- + each team in teams + if !orgTeamKeys.includes(team.key) + option(selected=(team.key === selectedTeam) value=team.key)=team.team_number + noscript + //- JL: I made the multiselect auto-submit on change, but to make it still work in browsers with JS disabled, this submit button will act in its place. + button(class="w3-btn theme-submit w3-margin-left" type="submit" name="selected" value="true")!=msg('driveDashboard.selectedTeam') + span(class="w3-mobile w3-margin-top") + label(class="w3-label w3-margin-left" style="padding-right: 8px")!=msg('driveDashboard.viewOr') + button(class="w3-btn theme-submit" type="submit" name="all" value="true")!=msg('driveDashboard.allTeams') + br + if selectedTeam == 'all' + h4!=msg('driveDashboard.nextMatch') + else + h4!=msg('driveDashboard.nextMatchTeam', {team: selectedTeam.substring(3)}) + //- Check if there are any matches + if !matches || !matches[0] + h3!=msg('driveDashboard.noMatches') + else + //- View first match + - var match = matches[0]; + +upcomingMatch(match, undefined, selectedTeam) + hr + //-Radar + div(class="w3-section w3-auto") + h4!=msg('driveDashboard.relativeStrengths') + h6 + i!=msg('driveDashboard.legendShowHide') + div(class="radar-chart-parent") + div(class="radar-chart") + h5!=msg('alliance.red') + canvas(id="RadarRedAlliance" class="radar-canvas") + div(class="radar-chart") + h5!=msg('alliance.blue') + canvas(id="RadarBlueAlliance" class="radar-canvas") + //-Table + div(class="w3-section") + h4!=msg('metrics.raw') + div + span!=msg('metrics.show') + input(type="radio" id="showAvg" name="sel" onclick="showAvg();" checked) + label(for="showAvg")  !{msg('metrics.AVG')} + input(type="radio" id="showMax" name="sel" onclick="showMax();") + label(for="showMax")  !{msg('metrics.MAX')} + p + - var aggRangeMap = []; + for scoreItem in currentAggRanges + - aggRangeMap[scoreItem.key] = scoreItem; + div#avgSect(class="w3-auto") + if (avgdata) + table(class="w3-table" style="max-width: 80%;") + tr + th(style="padding-left: 0; width: 25%;" class="w3-right-align")!=msg('metrics.metricAVG') + for team in teamList + if team == 0 + th + else + th(class="w3-center" style="padding: 8px 4px; width: 11%;") + u + a(href=`/reports/teamintel?team_key=${team}`)= team.substring(3) + each agg in avgdata + tr + - var text = agg.key; var result1 = text.replace( /([A-Z])/g, " $1" ); var result2 = result1.charAt(0).toUpperCase() + result1.slice(1) + td(class="w3-text-light-gray w3-small w3-right-align" style="padding-left: 0;") + a(href=`/reports/metricintel?key=${agg.key}`)= result2 + for team in teamList + if team == 0 + th + else + - var valueCol = 'w3-center w3-text-white' + - if (agg[team] == 0) valueCol = 'w3-center w3-text-gray' + if (aggRangeMap[agg.key]) + td(class=`${valueCol}` style=`padding: 8px 0px; background-color: rgb(${getValR(aggRangeMap[agg.key].AVGmin, aggRangeMap[agg.key].AVGmax, agg[team])},${getValG(aggRangeMap[agg.key].AVGmin, aggRangeMap[agg.key].AVGmax, agg[team])},${getValB(aggRangeMap[agg.key].AVGmin, aggRangeMap[agg.key].AVGmax, agg[team])})`)= agg[team] + else + td(class=`${valueCol}`)= agg[team] + div#maxSect(class="w3-auto") + if (maxdata) + table(class="w3-table" style="max-width: 80%;") + tr + th(style="padding-left: 0; width: 25%;" class="w3-right-align")!=msg('metrics.metricMAX') + for team in teamList + if team == 0 + th + else + th(class="w3-center" style="padding: 8px 4px; width: 11%;") + u + a(href=`/reports/teamintel?team_key=${team}`)= team.substring(3) + each agg in maxdata + tr + - var text = agg.key; var result1 = text.replace( /([A-Z])/g, " $1" ); var result2 = result1.charAt(0).toUpperCase() + result1.slice(1) + td(class="w3-text-light-gray w3-small w3-right-align" style="padding-left: 0;") + a(href=`/reports/metricintel?key=${agg.key}`)= result2 + for team in teamList + if team == 0 + td + else + - var valueCol = 'w3-center w3-text-white' + - if (agg[team] == 0) valueCol = 'w3-center w3-text-gray' + if (aggRangeMap[agg.key]) + td(class=`${valueCol}` style=`padding: 8px 0px; background-color: rgb(${getValR(aggRangeMap[agg.key].MAXmin, aggRangeMap[agg.key].MAXmax, agg[team])},${getValG(aggRangeMap[agg.key].MAXmin, aggRangeMap[agg.key].MAXmax, agg[team])},${getValB(aggRangeMap[agg.key].MAXmin, aggRangeMap[agg.key].MAXmax, agg[team])})`)= agg[team] + else + td(class=`${valueCol}`)= agg[team] + //-Super-scout notes + - if (user && user.role.access_level >= Permissions.ACCESS_SCOUTER) + if pitData && pitData[0] + each pit in pitData + div(style="white-space: pre-wrap;") + h4!=msg('scouting.supernotes', {team: pit.team_key.substring(3)}) + i + p= pit.super_data.otherNotes + + hr + if selectedTeam == 'all' + h4!=msg('driveDashboard.futureMatches') + else + h4!=msg('driveDashboard.futureMatchesTeam', {team: selectedTeam.substring(3)}) + each match, i in matches + //-Skip first match + if (i > 0) + +upcomingMatch(match, undefined, selectedTeam) + hr + + script var chartData = JSON.parse('!{dataForChartJS}'); + //- script. + console.log(JSON.parse(JSON.stringify(chartData))); + script. + //- Chart.defaults.global.defaultFontStyle = 'bold'; + //- Chart.defaults.global.defaultFontColor = '#DDD'; + Chart.defaults.font.weight = 'bold'; + Chart.defaults.color = '#DDD'; + + var redData = { + labels: chartData.labels, + datasets: [ + { + data: chartData.datasets.avg.red[0], + label: chartData.items.red[0].label, + backgroundColor: chartData.items.red[0].backgroundColor, + borderColor: chartData.items.red[0].borderColor, + }, + { + data: chartData.datasets.avg.red[1], + label: chartData.items.red[1].label, + backgroundColor: chartData.items.red[1].backgroundColor, + borderColor: chartData.items.red[1].borderColor, + }, + { + data: chartData.datasets.avg.red[2], + label: chartData.items.red[2].label, + backgroundColor: chartData.items.red[2].backgroundColor, + borderColor: chartData.items.red[2].borderColor, + }, + ], + }; + var blueData = { + labels: chartData.labels, + datasets: [ + { + data: chartData.datasets.avg.blue[0], + label: chartData.items.blue[0].label, + backgroundColor: chartData.items.blue[0].backgroundColor, + borderColor: chartData.items.blue[0].borderColor, + }, + { + data: chartData.datasets.avg.blue[1], + label: chartData.items.blue[1].label, + backgroundColor: chartData.items.blue[1].backgroundColor, + borderColor: chartData.items.blue[1].borderColor, + }, + { + data: chartData.datasets.avg.blue[2], + label: chartData.items.blue[2].label, + backgroundColor: chartData.items.blue[2].backgroundColor, + borderColor: chartData.items.blue[2].borderColor, + }, + ], + }; + + var redCtx = $('#RadarRedAlliance')[0].getContext('2d'); + var blueCtx = $('#RadarBlueAlliance')[0].getContext('2d'); + + var redRadar = new Chart(redCtx, { + type: 'radar', + data: redData, + options: chartData.options + }); + var blueRadar = new Chart(blueCtx, { + type: 'radar', + data: blueData, + options: chartData.options + }); + + showAvg(); + + function showAvg() { + var avg = document.getElementById('avgSect'); + avg.style.display = "block"; + var max = document.getElementById('maxSect'); + max.style.display = "none"; + + for (var i in redRadar.data.datasets) { + var set = redRadar.data.datasets[i]; + if (set.hasOwnProperty("data")) { + set.data = chartData.datasets.avg.red[i]; + } + } + redRadar.update(); + for (var i in blueRadar.data.datasets) { + var set = blueRadar.data.datasets[i]; + if (set.hasOwnProperty("data")) { + set.data = chartData.datasets.avg.blue[i]; + } + } + blueRadar.update(); + } + + function showMax() { + var avg = document.getElementById('avgSect'); + avg.style.display = "none"; + var max = document.getElementById('maxSect'); + max.style.display = "block"; + + for (var i in redRadar.data.datasets) { + var set = redRadar.data.datasets[i]; + if (set.hasOwnProperty("data")) { + set.data = chartData.datasets.max.red[i]; + } + } + redRadar.update(); + for (var i in blueRadar.data.datasets) { + var set = blueRadar.data.datasets[i]; + if (set.hasOwnProperty("data")) { + set.data = chartData.datasets.max.blue[i]; + } + } + blueRadar.update(); + } + + //- Multiselect for selecting team_key - Auto submit when it changes + $('select[name=team_key]').on('change', () => { + $('form[name=driveDashboardTeam]').submit(); }); \ No newline at end of file diff --git a/primary/views/dashboard/index.pug b/primary/views/dashboard/index.pug index 0ee210dc..36896fbb 100644 --- a/primary/views/dashboard/index.pug +++ b/primary/views/dashboard/index.pug @@ -41,7 +41,10 @@ block content - match.alliance = (match.alliance == "red") ? "Red" : "Blue"; - var btnColor = (match.alliance == "Red") ? "alliance-red" : "alliance-blue" - h4 !{msg('dashboard.matchNumber', {number: match.match_number})}
#{zoneTime(match.time * 1000).toFormat('cccc @ t')} + - var matchMsg = msg('dashboard.matchNumber', {number: match.match_number}) + - if (match.comp_level == 'sf') matchMsg = msg('dashboard.sfNumber', {number: match.set_number}) + - if (match.comp_level == 'f') matchMsg = msg('dashboard.fNumber', {number: match.match_number}) + h4 !{matchMsg}
#{zoneTime(match.time * 1000).toFormat('cccc @ t')} if match.data a(href=`/scouting/match?key=${match.match_team_key}&alliance=${match.alliance}`) div(class="gear-btn theme-dim w3-btn w3-section w3-margin-left w3-margin-right") diff --git a/primary/views/dashboard/matches.pug b/primary/views/dashboard/matches.pug index 49e7dcd3..1814242b 100644 --- a/primary/views/dashboard/matches.pug +++ b/primary/views/dashboard/matches.pug @@ -35,7 +35,10 @@ block content div(class="w3-col m6 l4 w3-padding") hr div(class="w3-col w3-padding") - span !{msg('dashboard.matchNumber', {number: match.match_number})}
#{zoneTime(match.time * 1000).toFormat('cccc @ t')} + - var matchMsg = msg('dashboard.matchNumber', {number: match.match_number}) + - if (match.comp_level == 'sf') matchMsg = msg('dashboard.sfNumber', {number: match.set_number}) + - if (match.comp_level == 'f') matchMsg = msg('dashboard.fNumber', {number: match.match_number}) + span !{matchMsg}
#{zoneTime(match.time * 1000).toFormat('cccc @ t')} each assignment, j in assignments - assignment.alliance = (assignment.alliance == "red") ? "Red" : "Blue"; div(class="w3-col" style="height: 55px; display: flex;") diff --git a/primary/views/dashboard/pits.pug b/primary/views/dashboard/pits.pug index e78ce689..3f91186c 100644 --- a/primary/views/dashboard/pits.pug +++ b/primary/views/dashboard/pits.pug @@ -58,9 +58,14 @@ block content //- TODOSUPER: Replace permission check with ACCESS_SUPER_SCOUT if user.role && user.role.access_level >= Permissions.ACCESS_TEAM_ADMIN td(class="theme-spacer") - a(href=`/scouting/superpit?key=${team.team_key}`) - div(class="w3-btn w3-col theme-link w3-padding") - span!=msg('scouting.superpit') + if team.super_data + a(href=`/scouting/superpit?key=${team.team_key}`) + div(class="w3-dark-grey w3-btn w3-section") + span!=msg('scouting.superpit') + else + a(href=`/scouting/superpit?key=${team.team_key}`) + div(class="w3-btn w3-col theme-link w3-padding") + span!=msg('scouting.superpit') h6 a(class="gear-btn theme-link w3-btn" href="/dashboard/pits?loadPhotos=1")!=msg('dashboard.loadTeamPhotos') diff --git a/primary/views/index.pug b/primary/views/index.pug index 7f36cee8..af293907 100644 --- a/primary/views/index.pug +++ b/primary/views/index.pug @@ -49,6 +49,9 @@ block content span(class="sprite sp-20 sp-radio sp-inline") span!=msg('index.viewer.intro') p!=msg('index.viewer.action') + i + u + a(href=`/browse`)!=msg('index.browse.link') hr div(id="blurbLearnMore" class="w3-left-align w3-medium" style=learnMoreVisible) div.w3-padding-small @@ -71,7 +74,7 @@ block content span(class="sprite sp-22 sp-black sp-info sp-inline") span!=msg('index.info.wiki') div.w3-center.w3-margin-top(id="discordLink") - a(class="theme-link w3-btn gear-btn" href="https://discord.gg/Mr3kyqkSrQ" target="_blank") + a(class="theme-link w3-btn gear-btn" href="https://discord.gg/hUsbWTeEVz" target="_blank") span(class="sprite sp-22 sp-black sp-discord sp-inline") span!=msg('index.info.discord') div.w3-center.w3-margin-top diff --git a/primary/views/layout.pug b/primary/views/layout.pug index 5845a8ef..c8383b96 100644 --- a/primary/views/layout.pug +++ b/primary/views/layout.pug @@ -49,6 +49,10 @@ html(lang=locale dir=getLocaleDirection(locale)) style. #page{ --background-image: url('#{fileRoot}/images/backgrounds/#{backgrounds[themeYear]}');} .sprite{ --sprites-url: url('#{fileRoot}/images/sprites.png?v=#{functionVersion}');} + //- Disable margin on content-container if in a modal dialog + if inModalDialog + style. + #content-container { margin: 0!important; } script(src=`${fileRoot}/lib/w3.js`) //script(src=`${fileRoot}/lib/hammer.min.js`) @@ -58,7 +62,6 @@ html(lang=locale dir=getLocaleDirection(locale)) script(src=`${fileRoot}/lib/jquery.js`) script(src=`${fileRoot}/lib/jscookie-2.2.1.min.js`) script(src=`${fileRoot}/lib/mmenu/mmenu.js`) - //- script(src=`${fileRoot}/lib/chart.min.js`) 2022-03-18 JL: Taking chart.js out of the required scripts for all pages & putting it only where needed (as of today, only Drive Team) //- script(src="https://moment.github.io/luxon/global/luxon.min.js") //uncomment if you want to test luxon stuff //Hacky way to force clients to download the new version of scripts/stylesheets: Add a "v" query at the end of the string script(src=`${fileRoot}/js/bundle.js?v=${functionVersion}`) @@ -131,59 +134,61 @@ html(lang=locale dir=getLocaleDirection(locale)) span Supported browsers include: Chrome and other Chromium-based browsers, Firefox, Edge, Opera, and new versions of Safari. //- sticky header bar - div(id="headerbar" class=`w3-card header tier-${process.env.TIER}`) - div(class="header-left") - //- Hamburger menu button - a(id="burger") - button(class="mburger mburger--squeeze" title=msg('layout.menu.main')) - b - b - b - //- Scoutradioz logo - div - span(style="display:inline-block;height:100%;vertical-align:middle;") - a(href="/home") - - const darkLogo = [2020].includes(themeYear) - img(src=`${fileRoot}/images/brand-logos/scoutradioz-${darkLogo ? 'black' : 'white'}-sm.png?v=1` class="header-logo" alt="Scoutradioz") - - if (['dev', 'test', 'qa'].includes(process.env.TIER)) - div(class="tierlabel")= process.env.TIER - //-div(class="w3-right w3-show-inline-block") - img(src=`${fileRoot}/images/infinite-recharge/Horizontal-one-color.png` class="w3-image w3-margin-right" style="max-height: 100%;") - //- Share and i18n buttons ***w3-right class cascades from right-to-left** - div(class="header-right") - //- i18n - a(href="javascript:selectLanguage()" class="centered" title="Language") - //- div(class="centered") - span(class="sprite sp-32 sp-i18n") - //- Share - - var orgKey = user ? user.org.org_key : 0; - a(href=`javascript:share('${orgKey}')` class="centered" title=msg('layout.share')) - - var spriteType = isIOS ? 'sp-share-ios' : 'sp-share-android'; - //- div(class="centered") - span(class=`sprite sp-32 ${spriteType} sp-white`) - //- div(class="centered w3-hide-small") - span(class="w3-hide-small" style="font-size:14px; margin-inline-start: 1px; font-family:Tahoma,Geneva,sans-serif;")!=msg('layout.share') - div(style="display: none;" class="slidein-overlay" id="overlay") + if !inModalDialog + div(id="headerbar" class=`w3-card header tier-${process.env.TIER}`) + div(class="header-left") + //- Hamburger menu button + a(id="burger") + button(class="mburger mburger--squeeze" title=msg('layout.menu.main')) + b + b + b + //- Scoutradioz logo + div + span(style="display:inline-block;height:100%;vertical-align:middle;") + a(href="/home") + - const darkLogo = [2020].includes(themeYear) + img(src=`${fileRoot}/images/brand-logos/scoutradioz-${darkLogo ? 'black' : 'white'}-sm.png?v=1` class="header-logo" alt="Scoutradioz") + - if (['dev', 'test', 'qa'].includes(process.env.TIER)) + div(class="tierlabel")= process.env.TIER + //-div(class="w3-right w3-show-inline-block") + img(src=`${fileRoot}/images/infinite-recharge/Horizontal-one-color.png` class="w3-image w3-margin-right" style="max-height: 100%;") + //- Share and i18n buttons ***w3-right class cascades from right-to-left** + div(class="header-right") + //- i18n + a(href="javascript:selectLanguage()" class="centered" title="Language") + //- div(class="centered") + span(class="sprite sp-32 sp-i18n") + //- Share + - var orgKey = user ? user.org.org_key : 0; + a(href=`javascript:share('${orgKey}')` class="centered" title=msg('layout.share')) + - var spriteType = isIOS ? 'sp-share-ios' : 'sp-share-android'; + //- div(class="centered") + span(class=`sprite sp-32 ${spriteType} sp-white`) + //- div(class="centered w3-hide-small") + span(class="w3-hide-small" style="font-size:14px; margin-inline-start: 1px; font-family:Tahoma,Geneva,sans-serif;")!=msg('layout.share') + div(style="display: none;" class="slidein-overlay" id="overlay") //- main content container, scrolls x independently div(id="content-container") - div(id="headerlogo" class="w3-center") - - - const headerlogos = { - 2020: ['infinite-recharge/Horizontal-reverse.png', 'Infinite Recharge'], - 2022: ['rapid-react/horizontal-color.svg', 'Rapid React'], - 2023: ['charged-up/horizontal-color.svg', 'Charged Up'], - 2024: ['crescendo/horizontal-color.svg', 'CRESCENDO'], - } - if (headerlogos[themeYear]) - img(src=`${fileRoot}/images/${headerlogos[themeYear][0]}` alt=headerlogos[themeYear][1] class="w3-image w3-center" style="max-height: 160px;") - if (!isOrgSelectScreen) - h3=eventName - if (!eventIsOrgCurrent) - span(class="sprite sp-warn sp-20 sp-inline w3-tooltip") - span(class="w3-tooltiptext w3-medium") - span You are currently viewing a different event from the rest of your organization. - a(class="link" href='/reports/clearbrowsedevent') Tap here to switch back to your org's current event. + if !inModalDialog + div(id="headerlogo" class="w3-center") + - + const headerlogos = { + 2020: ['infinite-recharge/Horizontal-reverse.png', 'Infinite Recharge'], + 2022: ['rapid-react/horizontal-color.svg', 'Rapid React'], + 2023: ['charged-up/horizontal-color.svg', 'Charged Up'], + 2024: ['crescendo/horizontal-color.svg', 'CRESCENDO'], + } + if (headerlogos[themeYear]) + img(src=`${fileRoot}/images/${headerlogos[themeYear][0]}` alt=headerlogos[themeYear][1] class="w3-image w3-center" style="max-height: 160px;") + if (!isOrgSelectScreen) + h3=eventName + if (!eventIsOrgCurrent) + span(class="sprite sp-warn sp-20 sp-inline w3-tooltip") + span(class="w3-tooltiptext w3-medium") + span You are currently viewing a different event from the rest of your organization. + a(class="link" href='/reports/clearbrowsedevent') Tap here to switch back to your org's current event. main(class="w3-padding w3-mobile w3-center" id="content") block content diff --git a/primary/views/manage/allianceselection.pug b/primary/views/manage/allianceselection.pug index bb248a95..8ddb63bf 100644 --- a/primary/views/manage/allianceselection.pug +++ b/primary/views/manage/allianceselection.pug @@ -13,54 +13,71 @@ block content } include ../reports/templates/heatmap h2 Alliance Selection Data - p.i. - The two buttons on the left can keep track of preferred (and otherwise) teams for Alliance Selection. -
Numbers under the "V" are visible and sortable by your scouting lead on the Alliance Selection dashboard. - p.i Don't pull your punches! Only people who have logged in to your organization can see these numbers. - if (aggdata) - - var aggRangeMap = []; - for scoreItem in currentAggRanges - - aggRangeMap[scoreItem.key] = scoreItem; - table(class="w3-table" id="metricTable") - tr - th(colspan=2 no-sort) Priority - th(class="w3-center") V - th(class="w3-center") Team - th(class="w3-center") Rank - - var colIdx = 4; - for item in layout - -//if (item.type == 'checkbox' || item.type == 'counter' || item.type == 'badcounter') - if (matchDataHelper.isQuantifiableType(item.type)) - - var text = item.key; var result1 = text.replace( /([A-Z])/g, " $1" ); var result2 = result1.charAt(0).toUpperCase() + result1.slice(1) - th(class="w3-right-align")= result2 - - colIdx++ - for row in aggdata + //- Dropdown to pick between team_keys at the org + if orgTeamKeys && orgTeamKeys.length > 1 + form#teamKeyForm(class="w3-container w3-padding-16" method="get" action="/manage/allianceselection") + label(class="w3-label") + span(class="sprite sp-help sp-inline sp-16 w3-tooltip")   + span(class="w3-tooltiptext")!=msg('allianceselection.tooltipPicklist') + span=msg('allianceselection.choosePicklist') + select(class="theme-input" name="picklist_key") + //- Show blank by default, require user to select their team from the dropdown + if !picklist_key + option(selected value="") + each thisTeamKey in orgTeamKeys + option(value=thisTeamKey selected=(picklist_key === thisTeamKey))=thisTeamKey.substring(3) + //- Display the rest of the page only if picklist_key is specified OR if there's only 1 team on the org + if !orgTeamKeys || picklist_key + p.i. + The two buttons on the left can keep track of preferred (and otherwise) teams for Alliance Selection. +
Numbers under the "V" are visible and sortable by your scouting lead on the Alliance Selection dashboard. + p.i Don't pull your punches! Only people who have logged in to your organization can see these numbers. + p.i=msg('allianceselection.tapForPopup') + if (aggdata) + - var aggRangeMap = []; + for scoreItem in currentAggRanges + - aggRangeMap[scoreItem.key] = scoreItem; + table(class="w3-table" id="metricTable") tr - td(style="padding: 2px!important;") - button(class="w3-button theme-red scouting-counter sc-small" onclick=`setValue('${row._id}', -1)` type="button") - - td(style="padding: 2px!important;") - button(class="w3-button w3-hover-green theme-submit scouting-counter sc-small" onclick=`setValue('${row._id}', 1)` type="button") + - td(class="w3-center" team-value key=row._id)= row.value - //- Change the team number's class depending on the row value - td(class="w3-center" team-number key=row._id class=(row.value > 0 ? 'wanted-team' : row.value < 0 ? 'unwanted-team' : ''))= row._id.substring(3) - td(class="w3-right-align")= row.rank + th(colspan=2 no-sort) Priority + th(class="w3-center") V + th(class="w3-center") Team + th(class="w3-center") Rank + - var colIdx = 4; for item in layout -//if (item.type == 'checkbox' || item.type == 'counter' || item.type == 'badcounter') if (matchDataHelper.isQuantifiableType(item.type)) - - var valStyle = 'w3-right-align w3-text-white' - - if (row[item.key] == 0) valStyle = 'w3-right-align w3-text-gray' - if (aggRangeMap[item.key]) - td(class=`${valStyle}` style=`background-color: rgb(${getValR(aggRangeMap[item.key].AVGmin, aggRangeMap[item.key].AVGmax, row[item.key])},${getValG(aggRangeMap[item.key].AVGmin, aggRangeMap[item.key].AVGmax, row[item.key])},${getValB(aggRangeMap[item.key].AVGmin, aggRangeMap[item.key].AVGmax, row[item.key])})`)= row[item.key] - else - td(class=`${valStyle}`)= row[item.key] - else - p Insufficient data at this time, come back later! + - var text = item.key; var result1 = text.replace( /([A-Z])/g, " $1" ); var result2 = result1.charAt(0).toUpperCase() + result1.slice(1) + th(class="w3-right-align")= result2 + - colIdx++ + for row in aggdata + tr + td(style="padding: 2px!important;") + button(class="w3-button theme-red scouting-counter sc-small" onclick=`setValue('${row._id}', -1, "${picklist_key}")` type="button") - + td(style="padding: 2px!important;") + button(class="w3-button w3-hover-green theme-submit scouting-counter sc-small" onclick=`setValue('${row._id}', 1, "${picklist_key}")` type="button") + + td(class="w3-center" team-value key=row._id)= row.value + //- Change the team number's class depending on the row value + td(class="w3-center underline clickable" team-number key=row._id class=(row.value > 0 ? 'wanted-team' : row.value < 0 ? 'unwanted-team' : ''))= row._id.substring(3) + td(class="w3-right-align")= row.rank + for item in layout + -//if (item.type == 'checkbox' || item.type == 'counter' || item.type == 'badcounter') + if (matchDataHelper.isQuantifiableType(item.type)) + - var valStyle = 'w3-right-align w3-text-white' + - if (row[item.key] == 0) valStyle = 'w3-right-align w3-text-gray' + if (aggRangeMap[item.key]) + td(class=`${valStyle}` style=`background-color: rgb(${getValR(aggRangeMap[item.key].AVGmin, aggRangeMap[item.key].AVGmax, row[item.key])},${getValG(aggRangeMap[item.key].AVGmin, aggRangeMap[item.key].AVGmax, row[item.key])},${getValB(aggRangeMap[item.key].AVGmin, aggRangeMap[item.key].AVGmax, row[item.key])})`)= row[item.key] + else + td(class=`${valStyle}`)= row[item.key] + else + p.i Insufficient data at this time, come back later! script. - function setValue(teamKey, value) + function setValue(teamKey, value, picklist_key) { - console.log("teamKey " + teamKey + ", value " + value); + console.log(`teamKey=${teamKey}, value=${value}, picklist_key=${picklist_key}`); + if (picklist_key === 'undefined') picklist_key = undefined; - $.post('/manage/allianceselection/updateteamvalue', {key: teamKey, value: value}) + $.post('/manage/allianceselection/updateteamvalue', {key: teamKey, value, picklist_key}) .done(msg => { //- Update the row with the team's new value var newValue = msg.value; @@ -78,5 +95,15 @@ block content NotificationCard.error(err.statusText); }); } + + $(() => { + $('td[team-number]').on('click', function () { + let team_key = $(this).attr('key'); + Dialog.showURL(`/reports/teamintel?team_key=${team_key}`); + }) + $('select[name=picklist_key]').on('change', () => { + $('#teamKeyForm').trigger('submit'); + }) + }) //- the "Priority" header takes up 2 columns so offset row by an extra 1 +tableSorter(1) \ No newline at end of file diff --git a/primary/views/manage/assignments/matches.pug b/primary/views/manage/assignments/matches.pug index 204b33d6..3074fbb8 100644 --- a/primary/views/manage/assignments/matches.pug +++ b/primary/views/manage/assignments/matches.pug @@ -41,6 +41,9 @@ block content br input(type="checkbox" class="w3-check" name='skipBreaks' id='skipBreaks') label !{msg('manage.assignments.skipBreaks')}  + p + input(type="checkbox" class="w3-check" name='scoutPlayoffs' id='scoutPlayoffs') + label !{msg('manage.assignments.scoutPlayoffs')}  p button(type="submit" class="w3-btn theme-submit")!=msg('manage.assignments.assignMatchTeams') diff --git a/primary/views/manage/audit/bymatch.pug b/primary/views/manage/audit/bymatch.pug index bde10950..d3ddff1e 100644 --- a/primary/views/manage/audit/bymatch.pug +++ b/primary/views/manage/audit/bymatch.pug @@ -35,7 +35,7 @@ block content div(class="w3-row w3-padding") each match_team in match div(class="w3-third w3-padding") - div(class="w3-btn w3-block theme-hover-white") + div(class=`w3-btn w3-block theme-hover-white alliance-border-${match_team.alliance}`) a(href=`/scouting/match?key=${match_team.match_team_key}`) div Team: #{match_team.team_key.substring(3)} div Assigned Scorer: #{match_team.assigned_scorer ? match_team.assigned_scorer.name : 'None'} diff --git a/primary/views/manage/audit/spr.pug b/primary/views/manage/audit/spr.pug index f2996ee7..42277f62 100644 --- a/primary/views/manage/audit/spr.pug +++ b/primary/views/manage/audit/spr.pug @@ -5,13 +5,63 @@ QUERY: lookbackto (the match # to look back to; if omitted, will show & calculate across all matches so far at the current event extends ../../layout include ../../reports/mixins/metricTables +mixin scouterName(report) + - var name = report.actual_scorer.name + a(target="_blank" href=`/scouting/match?key=${report.match_team_key}` class="w3-tooltip")=name + if scouterScoring[name] + span(class="w3-tooltiptext") SPR: #{scouterScoring[name].sprScore}
Team: #{report.team_key.substring(3)} block content style. + #content-container { + overflow-x: unset; /* To fix sticky headers */ + } .w3-tooltip .w3-tooltiptext{ width: 120px; padding: 8px 16px; margin-left: -60px; } + .spr-table { + border-collapse: collapse; + border-spacing: 0; + width: 100%; + } + .spr-table td, .spr-table th { + padding: 8px; + text-align: start; + vertical-align: top; + } + .spr-table .stickyTableHeader { + background: black; + } + style. + @media(max-width: 800px) { + .spr-table, .spr-table thead, .spr-table tbody, .spr-table th, .spr-table td, .spr-table tr { + display: block; + } + .spr-table thead tr { + display: none; + } + .spr-table td { + /* Behave like a "row" */ + border: none; + border-bottom: 1px solid #ffffff40; + position: relative; + padding-left: 50%; + } + + .spr-table td:before { + /* Now like a table header */ + position: absolute; + /* Top/left values mimic padding */ + top: 6px; + left: 6px; + width: 45%; + padding-right: 10px; + white-space: nowrap; + content: attr(data-header); + opacity: 0.7; + } + } h2(class="theme-text") Scouter Performance Ratings @@ -35,9 +85,9 @@ block content h6 Click on a column header to sort by that column's information (click again to change sort direction) div(class="w3-show-inline-block") - table(class="w3-table" id="metricTable") + table(class="w3-table w3-bordered" id="metricTable") tr - th(class="w3-center") Scout + th(class="w3-left-align") Scout th(class="w3-right-align w3-tooltip") SPR span.w3-tooltiptext Scouter Performance Rating (Lower Is Better) th(class="w3-right-align w3-tooltip") Count @@ -48,20 +98,39 @@ block content span.w3-tooltiptext Average ratio of error each scout, i in scouterScoring tr - td(class="w3-text-light-gray w3-center")= i - td(class="w3-text-light-gray w3-center")= Math.round(scout.sprScore*10)/10 - td(class="w3-text-light-gray w3-center")= scout.count - td(class="w3-text-light-gray w3-center")= Math.round(scout.avgDiff*10)/10 - td(class="w3-text-light-gray w3-center")= Math.round(scout.avgRatio*100)/100 + td(class="w3-text-light-gray w3-left-align")= i + td(class="w3-text-light-gray w3-right-align")= Math.round(scout.sprScore*10)/10 + td(class="w3-text-light-gray w3-right-align")= scout.count + td(class="w3-text-light-gray w3-right-align")= Math.round(scout.avgDiff*10)/10 + td(class="w3-text-light-gray w3-right-align")= Math.round(scout.avgRatio*100)/100 +tableSorter() h2(class="theme-text") Per-match auditing h6 Click on a match or list of scouts to see FIRST data or per-scout data respectively - div(class="w3-show-inline-block") - table(class="w3-table") - tr + div + table(class="spr-table") + thead(class="stickyTableHeader") + tr(class="w3-border-bottom w3-hide-small") + th Match + th Alliance + th Scouts + th.w3-tooltip FRC points + span.w3-tooltiptext Official score, not counting fouls + th.w3-tooltip Scout points + span.w3-tooltiptext Estimated score based on Contributed Points from scouting data + th.w3-tooltip Point diff + span.w3-tooltiptext Difference between FRC points and Scout points + th Err ratio + tr(class="w3-border-bottom w3-show-small") + th Match - Alliance
Scouts + th.w3-tooltip Scout points + span.w3-tooltiptext Estimated score based on Contributed Points from scouting data + th.w3-tooltip Point diff + span.w3-tooltiptext Difference between FRC points and Scout points + th Err ratio + //- tr th(class="w3-center") Match/scouts th(class="w3-right-align w3-tooltip") Point diff span.w3-tooltiptext Count of matches scouted @@ -71,8 +140,42 @@ block content span.w3-tooltiptext Average ratio of error - var rowToggle = 0; - var thisMatch = ''; - each matchall, i in compareTable + each row, i in compareTable + - var matchTitle; + - if (row.match.comp_level === 'f') matchTitle = msg('dashboard.fNumber', {number: row.match.match_number}); // finals always have set_number=1 + - if (row.match.comp_level === 'sf') matchTitle = msg('dashboard.sfNumber', {number: row.match.set_number}); // semis always have match_number=1 + - else matchTitle = msg('dashboard.matchNumber', {number: row.match.match_number}); // qualifying matches + //- Match # and blue alliance tr + td(rowspan="2" data-header="Match")!=matchTitle + td.alliance-blue-faded(data-header="Alliance")!=msg('alliance.blueShort') + if row.blue + td.alliance-blue-faded(data-header="Scouts") + +scouterName(row.blue.reports[0]) + span , + +scouterName(row.blue.reports[1]) + span , + +scouterName(row.blue.reports[2]) + td.alliance-blue-faded(data-header="FRC points")= row.blue.frcTot + td.alliance-blue-faded(data-header="Scout points")= row.blue.orgTot + td.alliance-blue-faded.b(data-header="Point difference")= row.blue.errDiff + td.alliance-blue-faded(data-header="Err ratio")= Math.round(row.blue.errRatio * 100) / 100 + //- FRC score and red alliance + tr.w3-border-bottom + td.alliance-red-faded(data-header="Alliance")!=msg('alliance.redShort') + if row.red + td.alliance-red-faded(data-header="Scouts") + +scouterName(row.red.reports[0]) + span , + +scouterName(row.red.reports[1]) + span , + +scouterName(row.red.reports[2]) + td.alliance-red-faded(data-header="FRC points")= row.red.frcTot + td.alliance-red-faded(data-header="Scout points")= row.red.orgTot + td.alliance-red-faded.b(data-header="Point difference")= row.red.errDiff + td.alliance-red-faded(data-header="Err ratio")= Math.round(row.red.errRatio * 100) / 100 + + //- tr - if (rowToggle == 0) thisMatch = matchall[0].split(" ")[0]; - if (rowToggle == 0) td(class="w3-text-light-gray w3-center") diff --git a/primary/views/manage/config/editform.pug b/primary/views/manage/config/editform.pug index b8224c09..b2ef1922 100644 --- a/primary/views/manage/config/editform.pug +++ b/primary/views/manage/config/editform.pug @@ -26,45 +26,6 @@ block content input(name="testData" id="testData" type="hidden") input(name="form_type" id="form_type" type="hidden" value=`${form_type}`) input(name="year" id="year" type="hidden" value=`${year}`) - dialog(id="previewDialog") - div(id="dialogContent") - button(id="closePreviewBtn") X - iframe(id="previewFrame") //- 2023-10-06 JL: Changed script to module so I can import types ESM-style - script(src=`${fileRoot}/js/script-editform.js` type="module") - - style. - #previewDialog { - width: calc(100% - 100px); - height: calc(100% - 100px); - padding: 0; - border: none; - } - #previewDialog::backdrop { - background-color: rgba(0,0,0,0.5); - } - - #dialogContent { - position: relative; - width: 100%; - height: 100%; - } - - #closePreviewBtn { - position: absolute; - top: 0; - right: 0; - width: 40px; - height: 40px; - display: grid; - place-items: center; - cursor: pointer; - } - - #previewFrame { - width: 100%; - top: 40px; - position: relative; - height: calc(100% - 40px); - } \ No newline at end of file + script(src=`${fileRoot}/js/script-editform.js` type="module") \ No newline at end of file diff --git a/primary/views/manage/config/index.pug b/primary/views/manage/config/index.pug index 2236a2f6..b4b6a8f5 100644 --- a/primary/views/manage/config/index.pug +++ b/primary/views/manage/config/index.pug @@ -47,16 +47,22 @@ block content option(value="1") true div(class="w3-auto w3-content") h2=title - form(id=`updateOrg_${org.org_key}` method="post" action="/manage/config") + form(id="updateOrg" method="post" action="/manage/config") div(class="w3-row") //- Top row - div(class="w3-col s0 m2 w3-padding-small") ID - div(class="w3-col s0 m8 w3-padding-small") Nickname + div(class="w3-col s6 m2 w3-padding-small") ID + div(class="w3-col s6 m4 w3-padding-small") + span Team(s)  + span(class="w3-tooltip sprite sp-help sp-16")   + span(class="w3-tooltiptext")=msg('manage.config.tooltipTeams') + div(class="w3-col s6 m4 w3-padding-small") Nickname div(class="w3-col s0 m2 w3-padding-small")   div(class="w3-col s6 m2 w3-padding-small") input(disabled type="text" class="theme-input w3-disabled" value=org.org_key) input(type="hidden" name="org_key" value=org.org_key) - div(class="w3-col s6 m8 w3-padding-small") + div(class="w3-col s6 m4 w3-padding-small") + input(type="text" class="theme-input" name="team_numbers" value=team_numbers.join(', ')) + div(class="w3-col s6 m4 w3-padding-small") input(type="text" class="theme-input" name="nickname" value=org.nickname) div(class="w3-col m2 w3-padding-small") button(type="submit" class="w3-btn theme-submit") Update Org @@ -67,7 +73,7 @@ block content div(class="w3-col s4") span Key  span(class="w3-tooltip sprite sp-help sp-16")   - span(class="w3-tooltiptext") Write a unique identifier for each subteam. After you create a subteam, the label can change but the key should not change. + span(class="w3-tooltiptext")=msg('manage.config.tooltipSubteamKey') div(class="w3-col s4") Pit scout? div(id=`subteams_${org.org_key}`) each subteam, i in org.config.members.subteams @@ -82,7 +88,7 @@ block content div(class="w3-col s3") span Key  span(class="w3-tooltip sprite sp-help sp-16")   - span(class="w3-tooltiptext") Write a unique identifier for each class. After you create a class, the label can change but the key should not change. + span(class="w3-tooltiptext")=msg('manage.config.tooltipClassKey') div(class="w3-col s3") Seniority div(class="w3-col s3") Youth? div(id=`classes_${org.org_key}`) @@ -107,4 +113,19 @@ block content div#classTemplate +classname('num', {label: '', key: '', seniority: '', youth: true}) //- Load orgs script - script(src=`${fileRoot}/js/script-orgs.js`) \ No newline at end of file + script(src=`${fileRoot}/js/script-orgs.js`) + script. + $('#updateOrg').on('submit', function(e) { + e.preventDefault(); + let data = FormSubmission.getFormData(this); + $.post('/manage/config', data) + .done(response => { + console.log(response); + NotificationCard.good(response); + }) + .fail(response => { + console.error(response); + NotificationCard.error(response.responseText) + }) + return false; + }) \ No newline at end of file diff --git a/primary/views/manage/index.pug b/primary/views/manage/index.pug index da2873d3..16b10fbe 100644 --- a/primary/views/manage/index.pug +++ b/primary/views/manage/index.pug @@ -74,6 +74,7 @@ block content div(class="gear-btn theme-link w3-btn") span!=msg('manage.event.recalcDerived') //- Manual data links + h5!=msg('manage.event.manual') a(href="/manage/manualdata/teams") div(class="gear-btn theme-link w3-btn") span(class="sprite sp-16 sp-edit sp-inline") @@ -86,6 +87,10 @@ block content div(class="gear-btn theme-link w3-btn") span(class="sprite sp-16 sp-edit sp-inline") span!=msg('manage.event.editMatchResults') + a(href="/manage/manualdata/rankings") + div(class="gear-btn theme-link w3-btn") + span(class="sprite sp-16 sp-edit sp-inline") + span!=msg('manage.event.editRankings') hr //- Member Management h4!=msg('layout.nav.manage.members.main') diff --git a/primary/views/manage/manualdata/matchresults.pug b/primary/views/manage/manualdata/matchresults.pug index 4dc10d5a..aec64286 100644 --- a/primary/views/manage/manualdata/matchresults.pug +++ b/primary/views/manage/manualdata/matchresults.pug @@ -31,18 +31,16 @@ block content div(class="w3-col s1 m2") # div(class="w3-col s2 m0")   div(class="w3-col s5 m5") Time - div(class="w3-col s6 m2 w3-padding-small") - div(class="w3-col s2")   - div(class="w3-col s8") Winner  - div(class="w3-col s2")   - div(class="w3-col s12 m4 w3-padding-small") - div(class="w3-col s3") Blue - div(class="w3-col s3")  Blue Score - div(class="w3-col s6") Blue RP - div(class="w3-col s12 m4 w3-padding-small") + div(class="w3-col s12 m5 w3-padding-small") div(class="w3-col s3") Red - div(class="w3-col s3")  Red Score - div(class="w3-col s6") Red RP + div(class="w3-col s2")  Score + div(class="w3-col s2")  Pts from Fouls + div(class="w3-col s5") Red RP + div(class="w3-col s12 m5 w3-padding-small") + div(class="w3-col s3") Blue + div(class="w3-col s2")  Score + div(class="w3-col s2")  Pts from Fouls + div(class="w3-col s5") Blue RP br each match in matches div(class="w3-col s12 m0 w3-section theme-spacer") @@ -53,63 +51,61 @@ block content div(class="w3-col s1 m2")= match.match_number div(class="w3-col s2 m0")   div(class="w3-col s5 m5")= zoneTime(1000*match.time).toLocaleString(DateTime.TIME_SIMPLE) - //-Winner - div(class="w3-col s6 m2 w3-padding-small") - div(class="w3-col s2")   - div(class="w3-col s8" style="margin-top: -10px;") - select(class="w3-input theme-input w3-no-border theme-inline-padding" type="multiselect" name=`WinningAlliance_${match.key}` id=`WinningAlliance_${match.key}`) - if match.winning_alliance == "blue" - option(value="") - option(value="blue" selected) Blue - option(value="red") Red - else if match.winning_alliance == "red" - option(value="") - option(value="blue") Blue - option(value="red" selected) Red - else - option(value="" selected) - option(value="blue") Blue - option(value="red") Red - div(class="w3-col s2")   //-Spacer div(class="w3-col s12 m0")   - //-Blue - div(class="w3-col s12 m4 w3-padding-small") + + //-Red + div(class="w3-col s12 m5 w3-padding-small") //-team #s - div(class="w3-col s3" style="margin-top: -10px;")= match.alliances.blue.team_keys[0].substring(3)+', '+match.alliances.blue.team_keys[1].substring(3)+', '+match.alliances.blue.team_keys[2].substring(3) + div(class="w3-col s3" style="margin-top: -10px;")= match.alliances.red.team_keys[0].substring(3)+', '+match.alliances.red.team_keys[1].substring(3)+', '+match.alliances.red.team_keys[2].substring(3) //-score - div(class="w3-col s3" style="margin-top: -10px; padding-left: 8px;") - if (match.alliances.blue.score > -1) - input(class="w3-input theme-input w3-no-border theme-inline-padding alliance-blue" type="text" name=`BlueScore_${match.key}` value=`${match.alliances.blue.score}`) + div(class="w3-col s2" style="margin-top: -10px; padding-left: 8px;") + if (match.alliances.red.score > -1) + input(class="w3-input theme-input w3-no-border theme-inline-padding alliance-red" type="text" name=`RedScore_${match.key}` value=`${match.alliances.red.score}`) else - input(class="w3-input theme-input w3-no-border theme-inline-padding alliance-blue" type="text" name=`BlueScore_${match.key}`) + input(class="w3-input theme-input w3-no-border theme-inline-padding alliance-red" type="text" name=`RedScore_${match.key}`) + //-fouls + div(class="w3-col s2" style="margin-top: -10px; padding-left: 8px;") + if (match.score_breakdown && match.score_breakdown.red && match.score_breakdown.red.foulPoints > -1) + input(class="w3-input theme-input w3-no-border theme-inline-padding alliance-red" type="text" name=`RedFouls_${match.key}` value=`${match.score_breakdown.red.foulPoints}`) + else + input(class="w3-input theme-input w3-no-border theme-inline-padding alliance-red" type="text" name=`RedFouls_${match.key}`) //-ranking points - div(class="w3-col s6" style="margin-top: -10px;") + div(class="w3-col s5" style="margin-top: -10px;") each rp in rankingpoints.attributes //- rp: label, name, and abbr - - let key = `Blue${rp.name}_${match.key}`; + - let key = `Red${rp.name}_${match.key}`; label(for=key class="w3-tooltip" style="margin-right: 4px; margin-left: 8px;") #{rp.abbr} span(class="w3-tooltiptext" style="width: 160px; margin-left: -80px;") #{rp.label} - input(type="checkbox" class="w3-check alliance-blue" name=key id=key checked=(match.score_breakdown && match.score_breakdown.blue[rp.name])) + input(type="checkbox" class="w3-check alliance-red" name=key id=key checked=(match.score_breakdown && match.score_breakdown.red[rp.name])) + //-Spacer div(class="w3-col s12 m0")   - //-Red - div(class="w3-col s12 m4 w3-padding-small") + + //-Blue + div(class="w3-col s12 m5 w3-padding-small") //-team #s - div(class="w3-col s3" style="margin-top: -10px;")= match.alliances.red.team_keys[0].substring(3)+', '+match.alliances.red.team_keys[1].substring(3)+', '+match.alliances.red.team_keys[2].substring(3) + div(class="w3-col s3" style="margin-top: -10px;")= match.alliances.blue.team_keys[0].substring(3)+', '+match.alliances.blue.team_keys[1].substring(3)+', '+match.alliances.blue.team_keys[2].substring(3) //-score - div(class="w3-col s3" style="margin-top: -10px; padding-left: 8px;") - if (match.alliances.red.score > -1) - input(class="w3-input theme-input w3-no-border theme-inline-padding alliance-red" type="text" name=`RedScore_${match.key}` value=`${match.alliances.red.score}`) + div(class="w3-col s2" style="margin-top: -10px; padding-left: 8px;") + if (match.alliances.blue.score > -1) + input(class="w3-input theme-input w3-no-border theme-inline-padding alliance-blue" type="text" name=`BlueScore_${match.key}` value=`${match.alliances.blue.score}`) else - input(class="w3-input theme-input w3-no-border theme-inline-padding alliance-red" type="text" name=`RedScore_${match.key}`) + input(class="w3-input theme-input w3-no-border theme-inline-padding alliance-blue" type="text" name=`BlueScore_${match.key}`) + //-fouls + div(class="w3-col s2" style="margin-top: -10px; padding-left: 8px;") + if (match.score_breakdown && match.score_breakdown.blue && match.score_breakdown.blue.foulPoints > -1) + input(class="w3-input theme-input w3-no-border theme-inline-padding alliance-blue" type="text" name=`BlueFouls_${match.key}` value=`${match.score_breakdown.blue.foulPoints}`) + else + input(class="w3-input theme-input w3-no-border theme-inline-padding alliance-blue" type="text" name=`BlueFouls_${match.key}`) //-ranking points - div(class="w3-col s6" style="margin-top: -10px;") + div(class="w3-col s5" style="margin-top: -10px;") each rp in rankingpoints.attributes //- rp: label, name, and abbr - - let key = `Red${rp.name}_${match.key}`; + - let key = `Blue${rp.name}_${match.key}`; label(for=key class="w3-tooltip" style="margin-right: 4px; margin-left: 8px;") #{rp.abbr} span(class="w3-tooltiptext" style="width: 160px; margin-left: -80px;") #{rp.label} - input(type="checkbox" class="w3-check alliance-red" name=key id=key checked=(match.score_breakdown && match.score_breakdown.red[rp.name])) + input(type="checkbox" class="w3-check alliance-blue" name=key id=key checked=(match.score_breakdown && match.score_breakdown.blue[rp.name])) + div(class="w3-section w3-auto") button(class="w3-btn theme-submit" type="submit") Submit \ No newline at end of file diff --git a/primary/views/manage/manualdata/rankings.pug b/primary/views/manage/manualdata/rankings.pug new file mode 100644 index 00000000..2a229d54 --- /dev/null +++ b/primary/views/manage/manualdata/rankings.pug @@ -0,0 +1,65 @@ +//- + Rankings shows the rankings for the current event. + reports.js + '/reports/rankings' +extends ../../layout +block content + style. + #content{ + /*Reduce page's padding*/ + padding: 4px 8px!important; + } + .w3-tooltip .w3-tooltiptext{ + width: 160px; + padding: 8px 16px; + margin-left: -80px; + } + if (rankings.length === 0) + +noDataFound(msg('reports.noRankingsYet'), true) + else + h2(class="theme-text")!=msg('manage.event.editRankings') + h6.i!=msg('manage.event.editRankingsInstructions') + div(class="w3-auto") + table(class="w3-table") + tr + th(colspan=2 no-sort) Adjust + th(class="w3-center theme-spacer")!=msg('reports.rank') + th(class="w3-center theme-spacer")!=msg('reports.team') + th(class="w3-center theme-spacer w3-tooltip")!=msg('reports.currentRankings.wlt') + span(class="w3-tooltiptext")!=msg('reports.currentRankings.wltDesc') + th(class="w3-center theme-spacer w3-tooltip")!=msg('reports.currentRankings.dq') + span(class="w3-tooltiptext")!=msg('reports.currentRankings.dqDesc') + th(class="w3-center theme-spacer")!=msg('matches') + th(class="w3-center theme-spacer w3-tooltip")!=msg('reports.currentRankings.rp') + span(class="w3-tooltiptext")!=msg('reports.currentRankings.rpDesc') + each team in rankings + tr + td(style="padding: 2px!important;") + button(class="w3-button theme-red scouting-counter sc-small" onclick=`setValue('${team.team_key}', 1)` type="button") + + td(style="padding: 2px!important;") + button(class="w3-button w3-hover-green theme-submit scouting-counter sc-small" onclick=`setValue('${team.team_key}', -1)` type="button") - + td(class="theme-text w3-center" team-value key=team.team_key) + b= team.rank + td(class="theme-text-secondary w3-center") + a(href=`/reports/teamintel?team_key=${team.team_key}`)= team.team_key.substring(3) + td(class="theme-text-secondary w3-center")= team.record.wins+'-'+team.record.losses+'-'+team.record.ties + td(class="theme-text-secondary w3-center")= team.dq + td(class="theme-text-secondary w3-center")= team.matches_played + td(class="theme-text-secondary w3-center")= team.extra_stats[0] + script. + function setValue(teamKey, value) + { + console.log("teamKey " + teamKey + ", value " + value); + + $.post('/manage/manualdata/updateteamranking', {key: teamKey, value: value}) + .done(msg => { + //- Update the row with the team's new value + var newValue = msg.value; + $(`td[team-value][key="${msg.team_key}"]`).text(newValue); + }) + .fail(err => { + NotificationCard.error(err.statusText); + }); + } + //- the "Priority" header takes up 2 columns so offset row by an extra 1 + //- +tableSorter(1) \ No newline at end of file diff --git a/primary/views/reports/browseevents.pug b/primary/views/reports/browseevents.pug index 4bb984c0..fda38c96 100644 --- a/primary/views/reports/browseevents.pug +++ b/primary/views/reports/browseevents.pug @@ -2,7 +2,14 @@ extends ../layout block content h2=title h6 Below is a list of all events for which your org has data. - ul + table(class="w3-table w3-bordered") + tr + th!=msg('year') + th!=msg('date') + th(style="width: 60%")!=msg('name') each event in events - li - a(class="link" href=`/reports/browseevent?event_key=${event.key}`) #{event.name} \ No newline at end of file + tr + td(class="w3-padding-16")=event.year + td(class="w3-padding-16")=event.start_date + td(class="w3-padding-16") + a(class="link" href=`/reports/browseevent?event_key=${event.key}`)=event.name \ No newline at end of file diff --git a/primary/views/scouting/match.pug b/primary/views/scouting/match.pug index 4e40806c..21e4745f 100644 --- a/primary/views/scouting/match.pug +++ b/primary/views/scouting/match.pug @@ -20,16 +20,9 @@ block content window.stickyBarEnabled = false; } $('#toggleSticky').prop('checked', window.stickyBarEnabled); - style. - /* - If we want it to be prettier, we can add this; but it might lead to worse battery performance on low end phones - #matchform > *{ - transition: filter 0.2s, opacity 0.2s; - } - */ script(src=`${fileRoot}/js/script-matchscouting.js?v=${functionVersion}`) - var titleParts = key.split('_').map(key => key.replace(/\D/g, '')); // 2022mrcmp_qm77_frc102 to ['2022', '77', '102'] - - var btnColor = alliance ? ((alliance.toLowerCase().startsWith('r')) ? "alliance-red" : "alliance-blue") : ''; + - var btnColor = alliance ? ((alliance.toLowerCase().startsWith('b')) ? "alliance-blue" : "alliance-red") : ''; p if images && images.main div(style="width:80%; margin-left:auto; margin-right:auto; display:block;") @@ -47,35 +40,35 @@ block content p= pit_super_data.otherNotes form#matchform(name="matchform" class="w3-centered") input#match_team_key(type="hidden", name="match_team_key", value=`${key}`) - - var headerList = []; // for sticky bar - each element in layout - - let answer = ""; - - if (answers) answer = answers[element.id]; - - element.label = resolveLabelTemplate(element.label, teamKey); - - case element.type - when "checkbox" - include templates/formCheckbox - when "counter" - include templates/formCounter - when "counterallownegative" - include templates/formCounterAllowNegative - when "badcounter" - include templates/formBadCounter - when "slider" - when "timeslider" - include templates/formSlider - when "multiselect" - include templates/formMultiselect - when "textblock" - include templates/formTextBlock - when "h2" - include templates/formHeader - - headerList.push(element.id); - when "h3" - include templates/formSubHeader - when "spacer" - include templates/formSpacer + each group, i in groupedLayout + section(id=`group_${i}` data-group-label=group.label) + each element in group.items + - let answer = ""; + - if (answers) answer = answers[element.id]; + - element.label = resolveLabelTemplate(element.label, teamKey); + + case element.type + when "checkbox" + include templates/formCheckbox + when "counter" + include templates/formCounter + when "counterallownegative" + include templates/formCounterAllowNegative + when "badcounter" + include templates/formBadCounter + when "slider" + when "timeslider" + include templates/formSlider + when "multiselect" + include templates/formMultiselect + when "textblock" + include templates/formTextBlock + when "h2" + include templates/formHeader + when "h3" + include templates/formSubHeader + when "spacer" + include templates/formSpacer br button#submit( onclick="window.onbeforeunload = null;" class="w3-btn theme-submit")!=msg('scouting.submit') if user && user.role.access_level >= Permissions.ACCESS_TEAM_ADMIN @@ -119,6 +112,6 @@ block content else span ▶ script. - window.headerList = JSON.parse('!{JSON.stringify(headerList)}'); + window.groupedLayout = JSON.parse(`!{JSON.stringify(groupedLayout).replace(/\`/g, '\\\`')}`); window.isIOS = #{!!isIOS}; if (!window.stickyBarEnabled) $('#stickyBar').hide(); \ No newline at end of file diff --git a/primary/views/scouting/supermatch.pug b/primary/views/scouting/supermatch.pug index c64e8167..d35f0e82 100644 --- a/primary/views/scouting/supermatch.pug +++ b/primary/views/scouting/supermatch.pug @@ -21,6 +21,8 @@ block content - let this_match_team_key = data.match_team_key; - let this_team_key = data.team_key; - var titleParts = this_match_team_key.split('_').map(key => key.replace(/\D/g, '')); // 2022mrcmp_qm77_frc102 to ['2022', '77', '102'] + - if (this_match_team_key.split('_')[1].substring(0, 2) == 'sf') titleParts[1] = (this_match_team_key.split('_')[1].split('m').map(key => key.replace(/\D/g, '')))[0]; // 2022mrcmp_sf4m1_frc102 to '4' + - if (this_match_team_key.split('_')[1].substring(0, 1) == 'f') titleParts[1] = (this_match_team_key.split('_')[1].split('m').map(key => key.replace(/\D/g, '')))[1]; // 2022mrcmp_f1m2_frc102 to '2' - let element = {"year":{"$numberInt":titleParts[0]},"order":"1","type":"textblock","label":"Super-Scout Notes","id":`${this_team_key}_otherNotes`,"org_key":org_key,"form_type":"supermatchscouting"} - var btnColor = data.alliance ? ((data.alliance.toLowerCase().startsWith('r')) ? "alliance-red" : "alliance-blue") : ''; p diff --git a/scoutradioz-types/types.d.ts b/scoutradioz-types/types.d.ts index 8001eb70..6e920a59 100644 --- a/scoutradioz-types/types.d.ts +++ b/scoutradioz-types/types.d.ts @@ -325,6 +325,7 @@ export declare interface OrgClass { export declare interface OrgTeamValue extends DbDocument { org_key: OrgKey; team_key: TeamKey; + picklist_key: string|undefined; event_key: EventKey; value: number; } diff --git a/scripts/s3sync.ts b/scripts/s3sync.ts new file mode 100644 index 00000000..83ad7306 --- /dev/null +++ b/scripts/s3sync.ts @@ -0,0 +1,21 @@ +import { parseArgs } from 'util'; +import { $ } from 'bun'; + +const s3Bucket = 'scoutradioz'; + +const { values, } = parseArgs({ + args: Bun.argv, + options: { + tier: { + type: 'string' + }, + folder: { + type: 'string' + }, + }, + strict: true, + allowPositionals: true, +}); + +await $`aws s3 sync ${values.folder} s3://${s3Bucket}/${values.tier} --exclude "*.js" --acl public-read`; +await $`aws s3 sync ${values.folder} s3://${s3Bucket}/${values.tier} --include "*.js" --content-type "application/javascript" --acl public-read`; \ No newline at end of file diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json index 5dffd2c7..3d30767a 100644 --- a/scripts/tsconfig.json +++ b/scripts/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { - "target": "es2016", - "module": "commonjs", + "target": "es2022", + "module": "es2022", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": false, @@ -10,5 +10,6 @@ "noImplicitThis": false, "moduleResolution": "node", "newLine": "crlf", + "resolveJsonModule": true, } } diff --git a/voyager/package.json b/voyager/package.json index 10a2404b..6e8d6991 100644 --- a/voyager/package.json +++ b/voyager/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "vite dev --host", "build": "vite build", - "preview": "vite preview", + "preview": "vite preview --host", "smui-theme": "smui-theme compile static/smui.css -i src/theme", "postinstall": "yarn smui-theme", "update": "yarn upgrade --pattern 'scoutradioz*' --ignore-platform", @@ -21,34 +21,34 @@ "sst:dev": "sst dev" }, "devDependencies": { - "@smui-extra/autocomplete": "^7.0.0-beta.16", - "@smui-extra/bottom-app-bar": "^7.0.0-beta.16", - "@smui/button": "^7.0.0-beta.16", - "@smui/card": "^7.0.0-beta.16", - "@smui/checkbox": "^7.0.0-beta.16", - "@smui/circular-progress": "^7.0.0-beta.16", - "@smui/common": "^7.0.0-beta.16", - "@smui/data-table": "^7.0.0-beta.16", - "@smui/dialog": "^7.0.0-beta.16", - "@smui/drawer": "^7.0.0-beta.16", - "@smui/fab": "^7.0.0-beta.16", - "@smui/form-field": "^7.0.0-beta.16", - "@smui/icon-button": "^7.0.0-beta.16", - "@smui/layout-grid": "^7.0.0-beta.16", - "@smui/linear-progress": "^7.0.0-beta.16", - "@smui/list": "^7.0.0-beta.16", - "@smui/paper": "^7.0.0-beta.16", - "@smui/ripple": "^7.0.0-beta.16", - "@smui/select": "^7.0.0-beta.16", - "@smui/slider": "^7.0.0-beta.16", - "@smui/snackbar": "^7.0.0-beta.16", - "@smui/switch": "^7.0.0-beta.16", - "@smui/tab": "^7.0.0-beta.16", - "@smui/tab-bar": "^7.0.0-beta.16", - "@smui/textfield": "^7.0.0-beta.16", - "@smui/tooltip": "^7.0.0-beta.16", - "@smui/top-app-bar": "^7.0.0-beta.16", - "@smui/touch-target": "^7.0.0-beta.16", + "@smui-extra/autocomplete": "^7.0.0", + "@smui-extra/bottom-app-bar": "^7.0.0", + "@smui/button": "^7.0.0", + "@smui/card": "^7.0.0", + "@smui/checkbox": "^7.0.0", + "@smui/circular-progress": "^7.0.0", + "@smui/common": "^7.0.0", + "@smui/data-table": "^7.0.0", + "@smui/dialog": "^7.0.0", + "@smui/drawer": "^7.0.0", + "@smui/fab": "^7.0.0", + "@smui/form-field": "^7.0.0", + "@smui/icon-button": "^7.0.0", + "@smui/layout-grid": "^7.0.0", + "@smui/linear-progress": "^7.0.0", + "@smui/list": "^7.0.0", + "@smui/paper": "^7.0.0", + "@smui/ripple": "^7.0.0", + "@smui/select": "^7.0.0", + "@smui/slider": "^7.0.0", + "@smui/snackbar": "^7.0.0", + "@smui/switch": "^7.0.0", + "@smui/tab": "^7.0.0", + "@smui/tab-bar": "^7.0.0", + "@smui/textfield": "^7.0.0", + "@smui/tooltip": "^7.0.0", + "@smui/top-app-bar": "^7.0.0", + "@smui/touch-target": "^7.0.0", "@sveltejs/kit": "^2.5.2", "@sveltejs/vite-plugin-svelte": "^3.0.2", "@types/js-cookie": "^3.0.6", @@ -71,7 +71,6 @@ "svelte-check": "^3.6.3", "svelte-kit-sst": "^2.40.1", "svelte-markdown": "^0.4.1", - "svelte-material-ui": "^7.0.0-beta.16", "tailwindcss": "^3.4.1", "typescript": "^5.3.2", "vite": "^5.1.3", @@ -84,7 +83,7 @@ "js-cookie": "^3.0.5", "lucia": "^3.0.1", "mongodb": "4.13.0", - "oslo": "^1.1.3", + "oslo": "^1.2.0", "qrcode": "^1.5.3", "scoutradioz-helpers": "../scoutradioz-helpers/", "scoutradioz-utilities": "../scoutradioz-utilities/", diff --git a/voyager/src/lib/logger.ts b/voyager/src/lib/logger.ts index 504f753f..0795f3ff 100644 --- a/voyager/src/lib/logger.ts +++ b/voyager/src/lib/logger.ts @@ -57,8 +57,8 @@ class Logger { let str = messages.map(message => { if (this.funcName) message = `[${this.funcName}] `; if (typeof message === 'string') return message; - if (message instanceof Error) return String(message); - else return JSON.stringify(message); + if (message instanceof Error) return message.stack || String(message) + else return JSON.stringify(message).replace(/,/g, ', '); }).join(' '); buffer.push({ diff --git a/voyager/src/routes/+layout.ts b/voyager/src/routes/+layout.ts index 8846e5ba..d9d26119 100644 --- a/voyager/src/routes/+layout.ts +++ b/voyager/src/routes/+layout.ts @@ -1,8 +1,7 @@ -import type { LayoutLoad } from './$types'; -import { i18n } from '$lib/i18n'; import { browser } from '$app/environment'; -import db, { type str } from '$lib/localDB'; -import type { Event } from 'scoutradioz-types'; +import { i18n } from '$lib/i18n'; +import db, { type EventLocal } from '$lib/localDB'; +import type { LayoutLoad } from './$types'; export const ssr = false; export const prerender = false; @@ -18,7 +17,7 @@ export const load: LayoutLoad = async () => { const org = await db.orgs.where({ org_key }).first(); let event_key: string | undefined; - let event: str | undefined; + let event: EventLocal | undefined; if (org?.event_key) { event_key = org.event_key; event = await db.events.where('key').equals(event_key).first(); diff --git a/voyager/src/routes/debug/+page.svelte b/voyager/src/routes/debug/+page.svelte index 1cc118dd..a43a2235 100644 --- a/voyager/src/routes/debug/+page.svelte +++ b/voyager/src/routes/debug/+page.svelte @@ -2,20 +2,19 @@ import db, { type Log } from '$lib/localDB'; import { - type logLevel, - logLevelStringToNumber, + getGlobalLogLevel, logLevelNumberToString, + logLevelStringToNumber, setGlobalLogLevel, - getGlobalLogLevel + type logLevel } from '$lib/logger'; - import Select, { Option } from '@smui/select'; - import DataTable, { Head, Body, Row, Cell, Pagination, Label } from '@smui/data-table'; + import { getPageLayoutContexts } from '$lib/utils'; + import DataTable, { Body, Cell, Head, Label, Pagination, Row } from '@smui/data-table'; import IconButton from '@smui/icon-button'; + import Select, { Option } from '@smui/select'; import { liveQuery, type IndexableTypeArray, type Observable } from 'dexie'; - import { getContext } from 'svelte'; - import type { SnackbarContext } from '$lib/types'; - let snackbar = getContext('snackbar') as SnackbarContext; + const { snackbar, dialog} = getPageLayoutContexts(); let groups: Observable; $: groups = liveQuery(() => db.logs.orderBy('group').uniqueKeys()); @@ -35,6 +34,8 @@ }); let rowsPerPage = 10; let currentPage = 0; + + const maxMessageLength = 100; $: start = currentPage * rowsPerPage; $: end = Math.min(start + rowsPerPage, $items?.length); @@ -93,15 +94,6 @@ }}>Flush server database cache - -

Logging behavior