Enable esnext and fix all lint errors (#7094)

* enable esnext and fix all lint errors

* Review update

* Missed some

* Some cleanup still

* Remove leftover eslint disable
This commit is contained in:
Jukka Kurkela 2020-02-14 01:41:49 +02:00 committed by GitHub
parent 7609385544
commit 25a9969489
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
66 changed files with 1609 additions and 1063 deletions

View File

@ -1,12 +1,24 @@
extends: chartjs
extends:
- chartjs
- esnext
env:
es6: true
browser: true
node: true
parser: babel-eslint
parserOptions:
ecmaVersion: 2018
sourceType: 'module'
ecmaVersion: 7
sourceType: module
ecmaFeatures:
impliedStrict: true
modules: true
experimentalObjectRestSpread: true
plugins: ['html']
rules:
class-methods-use-this: 0
no-empty-function: 0

673
package-lock.json generated
View File

@ -2338,6 +2338,17 @@
"integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=",
"dev": true
},
"array-includes": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.1.tgz",
"integrity": "sha512-c2VXaCHl7zPsvpkFsw4nxvFie4fh1ur9bpcgsVkIjqn0H/Xwdg+7fv3n2r/isyS8EBj5b06M9kHyZuIr4El6WQ==",
"dev": true,
"requires": {
"define-properties": "^1.1.3",
"es-abstract": "^1.17.0",
"is-string": "^1.0.5"
}
},
"array-initial": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/array-initial/-/array-initial-1.1.0.tgz",
@ -2404,6 +2415,16 @@
"integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=",
"dev": true
},
"array.prototype.flat": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.2.3.tgz",
"integrity": "sha512-gBlRZV0VSmfPIeWfuuy56XZMvbVfbEUnOXUvt3F/eUUUSyzlgLxhEX4YAEpxNAogRGehPSnfXyPtYyKAhkzQhQ==",
"dev": true,
"requires": {
"define-properties": "^1.1.3",
"es-abstract": "^1.17.0-next.1"
}
},
"arraybuffer.slice": {
"version": "0.0.7",
"resolved": "https://registry.npmjs.org/arraybuffer.slice/-/arraybuffer.slice-0.0.7.tgz",
@ -2553,6 +2574,20 @@
}
}
},
"babel-eslint": {
"version": "10.0.3",
"resolved": "https://registry.npmjs.org/babel-eslint/-/babel-eslint-10.0.3.tgz",
"integrity": "sha512-z3U7eMY6r/3f3/JB9mTsLjyxrv0Yb1zb8PCWCLpguxfCzBIZUwy23R1t/XKewP+8mEN2Ck8Dtr4q20z6ce6SoA==",
"dev": true,
"requires": {
"@babel/code-frame": "^7.0.0",
"@babel/parser": "^7.0.0",
"@babel/traverse": "^7.0.0",
"@babel/types": "^7.0.0",
"eslint-visitor-keys": "^1.0.0",
"resolve": "^1.12.0"
}
},
"babel-generator": {
"version": "6.26.1",
"resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz",
@ -3878,6 +3913,12 @@
}
}
},
"contains-path": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/contains-path/-/contains-path-0.1.0.tgz",
"integrity": "sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo=",
"dev": true
},
"content-type": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz",
@ -4446,6 +4487,44 @@
"is-arrayish": "^0.2.1"
}
},
"es-abstract": {
"version": "1.17.4",
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.4.tgz",
"integrity": "sha512-Ae3um/gb8F0mui/jPL+QiqmglkUsaQf7FwBEHYIFkztkneosu9imhqHpBzQ3h1vit8t5iQ74t6PEVvphBZiuiQ==",
"dev": true,
"requires": {
"es-to-primitive": "^1.2.1",
"function-bind": "^1.1.1",
"has": "^1.0.3",
"has-symbols": "^1.0.1",
"is-callable": "^1.1.5",
"is-regex": "^1.0.5",
"object-inspect": "^1.7.0",
"object-keys": "^1.1.1",
"object.assign": "^4.1.0",
"string.prototype.trimleft": "^2.1.1",
"string.prototype.trimright": "^2.1.1"
},
"dependencies": {
"has-symbols": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz",
"integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==",
"dev": true
}
}
},
"es-to-primitive": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz",
"integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==",
"dev": true,
"requires": {
"is-callable": "^1.1.4",
"is-date-object": "^1.0.1",
"is-symbol": "^1.0.2"
}
},
"es5-ext": {
"version": "0.10.52",
"resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.52.tgz",
@ -4636,6 +4715,293 @@
"integrity": "sha512-9NbZlmn5clHbzFc+EK7zp7KhgU2vhcbJNb4OrSrm9nMOMTs7yVdzP00jqqfs7dhDkhT4CfVxQlV1DMfjhGBLIA==",
"dev": true
},
"eslint-config-esnext": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/eslint-config-esnext/-/eslint-config-esnext-4.0.0.tgz",
"integrity": "sha512-UOovbox5WIgG9VSJPxtCsfwOkK96yNp8hBBi+WZ66OTr5zc7PxJCkE4MS7vON2Z1md5PNhwFHVzE9Uu+owBg1Q==",
"dev": true,
"requires": {
"babel-eslint": "^10.0.1",
"eslint": "^5.6.0",
"eslint-plugin-babel": "^5.2.1",
"eslint-plugin-import": "^2.14.0"
},
"dependencies": {
"acorn": {
"version": "6.4.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-6.4.0.tgz",
"integrity": "sha512-gac8OEcQ2Li1dxIEWGZzsp2BitJxwkwcOm0zHAJLcPJaVvm58FRnk6RkuLRpU1EujipU2ZFODv2P9DLMfnV8mw==",
"dev": true
},
"ansi-escapes": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz",
"integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==",
"dev": true
},
"ansi-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
"integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
"dev": true
},
"cli-cursor": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz",
"integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=",
"dev": true,
"requires": {
"restore-cursor": "^2.0.0"
}
},
"eslint": {
"version": "5.16.0",
"resolved": "https://registry.npmjs.org/eslint/-/eslint-5.16.0.tgz",
"integrity": "sha512-S3Rz11i7c8AA5JPv7xAH+dOyq/Cu/VXHiHXBPOU1k/JAM5dXqQPt3qcrhpHSorXmrpu2g0gkIBVXAqCpzfoZIg==",
"dev": true,
"requires": {
"@babel/code-frame": "^7.0.0",
"ajv": "^6.9.1",
"chalk": "^2.1.0",
"cross-spawn": "^6.0.5",
"debug": "^4.0.1",
"doctrine": "^3.0.0",
"eslint-scope": "^4.0.3",
"eslint-utils": "^1.3.1",
"eslint-visitor-keys": "^1.0.0",
"espree": "^5.0.1",
"esquery": "^1.0.1",
"esutils": "^2.0.2",
"file-entry-cache": "^5.0.1",
"functional-red-black-tree": "^1.0.1",
"glob": "^7.1.2",
"globals": "^11.7.0",
"ignore": "^4.0.6",
"import-fresh": "^3.0.0",
"imurmurhash": "^0.1.4",
"inquirer": "^6.2.2",
"js-yaml": "^3.13.0",
"json-stable-stringify-without-jsonify": "^1.0.1",
"levn": "^0.3.0",
"lodash": "^4.17.11",
"minimatch": "^3.0.4",
"mkdirp": "^0.5.1",
"natural-compare": "^1.4.0",
"optionator": "^0.8.2",
"path-is-inside": "^1.0.2",
"progress": "^2.0.0",
"regexpp": "^2.0.1",
"semver": "^5.5.1",
"strip-ansi": "^4.0.0",
"strip-json-comments": "^2.0.1",
"table": "^5.2.3",
"text-table": "^0.2.0"
}
},
"eslint-scope": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.3.tgz",
"integrity": "sha512-p7VutNr1O/QrxysMo3E45FjYDTeXBy0iTltPFNSqKAIfjDSXC+4dj+qfyuD8bfAXrW/y6lW3O76VaYNPKfpKrg==",
"dev": true,
"requires": {
"esrecurse": "^4.1.0",
"estraverse": "^4.1.1"
}
},
"espree": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/espree/-/espree-5.0.1.tgz",
"integrity": "sha512-qWAZcWh4XE/RwzLJejfcofscgMc9CamR6Tn1+XRXNzrvUSSbiAjGOI/fggztjIi7y9VLPqnICMIPiGyr8JaZ0A==",
"dev": true,
"requires": {
"acorn": "^6.0.7",
"acorn-jsx": "^5.0.0",
"eslint-visitor-keys": "^1.0.0"
}
},
"figures": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz",
"integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=",
"dev": true,
"requires": {
"escape-string-regexp": "^1.0.5"
}
},
"inquirer": {
"version": "6.5.2",
"resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.5.2.tgz",
"integrity": "sha512-cntlB5ghuB0iuO65Ovoi8ogLHiWGs/5yNrtUcKjFhSSiVeAIVpD7koaSU9RM8mpXw5YDi9RdYXGQMaOURB7ycQ==",
"dev": true,
"requires": {
"ansi-escapes": "^3.2.0",
"chalk": "^2.4.2",
"cli-cursor": "^2.1.0",
"cli-width": "^2.0.0",
"external-editor": "^3.0.3",
"figures": "^2.0.0",
"lodash": "^4.17.12",
"mute-stream": "0.0.7",
"run-async": "^2.2.0",
"rxjs": "^6.4.0",
"string-width": "^2.1.0",
"strip-ansi": "^5.1.0",
"through": "^2.3.6"
},
"dependencies": {
"ansi-regex": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz",
"integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==",
"dev": true
},
"strip-ansi": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz",
"integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==",
"dev": true,
"requires": {
"ansi-regex": "^4.1.0"
}
}
}
},
"is-fullwidth-code-point": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz",
"integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=",
"dev": true
},
"mimic-fn": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz",
"integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==",
"dev": true
},
"mute-stream": {
"version": "0.0.7",
"resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz",
"integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=",
"dev": true
},
"onetime": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz",
"integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=",
"dev": true,
"requires": {
"mimic-fn": "^1.0.0"
}
},
"restore-cursor": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz",
"integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=",
"dev": true,
"requires": {
"onetime": "^2.0.0",
"signal-exit": "^3.0.2"
}
},
"string-width": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz",
"integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==",
"dev": true,
"requires": {
"is-fullwidth-code-point": "^2.0.0",
"strip-ansi": "^4.0.0"
}
},
"strip-ansi": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
"integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
"dev": true,
"requires": {
"ansi-regex": "^3.0.0"
}
},
"strip-json-comments": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
"integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=",
"dev": true
}
}
},
"eslint-import-resolver-node": {
"version": "0.3.3",
"resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.3.tgz",
"integrity": "sha512-b8crLDo0M5RSe5YG8Pu2DYBj71tSB6OvXkfzwbJU2w7y8P4/yo0MyF8jU26IEuEuHF2K5/gcAJE3LhQGqBBbVg==",
"dev": true,
"requires": {
"debug": "^2.6.9",
"resolve": "^1.13.1"
},
"dependencies": {
"debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"dev": true,
"requires": {
"ms": "2.0.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
"dev": true
},
"resolve": {
"version": "1.15.1",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.15.1.tgz",
"integrity": "sha512-84oo6ZTtoTUpjgNEr5SJyzQhzL72gaRodsSfyxC/AXRvwu0Yse9H8eF9IpGo7b8YetZhlI6v7ZQ6bKBFV/6S7w==",
"dev": true,
"requires": {
"path-parse": "^1.0.6"
}
}
}
},
"eslint-module-utils": {
"version": "2.5.2",
"resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.5.2.tgz",
"integrity": "sha512-LGScZ/JSlqGKiT8OC+cYRxseMjyqt6QO54nl281CK93unD89ijSeRV6An8Ci/2nvWVKe8K/Tqdm75RQoIOCr+Q==",
"dev": true,
"requires": {
"debug": "^2.6.9",
"pkg-dir": "^2.0.0"
},
"dependencies": {
"debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"dev": true,
"requires": {
"ms": "2.0.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
"dev": true
}
}
},
"eslint-plugin-babel": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-babel/-/eslint-plugin-babel-5.3.0.tgz",
"integrity": "sha512-HPuNzSPE75O+SnxHIafbW5QB45r2w78fxqwK3HmjqIUoPfPzVrq6rD+CINU3yzoDSzEhUkX07VUphbF73Lth/w==",
"dev": true,
"requires": {
"eslint-rule-composer": "^0.3.0"
}
},
"eslint-plugin-html": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-html/-/eslint-plugin-html-6.0.0.tgz",
@ -4645,6 +5011,156 @@
"htmlparser2": "^3.10.1"
}
},
"eslint-plugin-import": {
"version": "2.20.1",
"resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.20.1.tgz",
"integrity": "sha512-qQHgFOTjguR+LnYRoToeZWT62XM55MBVXObHM6SKFd1VzDcX/vqT1kAz8ssqigh5eMj8qXcRoXXGZpPP6RfdCw==",
"dev": true,
"requires": {
"array-includes": "^3.0.3",
"array.prototype.flat": "^1.2.1",
"contains-path": "^0.1.0",
"debug": "^2.6.9",
"doctrine": "1.5.0",
"eslint-import-resolver-node": "^0.3.2",
"eslint-module-utils": "^2.4.1",
"has": "^1.0.3",
"minimatch": "^3.0.4",
"object.values": "^1.1.0",
"read-pkg-up": "^2.0.0",
"resolve": "^1.12.0"
},
"dependencies": {
"debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"dev": true,
"requires": {
"ms": "2.0.0"
}
},
"doctrine": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/doctrine/-/doctrine-1.5.0.tgz",
"integrity": "sha1-N53Ocw9hZvds76TmcHoVmwLFpvo=",
"dev": true,
"requires": {
"esutils": "^2.0.2",
"isarray": "^1.0.0"
}
},
"find-up": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz",
"integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=",
"dev": true,
"requires": {
"locate-path": "^2.0.0"
}
},
"load-json-file": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz",
"integrity": "sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg=",
"dev": true,
"requires": {
"graceful-fs": "^4.1.2",
"parse-json": "^2.2.0",
"pify": "^2.0.0",
"strip-bom": "^3.0.0"
}
},
"locate-path": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz",
"integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=",
"dev": true,
"requires": {
"p-locate": "^2.0.0",
"path-exists": "^3.0.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
"dev": true
},
"p-limit": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz",
"integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==",
"dev": true,
"requires": {
"p-try": "^1.0.0"
}
},
"p-locate": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz",
"integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=",
"dev": true,
"requires": {
"p-limit": "^1.1.0"
}
},
"p-try": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz",
"integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=",
"dev": true
},
"path-exists": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz",
"integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=",
"dev": true
},
"path-type": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/path-type/-/path-type-2.0.0.tgz",
"integrity": "sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM=",
"dev": true,
"requires": {
"pify": "^2.0.0"
}
},
"read-pkg": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz",
"integrity": "sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg=",
"dev": true,
"requires": {
"load-json-file": "^2.0.0",
"normalize-package-data": "^2.3.2",
"path-type": "^2.0.0"
}
},
"read-pkg-up": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-2.0.0.tgz",
"integrity": "sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4=",
"dev": true,
"requires": {
"find-up": "^2.0.0",
"read-pkg": "^2.0.0"
}
},
"strip-bom": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",
"integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=",
"dev": true
}
}
},
"eslint-rule-composer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/eslint-rule-composer/-/eslint-rule-composer-0.3.0.tgz",
"integrity": "sha512-bt+Sh8CtDmn2OajxvNO+BX7Wn4CIWMpTRm3MaiKPCQcnnlm0CS2mhui6QaoeQugs+3Kj2ESKEEGJUdVafwhiCg==",
"dev": true
},
"eslint-scope": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.0.0.tgz",
@ -6482,6 +6998,15 @@
"har-schema": "^2.0.0"
}
},
"has": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",
"integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==",
"dev": true,
"requires": {
"function-bind": "^1.1.1"
}
},
"has-ansi": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz",
@ -6826,6 +7351,12 @@
"integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==",
"dev": true
},
"is-callable": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.5.tgz",
"integrity": "sha512-ESKv5sMCJB2jnHTWZ3O5itG+O128Hsus4K4Qh1h2/cgn2vbgnLSVqfV46AeJA9D5EeeLa9w81KUXMtn34zhX+Q==",
"dev": true
},
"is-data-descriptor": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz",
@ -6846,6 +7377,12 @@
}
}
},
"is-date-object": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.2.tgz",
"integrity": "sha512-USlDT524woQ08aoZFzh3/Z6ch9Y/EWXEHQ/AaRN0SkKq4t2Jw2R2339tSXmwuVoY7LLlBCbOIlx2myP/L5zk0g==",
"dev": true
},
"is-descriptor": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz",
@ -6957,6 +7494,15 @@
"@types/estree": "0.0.39"
}
},
"is-regex": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.5.tgz",
"integrity": "sha512-vlKW17SNq44owv5AQR3Cq0bQPEb8+kF3UKZ2fiZNOWtztYE5i0CzCZxFDwO58qAOWtxdBRVO/V5Qin1wjCqFYQ==",
"dev": true,
"requires": {
"has": "^1.0.3"
}
},
"is-relative": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-relative/-/is-relative-1.0.0.tgz",
@ -6966,6 +7512,29 @@
"is-unc-path": "^1.0.0"
}
},
"is-string": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.5.tgz",
"integrity": "sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ==",
"dev": true
},
"is-symbol": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.3.tgz",
"integrity": "sha512-OwijhaRSgqvhm/0ZdAcXNZt9lYdKFpcRDT5ULUuYXPoT794UNOdU+gpT6Rzo7b4V2HUl/op6GqY894AZwv9faQ==",
"dev": true,
"requires": {
"has-symbols": "^1.0.1"
},
"dependencies": {
"has-symbols": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz",
"integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==",
"dev": true
}
}
},
"is-typedarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",
@ -12885,6 +13454,12 @@
}
}
},
"object-inspect": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.7.0.tgz",
"integrity": "sha512-a7pEHdh1xKIAgTySUGgLMx/xwDZskN1Ud6egYYN3EdRW4ZMPNEDUTF+hwy2LUC+Bl+SyLXANnwz/jyh/qutKUw==",
"dev": true
},
"object-keys": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
@ -12953,6 +13528,18 @@
"make-iterator": "^1.0.0"
}
},
"object.values": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.1.tgz",
"integrity": "sha512-WTa54g2K8iu0kmS/us18jEmdv1a4Wi//BZ/DTVYEcH0XhLM5NYdpDHja3gt57VrZLcNAO2WGA+KpWsDBaHt6eA==",
"dev": true,
"requires": {
"define-properties": "^1.1.3",
"es-abstract": "^1.17.0-next.1",
"function-bind": "^1.1.1",
"has": "^1.0.3"
}
},
"on-finished": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
@ -13190,6 +13777,12 @@
"integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=",
"dev": true
},
"path-is-inside": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz",
"integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=",
"dev": true
},
"path-key": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz",
@ -13279,6 +13872,66 @@
"pngjs": "^3.4.0"
}
},
"pkg-dir": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz",
"integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=",
"dev": true,
"requires": {
"find-up": "^2.1.0"
},
"dependencies": {
"find-up": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz",
"integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=",
"dev": true,
"requires": {
"locate-path": "^2.0.0"
}
},
"locate-path": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz",
"integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=",
"dev": true,
"requires": {
"p-locate": "^2.0.0",
"path-exists": "^3.0.0"
}
},
"p-limit": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz",
"integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==",
"dev": true,
"requires": {
"p-try": "^1.0.0"
}
},
"p-locate": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz",
"integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=",
"dev": true,
"requires": {
"p-limit": "^1.1.0"
}
},
"p-try": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz",
"integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=",
"dev": true
},
"path-exists": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz",
"integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=",
"dev": true
}
}
},
"plexer": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/plexer/-/plexer-1.0.1.tgz",
@ -14633,6 +15286,26 @@
}
}
},
"string.prototype.trimleft": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/string.prototype.trimleft/-/string.prototype.trimleft-2.1.1.tgz",
"integrity": "sha512-iu2AGd3PuP5Rp7x2kEZCrB2Nf41ehzh+goo8TV7z8/XDBbsvc6HQIlUl9RjkZ4oyrW1XM5UwlGl1oVEaDjg6Ag==",
"dev": true,
"requires": {
"define-properties": "^1.1.3",
"function-bind": "^1.1.1"
}
},
"string.prototype.trimright": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/string.prototype.trimright/-/string.prototype.trimright-2.1.1.tgz",
"integrity": "sha512-qFvWL3/+QIgZXVmJBfpHmxLB7xsUXz6HsUmP8+5dRaC3Q7oKUv9Vo6aMCRZC1smrtyECFsIT30PqBJ1gTjAs+g==",
"dev": true,
"requires": {
"define-properties": "^1.1.3",
"function-bind": "^1.1.1"
}
},
"string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",

View File

@ -37,6 +37,7 @@
"coveralls": "^3.0.9",
"eslint": "^6.8.0",
"eslint-config-chartjs": "^0.2.0",
"eslint-config-esnext": "^4.0.0",
"eslint-plugin-html": "^6.0.0",
"gitbook-cli": "^2.3.2",
"gulp": "^4.0.0",

View File

@ -7,3 +7,8 @@ globals:
rules:
no-new: 0
no-var: 0
object-shorthand: 0
prefer-arrow-callback: 0
no-invalid-this: 0
no-unneeded-ternary: 0

View File

@ -1,7 +1,5 @@
// TODO v3 - make this adapter external (chartjs-adapter-moment)
'use strict';
import moment from 'moment';
import adapters from '../core/core.adapters';
@ -21,11 +19,11 @@ const FORMATS = {
adapters._date.override(typeof moment === 'function' ? {
_id: 'moment', // DEBUG ONLY
formats: function() {
formats() {
return FORMATS;
},
parse: function(value, format) {
parse(value, format) {
if (typeof value === 'string' && typeof format === 'string') {
value = moment(value, format);
} else if (!(value instanceof moment)) {
@ -34,19 +32,19 @@ adapters._date.override(typeof moment === 'function' ? {
return value.isValid() ? value.valueOf() : null;
},
format: function(time, format) {
format(time, format) {
return moment(time).format(format);
},
add: function(time, amount, unit) {
add(time, amount, unit) {
return moment(time).add(amount, unit).valueOf();
},
diff: function(max, min, unit) {
diff(max, min, unit) {
return moment(max).diff(moment(min), unit);
},
startOf: function(time, unit, weekday) {
startOf(time, unit, weekday) {
time = moment(time);
if (unit === 'isoWeek') {
return time.isoWeekday(weekday).valueOf();
@ -54,7 +52,7 @@ adapters._date.override(typeof moment === 'function' ? {
return time.startOf(unit).valueOf();
},
endOf: function(time, unit) {
endOf(time, unit) {
return moment(time).endOf(unit).valueOf();
}
} : {});

View File

@ -1,5 +1,3 @@
'use strict';
// -----------------------------------------------------------------------------
// IMPORTANT: do NOT submit new adapters to this repository, instead
// create an external library named `chartjs-adapter-{lib-name}`

View File

@ -1,5 +1,3 @@
'use strict';
import DatasetController from '../core/core.datasetController';
import defaults from '../core/core.defaults';
import Rectangle from '../elements/element.rectangle';
@ -43,8 +41,8 @@ defaults.set('bar', {
* @private
*/
function computeMinSampleSize(scale, pixels) {
var min = scale._length;
var prev, curr, i, ilen;
let min = scale._length;
let prev, curr, i, ilen;
for (i = 1, ilen = pixels.length; i < ilen; ++i) {
min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
@ -66,13 +64,13 @@ function computeMinSampleSize(scale, pixels) {
* @private
*/
function computeFitCategoryTraits(index, ruler, options) {
var thickness = options.barThickness;
var count = ruler.stackCount;
var curr = ruler.pixels[index];
var min = isNullOrUndef(thickness)
const thickness = options.barThickness;
const count = ruler.stackCount;
const curr = ruler.pixels[index];
const min = isNullOrUndef(thickness)
? computeMinSampleSize(ruler.scale, ruler.pixels)
: -1;
var size, ratio;
let size, ratio;
if (isNullOrUndef(thickness)) {
size = min * options.categoryPercentage;
@ -87,7 +85,7 @@ function computeFitCategoryTraits(index, ruler, options) {
return {
chunk: size / count,
ratio: ratio,
ratio,
start: curr - (size / 2)
};
}
@ -99,12 +97,11 @@ function computeFitCategoryTraits(index, ruler, options) {
* @private
*/
function computeFlexCategoryTraits(index, ruler, options) {
var pixels = ruler.pixels;
var curr = pixels[index];
var prev = index > 0 ? pixels[index - 1] : null;
var next = index < pixels.length - 1 ? pixels[index + 1] : null;
var percent = options.categoryPercentage;
var start, size;
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) {
// first data: its size is double based on the next point or,
@ -117,23 +114,23 @@ function computeFlexCategoryTraits(index, ruler, options) {
next = curr + curr - prev;
}
start = curr - (curr - Math.min(prev, next)) / 2 * percent;
size = Math.abs(next - prev) / 2 * percent;
const start = curr - (curr - Math.min(prev, next)) / 2 * percent;
const size = Math.abs(next - prev) / 2 * percent;
return {
chunk: size / ruler.stackCount,
ratio: options.barPercentage,
start: start
start
};
}
function parseFloatBar(arr, item, vScale, i) {
var startValue = vScale._parse(arr[0], i);
var endValue = vScale._parse(arr[1], i);
var min = Math.min(startValue, endValue);
var max = Math.max(startValue, endValue);
var barStart = min;
var barEnd = max;
const startValue = vScale._parse(arr[0], i);
const endValue = vScale._parse(arr[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;
@ -145,12 +142,12 @@ function parseFloatBar(arr, item, vScale, i) {
item[vScale.axis] = barEnd;
item._custom = {
barStart: barStart,
barEnd: barEnd,
barStart,
barEnd,
start: startValue,
end: endValue,
min: min,
max: max
min,
max
};
}
@ -184,17 +181,13 @@ function isFloatBar(custom) {
class BarController extends DatasetController {
constructor(chart, datasetIndex) {
super(chart, datasetIndex);
}
/**
* Overriding primitive data parsing since we support mixed primitive/array
* data for float bars
* @private
*/
_parsePrimitiveData() {
return parseArrayOrPrimitive.apply(this, arguments);
_parsePrimitiveData(meta, data, start, count) {
return parseArrayOrPrimitive(meta, data, start, count);
}
/**
@ -202,8 +195,8 @@ class BarController extends DatasetController {
* data for float bars
* @private
*/
_parseArrayData() {
return parseArrayOrPrimitive.apply(this, arguments);
_parseArrayData(meta, data, start, count) {
return parseArrayOrPrimitive(meta, data, start, count);
}
/**
@ -246,17 +239,16 @@ class BarController extends DatasetController {
return {
label: '' + iScale.getLabelForValue(parsed[iScale.axis]),
value: value
value
};
}
initialize() {
var me = this;
var meta;
const me = this;
DatasetController.prototype.initialize.apply(me, arguments);
super.initialize();
meta = me._cachedMeta;
const meta = me._cachedMeta;
meta.stack = me.getDataset().stack;
meta.bar = true;
}
@ -369,8 +361,8 @@ class BarController extends DatasetController {
* @private
*/
_getStackIndex(datasetIndex, name) {
var stacks = this._getStacks(datasetIndex);
var index = (name !== undefined)
const stacks = this._getStacks(datasetIndex);
const index = (name !== undefined)
? stacks.indexOf(name)
: -1; // indexOf returns -1 if element is not present
@ -416,7 +408,7 @@ class BarController extends DatasetController {
let value = parsed[vScale.axis];
let start = 0;
let length = meta._stacked ? me._applyStack(vScale, parsed) : value;
let base, head, size;
let head, size;
if (length !== value) {
start = length - value;
@ -437,7 +429,7 @@ class BarController extends DatasetController {
// So we don't try to draw so huge rectangles.
// https://github.com/chartjs/Chart.js/issues/5247
// TODO: use borderWidth instead (need to move the parsing from rectangle)
base = _limitValue(vScale.getPixelForValue(start),
const base = _limitValue(vScale.getPixelForValue(start),
vScale._startPixel - 10,
vScale._endPixel + 10);
@ -450,9 +442,9 @@ class BarController extends DatasetController {
}
return {
size: size,
base: base,
head: head,
size,
base,
head,
center: head + size / 2
};
}
@ -461,22 +453,22 @@ class BarController extends DatasetController {
* @private
*/
_calculateBarIndexPixels(index, ruler, options) {
var me = this;
var range = options.barThickness === 'flex'
const me = this;
const range = options.barThickness === 'flex'
? computeFlexCategoryTraits(index, ruler, options)
: computeFitCategoryTraits(index, ruler, options);
var stackIndex = me._getStackIndex(me.index, me._cachedMeta.stack);
var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
var size = Math.min(
const stackIndex = me._getStackIndex(me.index, me._cachedMeta.stack);
const center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
const size = Math.min(
valueOrDefault(options.maxBarThickness, Infinity),
range.chunk * range.ratio);
return {
base: center - size / 2,
head: center + size / 2,
center: center,
size: size
center,
size
};
}

View File

@ -1,5 +1,3 @@
'use strict';
import DatasetController from '../core/core.datasetController';
import defaults from '../core/core.defaults';
import Point from '../elements/element.point';
@ -25,7 +23,7 @@ defaults.set('bubble', {
tooltips: {
callbacks: {
title: function() {
title() {
// Title doesn't make sense for scatter since we format the data as a point
return '';
}
@ -35,10 +33,6 @@ defaults.set('bubble', {
class BubbleController extends DatasetController {
constructor(chart, datasetIndex) {
super(chart, datasetIndex);
}
/**
* Parse array of objects
* @private
@ -142,17 +136,17 @@ class BubbleController extends DatasetController {
* @private
*/
_resolveDataElementOptions(index, mode) {
var me = this;
var chart = me.chart;
var dataset = me.getDataset();
var parsed = me._getParsed(index);
var values = super._resolveDataElementOptions.apply(me, arguments);
const me = this;
const chart = me.chart;
const dataset = me.getDataset();
const parsed = me._getParsed(index);
let values = super._resolveDataElementOptions(index, mode);
// Scriptable options
var context = {
chart: chart,
const context = {
chart,
dataIndex: index,
dataset: dataset,
dataset,
datasetIndex: me.index
};

View File

@ -1,5 +1,3 @@
'use strict';
import DatasetController from '../core/core.datasetController';
import defaults from '../core/core.defaults';
import Arc from '../elements/element.arc';
@ -22,12 +20,12 @@ defaults.set('doughnut', {
},
legend: {
labels: {
generateLabels: function(chart) {
var data = chart.data;
generateLabels(chart) {
const data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function(label, i) {
var meta = chart.getDatasetMeta(0);
var style = meta.controller.getStyle(i);
return data.labels.map((label, i) => {
const meta = chart.getDatasetMeta(0);
const style = meta.controller.getStyle(i);
return {
text: label,
@ -45,10 +43,10 @@ defaults.set('doughnut', {
}
},
onClick: function(e, legendItem) {
var index = legendItem.index;
var chart = this.chart;
var i, ilen, meta;
onClick(e, legendItem) {
const index = legendItem.index;
const chart = this.chart;
let i, ilen, meta;
for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
@ -74,12 +72,12 @@ defaults.set('doughnut', {
// Need to override these to give a nice default
tooltips: {
callbacks: {
title: function() {
title() {
return '';
},
label: function(tooltipItem, data) {
var dataLabel = data.labels[tooltipItem.index];
var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
label(tooltipItem, data) {
let dataLabel = data.labels[tooltipItem.index];
const value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
if (isArray(dataLabel)) {
// show value on first line of multiline label
@ -112,9 +110,9 @@ class DoughnutController extends DatasetController {
* @private
*/
_parse(start, count) {
var data = this.getDataset().data;
var meta = this._cachedMeta;
var i, ilen;
const data = this.getDataset().data;
const meta = this._cachedMeta;
let i, ilen;
for (i = start, ilen = start + count; i < ilen; ++i) {
meta._parsed[i] = +data[i];
}
@ -122,9 +120,9 @@ class DoughnutController extends DatasetController {
// Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
getRingIndex(datasetIndex) {
var ringIndex = 0;
let ringIndex = 0;
for (var j = 0; j < datasetIndex; ++j) {
for (let j = 0; j < datasetIndex; ++j) {
if (this.chart.isDatasetVisible(j)) {
++ringIndex;
}
@ -134,51 +132,50 @@ class DoughnutController extends DatasetController {
}
update(mode) {
var me = this;
var chart = me.chart;
var chartArea = chart.chartArea;
var opts = chart.options;
var ratioX = 1;
var ratioY = 1;
var offsetX = 0;
var offsetY = 0;
var meta = me._cachedMeta;
var arcs = meta.data;
var cutout = opts.cutoutPercentage / 100 || 0;
var circumference = opts.circumference;
var chartWeight = me._getRingWeight(me.index);
var maxWidth, maxHeight, i, ilen;
const me = this;
const chart = me.chart;
const chartArea = chart.chartArea;
const opts = chart.options;
let ratioX = 1;
let ratioY = 1;
let offsetX = 0;
let offsetY = 0;
const meta = me._cachedMeta;
const arcs = meta.data;
const cutout = opts.cutoutPercentage / 100 || 0;
const circumference = opts.circumference;
const chartWeight = me._getRingWeight(me.index);
// If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc
if (circumference < DOUBLE_PI) {
var startAngle = opts.rotation % DOUBLE_PI;
let startAngle = opts.rotation % DOUBLE_PI;
startAngle += startAngle >= PI ? -DOUBLE_PI : startAngle < -PI ? DOUBLE_PI : 0;
var endAngle = startAngle + circumference;
var startX = Math.cos(startAngle);
var startY = Math.sin(startAngle);
var endX = Math.cos(endAngle);
var endY = Math.sin(endAngle);
var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI;
var contains90 = (startAngle <= HALF_PI && endAngle >= HALF_PI) || endAngle >= DOUBLE_PI + HALF_PI;
var contains180 = startAngle === -PI || endAngle >= PI;
var contains270 = (startAngle <= -HALF_PI && endAngle >= -HALF_PI) || endAngle >= PI + HALF_PI;
var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);
var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);
var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);
var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);
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 contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI;
const contains90 = (startAngle <= HALF_PI && endAngle >= HALF_PI) || endAngle >= DOUBLE_PI + HALF_PI;
const contains180 = startAngle === -PI || endAngle >= PI;
const contains270 = (startAngle <= -HALF_PI && endAngle >= -HALF_PI) || endAngle >= PI + HALF_PI;
const minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);
const minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);
const maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);
const maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);
ratioX = (maxX - minX) / 2;
ratioY = (maxY - minY) / 2;
offsetX = -(maxX + minX) / 2;
offsetY = -(maxY + minY) / 2;
}
for (i = 0, ilen = arcs.length; i < ilen; ++i) {
for (let i = 0, ilen = arcs.length; i < ilen; ++i) {
arcs[i]._options = me._resolveDataElementOptions(i, mode);
}
chart.borderWidth = me.getMaxBorderWidth();
maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;
maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;
const maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;
const maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;
chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
chart.innerRadius = Math.max(chart.outerRadius * cutout, 0);
chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
@ -263,7 +260,7 @@ class DoughnutController extends DatasetController {
}
calculateCircumference(value) {
var total = this._cachedMeta.total;
const total = this._cachedMeta.total;
if (total > 0 && !isNaN(value)) {
return DOUBLE_PI * (Math.abs(value) / total);
}
@ -272,10 +269,10 @@ class DoughnutController extends DatasetController {
// gets the max border or hover width to properly scale pie charts
getMaxBorderWidth(arcs) {
var me = this;
var max = 0;
var chart = me.chart;
var i, ilen, meta, controller, options;
const me = this;
let max = 0;
const chart = me.chart;
let i, ilen, meta, controller, options;
if (!arcs) {
// Find the outmost visible dataset
@ -310,9 +307,9 @@ class DoughnutController extends DatasetController {
* @private
*/
_getRingWeightOffset(datasetIndex) {
var ringWeightOffset = 0;
let ringWeightOffset = 0;
for (var i = 0; i < datasetIndex; ++i) {
for (let i = 0; i < datasetIndex; ++i) {
if (this.chart.isDatasetVisible(i)) {
ringWeightOffset += this._getRingWeight(i);
}

View File

@ -1,5 +1,3 @@
'use strict';
import BarController from './controller.bar';
import defaults from '../core/core.defaults';
@ -44,10 +42,6 @@ defaults.set('horizontalBar', {
class HorizontalBarController extends BarController {
constructor(chart, datasetIndex) {
super(chart, datasetIndex);
}
/**
* @private
*/

View File

@ -1,5 +1,3 @@
'use strict';
import DatasetController from '../core/core.datasetController';
import defaults from '../core/core.defaults';
import Line from '../elements/element.line';
@ -96,12 +94,12 @@ class LineController extends DatasetController {
/**
* @private
*/
_resolveDatasetElementOptions() {
_resolveDatasetElementOptions(active) {
const me = this;
const config = me._config;
const options = me.chart.options;
const lineOptions = options.elements.line;
const values = DatasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
const values = super._resolveDatasetElementOptions(active);
// The default behavior of lines is to break at null values, according
// to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158

View File

@ -1,5 +1,3 @@
'use strict';
import DoughnutController from './controller.doughnut';
import defaults from '../core/core.defaults';
import {clone} from '../helpers/helpers.core';

View File

@ -1,5 +1,3 @@
'use strict';
import DatasetController from '../core/core.datasetController';
import defaults from '../core/core.defaults';
import Arc from '../elements/element.arc';
@ -34,12 +32,12 @@ defaults.set('polarArea', {
startAngle: 0,
legend: {
labels: {
generateLabels: function(chart) {
var data = chart.data;
generateLabels(chart) {
const data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function(label, i) {
var meta = chart.getDatasetMeta(0);
var style = meta.controller.getStyle(i);
return data.labels.map((label, i) => {
const meta = chart.getDatasetMeta(0);
const style = meta.controller.getStyle(i);
return {
text: label,
@ -57,10 +55,10 @@ defaults.set('polarArea', {
}
},
onClick: function(e, legendItem) {
var index = legendItem.index;
var chart = this.chart;
var i, ilen, meta;
onClick(e, legendItem) {
const index = legendItem.index;
const chart = this.chart;
let i, ilen, meta;
for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
@ -74,10 +72,10 @@ defaults.set('polarArea', {
// Need to override these to give a nice default
tooltips: {
callbacks: {
title: function() {
title() {
return '';
},
label: function(item, data) {
label(item, data) {
return data.labels[item.index] + ': ' + item.value;
}
}
@ -124,11 +122,11 @@ class PolarAreaController extends DatasetController {
* @private
*/
_updateRadius() {
var me = this;
var chart = me.chart;
var chartArea = chart.chartArea;
var opts = chart.options;
var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
const me = this;
const chart = me.chart;
const chartArea = chart.chartArea;
const opts = chart.options;
const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
chart.outerRadius = Math.max(minSize / 2, 0);
chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
@ -190,11 +188,11 @@ class PolarAreaController extends DatasetController {
}
countVisibleElements() {
var dataset = this.getDataset();
var meta = this._cachedMeta;
var count = 0;
const dataset = this.getDataset();
const meta = this._cachedMeta;
let count = 0;
meta.data.forEach(function(element, index) {
meta.data.forEach((element, index) => {
if (!isNaN(dataset.data[index]) && !element.hidden) {
count++;
}
@ -207,20 +205,20 @@ class PolarAreaController extends DatasetController {
* @private
*/
_computeAngle(index) {
var me = this;
var meta = me._cachedMeta;
var count = meta.count;
var dataset = me.getDataset();
const me = this;
const meta = me._cachedMeta;
const count = meta.count;
const dataset = me.getDataset();
if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
return 0;
}
// Scriptable options
var context = {
const context = {
chart: me.chart,
dataIndex: index,
dataset: dataset,
dataset,
datasetIndex: me.index
};

View File

@ -1,5 +1,3 @@
'use strict';
import DatasetController from '../core/core.datasetController';
import defaults from '../core/core.defaults';
import Line from '../elements/element.line';
@ -22,10 +20,6 @@ defaults.set('radar', {
class RadarController extends DatasetController {
constructor(chart, datasetIndex) {
super(chart, datasetIndex);
}
/**
* @private
*/
@ -106,11 +100,11 @@ class RadarController extends DatasetController {
/**
* @private
*/
_resolveDatasetElementOptions() {
_resolveDatasetElementOptions(active) {
const me = this;
const config = me._config;
const options = me.chart.options;
const values = super._resolveDatasetElementOptions.apply(me, arguments);
const values = super._resolveDatasetElementOptions(active);
values.spanGaps = valueOrDefault(config.spanGaps, options.spanGaps);
values.tension = valueOrDefault(config.lineTension, options.elements.line.tension);

View File

@ -1,5 +1,3 @@
'use strict';
import LineController from './controller.line';
import defaults from '../core/core.defaults';
@ -21,10 +19,10 @@ defaults.set('scatter', {
tooltips: {
callbacks: {
title: function() {
title() {
return ''; // doesn't make sense for scatter since data are formatted as a point
},
label: function(item) {
label(item) {
return '(' + item.label + ', ' + item.value + ')';
}
}

View File

@ -1,5 +1,3 @@
'use strict';
import bar from './controller.bar';
import bubble from './controller.bubble';
import doughnut from './controller.doughnut';
@ -15,13 +13,13 @@ import scatter from './controller.scatter';
// by the controller in core.controller.js (`controllers[meta.type]`).
export default {
bar: bar,
bubble: bubble,
doughnut: doughnut,
horizontalBar: horizontalBar,
line: line,
polarArea: polarArea,
pie: pie,
radar: radar,
scatter: scatter
bar,
bubble,
doughnut,
horizontalBar,
line,
polarArea,
pie,
radar,
scatter
};

View File

@ -4,8 +4,6 @@
* @private
*/
'use strict';
import {extend} from '../helpers/helpers.core';
/**

View File

@ -1,22 +1,20 @@
'use strict';
import helpers from '../helpers/index';
import {effects} from '../helpers/helpers.easing';
import effects from '../helpers/helpers.easing';
import {resolve} from '../helpers/helpers.options';
const transparent = 'transparent';
const interpolators = {
boolean: function(from, to, factor) {
boolean(from, to, factor) {
return factor > 0.5 ? to : from;
},
color: function(from, to, factor) {
var c0 = helpers.color(from || transparent);
var c1 = c0.valid && helpers.color(to || transparent);
color(from, to, factor) {
const c0 = helpers.color(from || transparent);
const c1 = c0.valid && helpers.color(to || transparent);
return c1 && c1.valid
? c1.mix(c0, factor).hexString()
: to;
},
number: function(from, to, factor) {
number(from, to, factor) {
return from + (to - from) * factor;
}
};
@ -26,7 +24,7 @@ class Animation {
const currentValue = target[prop];
to = resolve([cfg.to, to, currentValue, cfg.from]);
let from = resolve([cfg.from, currentValue, to]);
const from = resolve([cfg.from, currentValue, to]);
this._active = true;
this._fn = cfg.fn || interpolators[cfg.type || typeof from];

View File

@ -1,5 +1,3 @@
'use strict';
import Animator from './core.animator';
import Animation from './core.animation';
import defaults from '../core/core.defaults';
@ -57,8 +55,8 @@ defaults.set('animation', {
});
function copyOptions(target, values) {
let oldOpts = target.options;
let newOpts = values.options;
const oldOpts = target.options;
const newOpts = values.options;
if (!oldOpts || !newOpts || newOpts.$shared) {
return;
}
@ -101,7 +99,7 @@ export default class Animations {
if (!isObject(cfg)) {
return;
}
(cfg.properties || [key]).forEach(function(prop) {
(cfg.properties || [key]).forEach((prop) => {
// Can have only one config per animation.
if (!animatedProps.has(prop)) {
animatedProps.set(prop, extend({}, animDefaults, cfg));
@ -152,16 +150,16 @@ export default class Animations {
let i;
for (i = props.length - 1; i >= 0; --i) {
let prop = props[i];
const prop = props[i];
if (prop.charAt(0) === '$') {
continue;
}
if (prop === 'options') {
animations.push.apply(animations, this._animateOptions(target, values));
animations.push(...this._animateOptions(target, values));
continue;
}
let value = values[prop];
const value = values[prop];
let animation = running[prop];
if (animation) {
animation.cancel();

View File

@ -1,5 +1,3 @@
'use strict';
import helpers from '../helpers/index';
/**
@ -36,7 +34,7 @@ class Animator {
const numSteps = anims.duration;
callbacks.forEach(fn => fn({
chart: chart,
chart,
numSteps,
currentStep: date - anims.start
}));
@ -53,7 +51,7 @@ class Animator {
}
me._running = true;
me._request = helpers.requestAnimFrame.call(window, function() {
me._request = helpers.requestAnimFrame.call(window, () => {
me._update();
me._request = null;
@ -71,7 +69,7 @@ class Animator {
const date = Date.now();
let remaining = 0;
me._charts.forEach(function(anims, chart) {
me._charts.forEach((anims, chart) => {
if (!anims.running || !anims.items.length) {
return;
}

View File

@ -1,5 +1,3 @@
'use strict';
import Animator from './core.animator';
import controllers from '../controllers/index';
import defaults from './core.defaults';
@ -65,9 +63,9 @@ function mergeScaleConfig(config, options) {
* default scale options for the `scales` and `scale` properties, then returns
* a deep copy of the result, thus doesn't alter inputs.
*/
function mergeConfig(/* config objects ... */) {
return helpers.merge({}, [].slice.call(arguments), {
merger: function(key, target, source, options) {
function mergeConfig(...args/* config objects ... */) {
return helpers.merge({}, args, {
merger(key, target, source, options) {
if (key !== 'scales' && key !== 'scale') {
helpers._merger(key, target, source, options);
}
@ -101,9 +99,9 @@ function isAnimationDisabled(config) {
}
function updateConfig(chart) {
var newOptions = chart.options;
let newOptions = chart.options;
helpers.each(chart.scales, function(scale) {
helpers.each(chart.scales, (scale) => {
layouts.removeBox(chart, scale);
});
@ -215,10 +213,10 @@ class Chart {
// Define alias to the config data: `chart.data === chart.config.data`
Object.defineProperty(me, 'data', {
get: function() {
get() {
return me.config.data;
},
set: function(value) {
set(value) {
me.config.data = value;
}
});
@ -333,7 +331,7 @@ class Chart {
const scalesOptions = options.scales || {};
const scaleOptions = options.scale;
helpers.each(scalesOptions, function(axisOptions, axisID) {
helpers.each(scalesOptions, (axisOptions, axisID) => {
axisOptions.id = axisID;
});
@ -350,7 +348,7 @@ class Chart {
const options = me.options;
const scaleOpts = options.scales;
const scales = me.scales || {};
const updated = Object.keys(scales).reduce(function(obj, id) {
const updated = Object.keys(scales).reduce((obj, id) => {
obj[id] = false;
return obj;
}, {});
@ -358,7 +356,7 @@ class Chart {
if (scaleOpts) {
items = items.concat(
Object.keys(scaleOpts).map(function(axisID) {
Object.keys(scaleOpts).map((axisID) => {
const axisOptions = scaleOpts[axisID];
const isRadial = axisID.charAt(0).toLowerCase() === 'r';
const isHorizontal = axisID.charAt(0).toLowerCase() === 'x';
@ -371,7 +369,7 @@ class Chart {
);
}
helpers.each(items, function(item) {
helpers.each(items, (item) => {
const scaleOptions = item.options;
const id = scaleOptions.id;
const scaleType = valueOrDefault(scaleOptions.type, item.dtype);
@ -393,7 +391,7 @@ class Chart {
return;
}
scale = new scaleClass({
id: id,
id,
type: scaleType,
options: scaleOptions,
ctx: me.ctx,
@ -416,7 +414,7 @@ class Chart {
}
});
// clear up discarded scales
helpers.each(updated, function(hasUpdated, id) {
helpers.each(updated, (hasUpdated, id) => {
if (!hasUpdated) {
delete scales[id];
}
@ -507,7 +505,7 @@ class Chart {
*/
_resetElements() {
const me = this;
helpers.each(me.data.datasets, function(dataset, datasetIndex) {
helpers.each(me.data.datasets, (dataset, datasetIndex) => {
me.getDatasetMeta(datasetIndex).controller.reset();
}, me);
}
@ -548,7 +546,7 @@ class Chart {
// Can only reset the new controllers after the scales have been updated
if (me.options.animation) {
helpers.each(newControllers, function(controller) {
helpers.each(newControllers, (controller) => {
controller.reset();
});
}
@ -585,16 +583,16 @@ class Chart {
layouts.update(me, me.width, me.height);
me._layers = [];
helpers.each(me.boxes, function(box) {
helpers.each(me.boxes, (box) => {
// _configure is called twice, once in core.scale.update and once here.
// Here the boxes are fully updated and at their final positions.
if (box._configure) {
box._configure();
}
me._layers.push.apply(me._layers, box._layers());
me._layers.push(...box._layers());
}, me);
me._layers.forEach(function(item, index) {
me._layers.forEach((item, index) => {
item._idx = index;
});
@ -663,7 +661,7 @@ class Chart {
draw() {
const me = this;
let i, layers;
let i;
me.clear();
@ -678,7 +676,7 @@ class Chart {
// Because of plugin hooks (before/afterDatasetsDraw), datasets can't
// currently be part of layers. Instead, we draw
// layers <= 0 before(default, backward compat), and the rest after
layers = me._layers;
const layers = me._layers;
for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
layers[i].draw(me.chartArea);
}
@ -726,14 +724,13 @@ class Chart {
*/
_drawDatasets() {
const me = this;
let metasets, i;
if (plugins.notify(me, 'beforeDatasetsDraw') === false) {
return;
}
metasets = me._getSortedVisibleDatasetMetas();
for (i = metasets.length - 1; i >= 0; --i) {
const metasets = me._getSortedVisibleDatasetMetas();
for (let i = metasets.length - 1; i >= 0; --i) {
me._drawDataset(metasets[i]);
}
@ -751,7 +748,7 @@ class Chart {
const clip = meta._clip;
const area = me.chartArea;
const args = {
meta: meta,
meta,
index: meta.index,
};
@ -915,8 +912,8 @@ class Chart {
delete Chart.instances[me.id];
}
toBase64Image() {
return this.canvas.toDataURL.apply(this.canvas, arguments);
toBase64Image(...args) {
return this.canvas.toDataURL(...args);
}
/**
@ -925,11 +922,11 @@ class Chart {
bindEvents() {
const me = this;
const listeners = me._listeners;
let listener = function() {
me._eventHandler.apply(me, arguments);
let listener = function(e) {
me._eventHandler(e);
};
helpers.each(me.options.events, function(type) {
helpers.each(me.options.events, (type) => {
me.platform.addEventListener(me, type, listener);
listeners[type] = listener;
});
@ -957,7 +954,7 @@ class Chart {
}
delete me._listeners;
helpers.each(listeners, function(listener, type) {
helpers.each(listeners, (listener, type) => {
me.platform.removeEventListener(me, type, listener);
});
}

View File

@ -1,5 +1,3 @@
'use strict';
import helpers from '../helpers/index';
import Animations from './core.animations';
@ -26,20 +24,19 @@ function listenArrayEvents(array, listener) {
}
});
arrayEvents.forEach(function(key) {
var method = '_onData' + key.charAt(0).toUpperCase() + key.slice(1);
var base = array[key];
arrayEvents.forEach((key) => {
const method = '_onData' + key.charAt(0).toUpperCase() + key.slice(1);
const base = array[key];
Object.defineProperty(array, key, {
configurable: true,
enumerable: false,
value: function() {
var args = Array.prototype.slice.call(arguments);
var res = base.apply(this, args);
value(...args) {
const res = base.apply(this, args);
array._chartjs.listeners.forEach(function(object) {
array._chartjs.listeners.forEach((object) => {
if (typeof object[method] === 'function') {
object[method].apply(object, args);
object[method](...args);
}
});
@ -50,10 +47,10 @@ function listenArrayEvents(array, listener) {
}
function scaleClip(scale, allowedOverflow) {
var opts = scale && scale.options || {};
var reverse = opts.reverse;
var min = opts.min === undefined ? allowedOverflow : 0;
var max = opts.max === undefined ? allowedOverflow : 0;
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
@ -64,8 +61,8 @@ function defaultClip(xScale, yScale, allowedOverflow) {
if (allowedOverflow === false) {
return false;
}
var x = scaleClip(xScale, allowedOverflow);
var y = scaleClip(yScale, allowedOverflow);
const x = scaleClip(xScale, allowedOverflow);
const y = scaleClip(yScale, allowedOverflow);
return {
top: y.end,
@ -76,7 +73,7 @@ function defaultClip(xScale, yScale, allowedOverflow) {
}
function toClip(value) {
var t, r, b, l;
let t, r, b, l;
if (helpers.isObject(value)) {
t = value.top;
@ -100,13 +97,13 @@ function toClip(value) {
* the _chartjs stub and overridden methods) if array doesn't have any more listeners.
*/
function unlistenArrayEvents(array, listener) {
var stub = array._chartjs;
const stub = array._chartjs;
if (!stub) {
return;
}
var listeners = stub.listeners;
var index = listeners.indexOf(listener);
const listeners = stub.listeners;
const index = listeners.indexOf(listener);
if (index !== -1) {
listeners.splice(index, 1);
}
@ -115,7 +112,7 @@ function unlistenArrayEvents(array, listener) {
return;
}
arrayEvents.forEach(function(key) {
arrayEvents.forEach((key) => {
delete array[key];
});
@ -123,9 +120,9 @@ function unlistenArrayEvents(array, listener) {
}
function getSortedDatasetIndices(chart, filterVisible) {
var keys = [];
var metasets = chart._getSortedDatasetMetas(filterVisible);
var i, ilen;
const keys = [];
const metasets = chart._getSortedDatasetMetas(filterVisible);
let i, ilen;
for (i = 0, ilen = metasets.length; i < ilen; ++i) {
keys.push(metasets[i].index);
@ -134,8 +131,8 @@ function getSortedDatasetIndices(chart, filterVisible) {
}
function applyStack(stack, value, dsIndex, allOther) {
var keys = stack.keys;
var i, ilen, datasetIndex, otherValue;
const keys = stack.keys;
let i, ilen, datasetIndex, otherValue;
for (i = 0, ilen = keys.length; i < ilen; ++i) {
datasetIndex = +keys[i];
@ -168,7 +165,7 @@ function convertObjectDataToArray(data) {
}
function isStacked(scale, meta) {
var stacked = scale && scale.options.stacked;
const stacked = scale && scale.options.stacked;
return stacked || (stacked === undefined && meta.stack !== undefined);
}
@ -177,7 +174,7 @@ function getStackKey(indexScale, valueScale, meta) {
}
function getUserBounds(scale) {
var {min, max, minDefined, maxDefined} = scale._getUserBounds();
const {min, max, minDefined, maxDefined} = scale._getUserBounds();
return {
min: minDefined ? min : Number.NEGATIVE_INFINITY,
max: maxDefined ? max : Number.POSITIVE_INFINITY
@ -210,9 +207,7 @@ function updateStacks(controller, parsed) {
function getFirstScaleId(chart, axis) {
const scales = chart.scales;
return Object.keys(scales).filter(key => {
return scales[key].axis === axis;
}).shift();
return Object.keys(scales).filter(key => scales[key].axis === axis).shift();
}
class DatasetController {
@ -388,13 +383,13 @@ class DatasetController {
addElements() {
const me = this;
const meta = me._cachedMeta;
let i, ilen, data;
me._dataCheck();
data = me._data;
const data = me._data;
const metaData = meta.data = new Array(data.length);
for (i = 0, ilen = data.length; i < ilen; ++i) {
for (let i = 0, ilen = data.length; i < ilen; ++i) {
metaData[i] = new me.dataElementType();
}
@ -419,7 +414,7 @@ class DatasetController {
if (meta.stack !== dataset.stack) {
stackChanged = true;
// remove values from old stack
meta._parsed.forEach(function(parsed) {
meta._parsed.forEach((parsed) => {
delete parsed._stacks[meta.vScale.id][meta.index];
});
meta.stack = dataset.stack;
@ -445,7 +440,7 @@ class DatasetController {
me.chart.options[me._type].datasets,
me.getDataset(),
], {
merger: function(key, target, source) {
merger(key, target, source) {
if (key !== 'data') {
helpers._merger(key, target, source);
}
@ -620,7 +615,7 @@ class DatasetController {
const stack = canStack && meta._stacked && {keys: getSortedDatasetIndices(this.chart, true), values: null};
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
let {min: otherMin, max: otherMax} = getUserBounds(otherScale);
const {min: otherMin, max: otherMax} = getUserBounds(otherScale);
let i, item, value, parsed, otherValue;
function _compute() {
@ -778,9 +773,7 @@ class DatasetController {
const me = this;
const getHoverColor = helpers.getHoverColor;
const normalOptions = me.getStyle(index);
const missingColors = Object.keys(normalOptions).filter(key => {
return key.indexOf('Color') !== -1 && !(key in options);
});
const missingColors = Object.keys(normalOptions).filter(key => key.indexOf('Color') !== -1 && !(key in options));
let i = missingColors.length - 1;
let color;
for (; i >= 0; i--) {

View File

@ -1,5 +1,3 @@
'use strict';
import {merge} from '../helpers/helpers.core';
class Defaults {

View File

@ -1,5 +1,3 @@
'use strict';
import {extend, inherits} from '../helpers/helpers.core';
import {isNumber} from '../helpers/helpers.math';

View File

@ -1,5 +1,3 @@
'use strict';
import helpers from '../helpers/index';
import {_isPointInArea} from '../helpers/helpers.canvas';
import {_lookupByKey, _rlookupByKey} from '../helpers/helpers.collection';
@ -92,7 +90,7 @@ function optimizedEvaluateItems(chart, axis, position, handler, intersect) {
const value = position[axis];
for (let i = 0, ilen = metasets.length; i < ilen; ++i) {
const {index, data} = metasets[i];
let {lo, hi} = binarySearch(metasets[i], axis, value, intersect);
const {lo, hi} = binarySearch(metasets[i], axis, value, intersect);
for (let j = lo; j <= hi; ++j) {
const element = data[j];
if (!element.skip) {
@ -196,7 +194,7 @@ export default {
* @param {IInteractionOptions} options - options to use during interaction
* @return {Object[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
index: function(chart, e, options) {
index(chart, e, options) {
const position = getRelativePosition(e, chart);
// Default axis for index mode is 'x' to match old behaviour
const axis = options.axis || 'x';
@ -207,7 +205,7 @@ export default {
return [];
}
chart._getSortedVisibleDatasetMetas().forEach(function(meta) {
chart._getSortedVisibleDatasetMetas().forEach((meta) => {
const index = items[0].index;
const element = meta.data[index];
@ -229,7 +227,7 @@ export default {
* @param {IInteractionOptions} options - options to use during interaction
* @return {Object[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
dataset: function(chart, e, options) {
dataset(chart, e, options) {
const position = getRelativePosition(e, chart);
const axis = options.axis || 'xy';
let items = options.intersect ? getIntersectItems(chart, position, axis) : getNearestItems(chart, position, axis);
@ -255,7 +253,7 @@ export default {
* @param {IInteractionOptions} options - options to use
* @return {Object[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
point: function(chart, e, options) {
point(chart, e, options) {
const position = getRelativePosition(e, chart);
const axis = options.axis || 'xy';
return getIntersectItems(chart, position, axis);
@ -269,7 +267,7 @@ export default {
* @param {IInteractionOptions} options - options to use
* @return {Object[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
nearest: function(chart, e, options) {
nearest(chart, e, options) {
const position = getRelativePosition(e, chart);
const axis = options.axis || 'xy';
return getNearestItems(chart, position, axis, options.intersect);
@ -283,12 +281,12 @@ export default {
* @param {IInteractionOptions} options - options to use
* @return {Object[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
x: function(chart, e, options) {
x(chart, e, options) {
const position = getRelativePosition(e, chart);
const items = [];
let intersectsItem = false;
evaluateAllVisibleItems(chart, function(element, datasetIndex, index) {
evaluateAllVisibleItems(chart, (element, datasetIndex, index) => {
if (element.inXRange(position.x)) {
items.push({element, datasetIndex, index});
}
@ -314,12 +312,12 @@ export default {
* @param {IInteractionOptions} options - options to use
* @return {Object[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
y: function(chart, e, options) {
y(chart, e, options) {
const position = getRelativePosition(e, chart);
const items = [];
let intersectsItem = false;
evaluateAllVisibleItems(chart, function(element, datasetIndex, index) {
evaluateAllVisibleItems(chart, (element, datasetIndex, index) => {
if (element.inYRange(position.y)) {
items.push({element, datasetIndex, index});
}

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from './core.defaults';
import {each, extend} from '../helpers/helpers.core';
import {toPadding} from '../helpers/helpers.options';
@ -19,9 +17,9 @@ function filterDynamicPositionByAxis(array, axis) {
}
function sortByWeight(array, reverse) {
return array.sort(function(a, b) {
var v0 = reverse ? b : a;
var v1 = reverse ? a : b;
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;
@ -29,14 +27,14 @@ function sortByWeight(array, reverse) {
}
function wrapBoxes(boxes) {
var layoutBoxes = [];
var i, ilen, box;
const layoutBoxes = [];
let i, ilen, box;
for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
box = boxes[i];
layoutBoxes.push({
index: i,
box: box,
box,
pos: box.position,
horizontal: box.isHorizontal(),
weight: box.weight
@ -46,7 +44,7 @@ function wrapBoxes(boxes) {
}
function setLayoutDims(layouts, params) {
var i, ilen, layout;
let i, ilen, layout;
for (i = 0, ilen = layouts.length; i < ilen; ++i) {
layout = layouts[i];
// store width used instead of chartArea.w in fitBoxes
@ -81,9 +79,8 @@ function getCombinedMax(maxPadding, chartArea, a, b) {
}
function updateDims(chartArea, params, layout) {
var box = layout.box;
var maxPadding = chartArea.maxPadding;
var newWidth, newHeight;
const box = layout.box;
const maxPadding = chartArea.maxPadding;
if (layout.size) {
// this layout was already counted for, lets first reduce old size
@ -93,15 +90,15 @@ function updateDims(chartArea, params, layout) {
chartArea[layout.pos] += layout.size;
if (box.getPadding) {
var boxPadding = box.getPadding();
const boxPadding = box.getPadding();
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);
}
newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right');
newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom');
const newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right');
const newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom');
if (newWidth !== chartArea.w || newHeight !== chartArea.h) {
chartArea.w = newWidth;
@ -113,10 +110,10 @@ function updateDims(chartArea, params, layout) {
}
function handleMaxPadding(chartArea) {
var maxPadding = chartArea.maxPadding;
const maxPadding = chartArea.maxPadding;
function updatePos(pos) {
var change = Math.max(maxPadding[pos] - chartArea[pos], 0);
const change = Math.max(maxPadding[pos] - chartArea[pos], 0);
chartArea[pos] += change;
return change;
}
@ -127,11 +124,11 @@ function handleMaxPadding(chartArea) {
}
function getMargins(horizontal, chartArea) {
var maxPadding = chartArea.maxPadding;
const maxPadding = chartArea.maxPadding;
function marginForPositions(positions) {
var margin = {left: 0, top: 0, right: 0, bottom: 0};
positions.forEach(function(pos) {
const margin = {left: 0, top: 0, right: 0, bottom: 0};
positions.forEach((pos) => {
margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
});
return margin;
@ -143,8 +140,8 @@ function getMargins(horizontal, chartArea) {
}
function fitBoxes(boxes, chartArea, params) {
var refitBoxes = [];
var i, ilen, layout, box, refit, changed;
const refitBoxes = [];
let i, ilen, layout, box, refit, changed;
for (i = 0, ilen = boxes.length; i < ilen; ++i) {
layout = boxes[i];
@ -172,10 +169,10 @@ function fitBoxes(boxes, chartArea, params) {
}
function placeBoxes(boxes, chartArea, params) {
var userPadding = params.padding;
var x = chartArea.x;
var y = chartArea.y;
var i, ilen, layout, box;
const userPadding = params.padding;
let x = chartArea.x;
let y = chartArea.y;
let i, ilen, layout, box;
for (i = 0, ilen = boxes.length; i < ilen; ++i) {
layout = boxes[i];
@ -241,7 +238,7 @@ export default {
* @param {Chart} chart - the chart to use
* @param {ILayoutItem} item - the item to add to be layed out
*/
addBox: function(chart, item) {
addBox(chart, item) {
if (!chart.boxes) {
chart.boxes = [];
}
@ -254,8 +251,8 @@ export default {
item._layers = item._layers || function() {
return [{
z: 0,
draw: function() {
item.draw.apply(item, arguments);
draw(chartArea) {
item.draw(chartArea);
}
}];
};
@ -268,8 +265,8 @@ export default {
* @param {Chart} chart - the chart to remove the box from
* @param {ILayoutItem} layoutItem - the item to remove from the layout
*/
removeBox: function(chart, layoutItem) {
var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
removeBox(chart, layoutItem) {
const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
if (index !== -1) {
chart.boxes.splice(index, 1);
}
@ -281,11 +278,11 @@ export default {
* @param {ILayoutItem} item - the item to configure with the given options
* @param {object} options - the new item options.
*/
configure: function(chart, item, options) {
var props = ['fullWidth', 'position', 'weight'];
var ilen = props.length;
var i = 0;
var prop;
configure(chart, item, options) {
const props = ['fullWidth', 'position', 'weight'];
const ilen = props.length;
let i = 0;
let prop;
for (; i < ilen; ++i) {
prop = props[i];
@ -302,19 +299,19 @@ export default {
* @param {number} width - the width to fit into
* @param {number} height - the height to fit into
*/
update: function(chart, width, height) {
update(chart, width, height) {
if (!chart) {
return;
}
var layoutOptions = chart.options.layout || {};
var padding = toPadding(layoutOptions.padding);
const layoutOptions = chart.options.layout || {};
const padding = toPadding(layoutOptions.padding);
var availableWidth = width - padding.width;
var availableHeight = height - padding.height;
var boxes = buildLayoutBoxes(chart.boxes);
var verticalBoxes = boxes.vertical;
var horizontalBoxes = boxes.horizontal;
const availableWidth = width - padding.width;
const availableHeight = height - padding.height;
const boxes = buildLayoutBoxes(chart.boxes);
const verticalBoxes = boxes.vertical;
const horizontalBoxes = boxes.horizontal;
// Essentially we now have any number of boxes on each of the 4 sides.
// Our canvas looks like the following.
@ -343,15 +340,15 @@ export default {
// |----------------------------------------------------|
//
var params = Object.freeze({
const params = Object.freeze({
outerWidth: width,
outerHeight: height,
padding: padding,
availableWidth: availableWidth,
padding,
availableWidth,
vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length,
hBoxMaxHeight: availableHeight / 2
});
var chartArea = extend({
const chartArea = extend({
maxPadding: extend({}, padding),
w: availableWidth,
h: availableHeight,
@ -391,8 +388,8 @@ export default {
};
// Finally update boxes in chartArea (radial scale for example)
each(boxes.chartArea, function(layout) {
var box = layout.box;
each(boxes.chartArea, (layout) => {
const box = layout.box;
extend(box, chart.chartArea);
box.update(chartArea.w, chartArea.h);
});

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from './core.defaults';
import {clone} from '../helpers/helpers.core';
@ -38,8 +36,8 @@ class PluginService {
* @param {IPlugin[]|IPlugin} plugins plugin instance(s).
*/
register(plugins) {
var p = this._plugins;
([]).concat(plugins).forEach(function(plugin) {
const p = this._plugins;
([]).concat(plugins).forEach((plugin) => {
if (p.indexOf(plugin) === -1) {
p.push(plugin);
}
@ -53,9 +51,9 @@ class PluginService {
* @param {IPlugin[]|IPlugin} plugins plugin instance(s).
*/
unregister(plugins) {
var p = this._plugins;
([]).concat(plugins).forEach(function(plugin) {
var idx = p.indexOf(plugin);
const p = this._plugins;
([]).concat(plugins).forEach((plugin) => {
const idx = p.indexOf(plugin);
if (idx !== -1) {
p.splice(idx, 1);
}
@ -101,9 +99,9 @@ class PluginService {
* @returns {boolean} false if any of the plugins return false, else returns true.
*/
notify(chart, hook, args) {
var descriptors = this._descriptors(chart);
var ilen = descriptors.length;
var i, descriptor, plugin, params, method;
const descriptors = this._descriptors(chart);
const ilen = descriptors.length;
let i, descriptor, plugin, params, method;
for (i = 0; i < ilen; ++i) {
descriptor = descriptors[i];
@ -128,24 +126,24 @@ class PluginService {
* @private
*/
_descriptors(chart) {
var cache = chart.$plugins || (chart.$plugins = {});
const cache = chart.$plugins || (chart.$plugins = {});
if (cache.id === this._cacheId) {
return cache.descriptors;
}
var plugins = [];
var descriptors = [];
var config = (chart && chart.config) || {};
var options = (config.options && config.options.plugins) || {};
const plugins = [];
const descriptors = [];
const config = (chart && chart.config) || {};
const options = (config.options && config.options.plugins) || {};
this._plugins.concat(config.plugins || []).forEach(function(plugin) {
var idx = plugins.indexOf(plugin);
this._plugins.concat(config.plugins || []).forEach((plugin) => {
const idx = plugins.indexOf(plugin);
if (idx !== -1) {
return;
}
var id = plugin.id;
var opts = options[id];
const id = plugin.id;
let opts = options[id];
if (opts === false) {
return;
}
@ -156,7 +154,7 @@ class PluginService {
plugins.push(plugin);
descriptors.push({
plugin: plugin,
plugin,
options: opts || {}
});
});

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from './core.defaults';
import Element from './core.element';
import {_alignPixel, _measureText} from '../helpers/helpers.canvas';
@ -103,10 +101,10 @@ function getPixelForGridLine(scale, index, offsetGridLines) {
}
function garbageCollect(caches, length) {
each(caches, function(cache) {
var gc = cache.gc;
var gcLen = gc.length / 2;
var i;
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]];
@ -150,7 +148,6 @@ function getEvenSpacing(arr) {
function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
const evenMajorSpacing = getEvenSpacing(majorIndices);
const spacing = ticks.length / ticksLimit;
let factors, factor, i, ilen;
// If the major ticks are evenly spaced apart, place the minor ticks
// so that they divide the major ticks into even chunks
@ -158,9 +155,9 @@ function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
return Math.max(spacing, 1);
}
factors = _factorize(evenMajorSpacing);
for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
factor = factors[i];
const factors = _factorize(evenMajorSpacing);
for (let i = 0, ilen = factors.length - 1; i < ilen; i++) {
const factor = factors[i];
if (factor > spacing) {
return factor;
}
@ -224,6 +221,7 @@ function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
class Scale extends Element {
// eslint-disable-next-line max-statements
constructor(cfg) {
super();
@ -351,15 +349,16 @@ class Scale extends Element {
*/
_getMinMax(canStack) {
const me = this;
// eslint-disable-next-line prefer-const
let {min, max, minDefined, maxDefined} = me._getUserBounds();
let i, ilen, metas, minmax;
let minmax;
if (minDefined && maxDefined) {
return {min, max};
}
metas = me._getMatchingVisibleMetas();
for (i = 0, ilen = metas.length; i < ilen; ++i) {
const metas = me._getMatchingVisibleMetas();
for (let i = 0, ilen = metas.length; i < ilen; ++i) {
minmax = metas[i].controller._getMinMax(me, canStack);
if (!minDefined) {
min = Math.min(min, minmax.min);
@ -430,7 +429,6 @@ class Scale extends Element {
const me = this;
const tickOpts = me.options.ticks;
const sampleSize = tickOpts.sampleSize;
let samplingEnabled;
// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
me.beforeUpdate();
@ -470,7 +468,7 @@ class Scale extends Element {
// Compute tick rotation and fit using a sampled subset of labels
// We generally don't need to compute the size of every single label for determining scale size
samplingEnabled = sampleSize < me.ticks.length;
const samplingEnabled = sampleSize < me.ticks.length;
me._convertTicksToLabels(samplingEnabled ? sample(me.ticks, sampleSize) : me.ticks);
// _configure is called twice, once here, once from core.controller.updateLayout.
@ -615,20 +613,20 @@ class Scale extends Element {
const minRotation = tickOpts.minRotation || 0;
const maxRotation = tickOpts.maxRotation;
let labelRotation = minRotation;
let labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal;
let tickWidth, maxHeight, maxLabelDiagonal;
if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
me.labelRotation = minRotation;
return;
}
labelSizes = me._getLabelSizes();
maxLabelWidth = labelSizes.widest.width;
maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;
const labelSizes = me._getLabelSizes();
const maxLabelWidth = labelSizes.widest.width;
const maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;
// Estimate the width of each grid based on the canvas width, the maximum
// label width and the number of tick intervals
maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);
const maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);
tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
// Allow 3 pixels x2 padding either side for label readability
@ -734,7 +732,7 @@ class Scale extends Element {
} else {
// A vertical axis is more constrained by the width. Labels are the
// dominant factor here, so get that length first and account for padding
var labelWidth = tickOpts.mirror ? 0 :
const labelWidth = tickOpts.mirror ? 0 :
// use lineSpace for consistency with horizontal axis
// tickPadding is not implemented for horizontal
widestLabelSize.width + tickPadding + lineSpace;
@ -838,7 +836,7 @@ class Scale extends Element {
ticks = sample(ticks, sampleSize);
}
const length = ticks.length;
let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest;
let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;
for (i = 0; i < length; ++i) {
label = ticks[i].label;
@ -868,8 +866,8 @@ class Scale extends Element {
}
garbageCollect(caches, length);
widest = widths.indexOf(Math.max.apply(null, widths));
highest = heights.indexOf(Math.max.apply(null, heights));
const widest = widths.indexOf(Math.max.apply(null, widths));
const highest = heights.indexOf(Math.max.apply(null, heights));
function valueAt(idx) {
return {
@ -1162,18 +1160,18 @@ class Scale extends Element {
}
items.push({
tx1: tx1,
ty1: ty1,
tx2: tx2,
ty2: ty2,
x1: x1,
y1: y1,
x2: x2,
y2: y2,
tx1,
ty1,
tx2,
ty2,
x1,
y1,
x2,
y2,
width: lineWidth,
color: lineColor,
borderDash: borderDash,
borderDashOffset: borderDashOffset,
borderDash,
borderDashOffset,
});
}
@ -1256,13 +1254,13 @@ class Scale extends Element {
}
items.push({
x: x,
y: y,
rotation: rotation,
label: label,
font: font,
textOffset: textOffset,
textAlign: textAlign
x,
y,
rotation,
label,
font,
textOffset,
textAlign
});
}
@ -1406,7 +1404,7 @@ class Scale extends Element {
/**
* @private
*/
_drawTitle() {
_drawTitle(chartArea) { // eslint-disable-line no-unused-vars
const me = this;
const ctx = me.ctx;
const options = me.options;
@ -1501,22 +1499,22 @@ class Scale extends Element {
// backward compatibility: draw has been overridden by custom scale
return [{
z: tz,
draw: function() {
me.draw.apply(me, arguments);
draw(chartArea) {
me.draw(chartArea);
}
}];
}
return [{
z: gz,
draw: function() {
me._drawGrid.apply(me, arguments);
me._drawTitle.apply(me, arguments);
draw(chartArea) {
me._drawGrid(chartArea);
me._drawTitle();
}
}, {
z: tz,
draw: function() {
me._drawLabels.apply(me, arguments);
draw(chartArea) {
me._drawLabels(chartArea);
}
}];
}
@ -1555,7 +1553,7 @@ class Scale extends Element {
chart: me.chart,
scale: me,
tick: me.ticks[index],
index: index
index
};
return extend(_parseFont({
fontFamily: resolve([options.fontFamily], context),

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from './core.defaults';
import {clone, each, extend, merge} from '../helpers/helpers.core';
import layouts from './core.layouts';
@ -13,26 +11,26 @@ export default {
// Scale config defaults
defaults: {},
registerScaleType: function(type, scaleConstructor, scaleDefaults) {
registerScaleType(type, scaleConstructor, scaleDefaults) {
this.constructors[type] = scaleConstructor;
this.defaults[type] = clone(scaleDefaults);
},
getScaleConstructor: function(type) {
getScaleConstructor(type) {
return Object.prototype.hasOwnProperty.call(this.constructors, type) ? this.constructors[type] : undefined;
},
getScaleDefaults: function(type) {
getScaleDefaults(type) {
// Return the scale defaults merged with the global settings so that we always use the latest ones
return Object.prototype.hasOwnProperty.call(this.defaults, type) ? merge({}, [defaults.scale, this.defaults[type]]) : {};
},
updateScaleDefaults: function(type, additions) {
var me = this;
updateScaleDefaults(type, additions) {
const me = this;
if (Object.prototype.hasOwnProperty.call(me.defaults, type)) {
me.defaults[type] = extend(me.defaults[type], additions);
}
},
addScalesToLayout: function(chart) {
addScalesToLayout(chart) {
// Adds each scale to the chart.boxes array to be sized accordingly
each(chart.scales, function(scale) {
each(chart.scales, (scale) => {
// Set ILayoutItem parameters for backwards compatibility
scale.fullWidth = scale.options.fullWidth;
scale.position = scale.options.position;

View File

@ -1,5 +1,3 @@
'use strict';
import {isArray} from '../helpers/helpers.core';
import {log10} from '../helpers/helpers.math';
@ -19,7 +17,7 @@ export default {
* @param value the value to display
* @return {string|string[]} the label to display
*/
values: function(value) {
values(value) {
return isArray(value) ? value : '' + value;
},
@ -31,7 +29,7 @@ export default {
* @param ticks {object[]} the list of ticks being converted
* @return {string} string representation of the tickValue parameter
*/
numeric: function(tickValue, index, ticks) {
numeric(tickValue, index, ticks) {
if (tickValue === 0) {
return '0'; // never show decimal places for 0
}

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from '../core/core.defaults';
import Element from '../core/core.element';
import {extend} from '../helpers/helpers.core';
@ -150,7 +148,7 @@ class Arc extends Element {
y: me.y,
innerRadius: me.innerRadius,
outerRadius: Math.max(me.outerRadius - pixelMargin, 0),
pixelMargin: pixelMargin,
pixelMargin,
startAngle: me.startAngle,
endAngle: me.endAngle,
fullCircles: Math.floor(me.circumference / TAU)

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from '../core/core.defaults';
import Element from '../core/core.element';
import {extend} from '../helpers/helpers.core';
@ -72,8 +70,9 @@ function pathSegment(ctx, line, segment, params) {
const {points, options} = line;
const lineMethod = getLineMethod(options);
const count = points.length;
// eslint-disable-next-line prefer-const
let {move = true, reverse} = params || {};
let ilen = end < start ? count + end - start : end - start;
const ilen = end < start ? count + end - start : end - start;
let i, point, prev;
for (i = 0; i <= ilen; ++i) {
@ -117,8 +116,8 @@ function fastPathSegment(ctx, line, segment, params) {
const points = line.points;
const count = points.length;
const {start, end} = segment;
let {move = true, reverse} = params || {};
let ilen = end < start ? count + end - start : end - start;
const {move = true, reverse} = params || {};
const ilen = end < start ? count + end - start : end - start;
let avgX = 0;
let countX = 0;
let i, point, prevX, minY, maxY, lastY;
@ -291,7 +290,7 @@ class Line extends Element {
continue;
}
const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));
let interpolated = _interpolate(p1, p2, t, options.steppedLine);
const interpolated = _interpolate(p1, p2, t, options.steppedLine);
interpolated[property] = point[property];
result.push(interpolated);
}

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from '../core/core.defaults';
import Element from '../core/core.element';
import {_isPointInArea, drawPoint} from '../helpers/helpers.canvas';

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from '../core/core.defaults';
import Element from '../core/core.element';
import {extend, isObject} from '../helpers/helpers.core';
@ -22,7 +20,7 @@ defaults.set('elements', {
* @private
*/
function getBarBounds(bar) {
var x1, x2, y1, y2, half;
let x1, x2, y1, y2, half;
if (bar.horizontal) {
half = bar.height / 2;
@ -51,8 +49,8 @@ function swap(orig, v1, v2) {
}
function parseBorderSkipped(bar) {
var edge = bar.options.borderSkipped;
var res = {};
let edge = bar.options.borderSkipped;
const res = {};
if (!edge) {
return res;
@ -75,9 +73,9 @@ function skipOrLimit(skip, value, min, max) {
}
function parseBorderWidth(bar, maxW, maxH) {
var value = bar.options.borderWidth;
var skip = parseBorderSkipped(bar);
var t, r, b, l;
const value = bar.options.borderWidth;
const skip = parseBorderSkipped(bar);
let t, r, b, l;
if (isObject(value)) {
t = +value.top || 0;
@ -97,10 +95,10 @@ function parseBorderWidth(bar, maxW, maxH) {
}
function boundingRects(bar) {
var bounds = getBarBounds(bar);
var width = bounds.right - bounds.left;
var height = bounds.bottom - bounds.top;
var border = parseBorderWidth(bar, width / 2, height / 2);
const bounds = getBarBounds(bar);
const width = bounds.right - bounds.left;
const height = bounds.bottom - bounds.top;
const border = parseBorderWidth(bar, width / 2, height / 2);
return {
outer: {
@ -119,9 +117,9 @@ function boundingRects(bar) {
}
function inRange(bar, x, y) {
var skipX = x === null;
var skipY = y === null;
var bounds = !bar || (skipX && skipY) ? false : getBarBounds(bar);
const skipX = x === null;
const skipY = y === null;
const bounds = !bar || (skipX && skipY) ? false : getBarBounds(bar);
return bounds
&& (skipX || x >= bounds.left && x <= bounds.right)

View File

@ -1,5 +1,3 @@
'use strict';
import Arc from './element.arc';
import Line from './element.line';
import Point from './element.point';

View File

@ -1,5 +1,3 @@
'use strict';
import {isArray} from './helpers.core';
/**
@ -37,8 +35,8 @@ export function _measureText(ctx, data, gc, longest, string) {
*/
export function _longestText(ctx, font, arrayOfThings, cache) {
cache = cache || {};
var data = cache.data = cache.data || {};
var gc = cache.garbageCollect = cache.garbageCollect || [];
let data = cache.data = cache.data || {};
let gc = cache.garbageCollect = cache.garbageCollect || [];
if (cache.font !== font) {
data = cache.data = {};
@ -47,9 +45,9 @@ export function _longestText(ctx, font, arrayOfThings, cache) {
}
ctx.font = font;
var longest = 0;
var ilen = arrayOfThings.length;
var i, j, jlen, thing, nestedThing;
let longest = 0;
const ilen = arrayOfThings.length;
let i, j, jlen, thing, nestedThing;
for (i = 0; i < ilen; i++) {
thing = arrayOfThings[i];
@ -69,7 +67,7 @@ export function _longestText(ctx, font, arrayOfThings, cache) {
}
}
var gcLen = gc.length / 2;
const gcLen = gc.length / 2;
if (gcLen > arrayOfThings.length) {
for (i = 0; i < gcLen; i++) {
delete data[gc[i]];
@ -102,11 +100,11 @@ export function clear(chart) {
}
export function drawPoint(ctx, options, x, y) {
var type, xOffset, yOffset, size, cornerRadius;
var style = options.pointStyle;
var rotation = options.rotation;
var radius = options.radius;
var rad = (rotation || 0) * RAD_PER_DEG;
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();

View File

@ -1,5 +1,3 @@
'use strict';
/**
* Binary search
* @param {array} table - the table search. must be sorted!

View File

@ -1,5 +1,3 @@
'use strict';
/**
* @namespace Chart.helpers
*/
@ -14,7 +12,7 @@ export function noop() {}
* @function
*/
export const uid = (function() {
var id = 0;
let id = 0;
return function() {
return id++;
};
@ -40,7 +38,7 @@ export function isArray(value) {
if (Array.isArray && Array.isArray(value)) {
return true;
}
var type = Object.prototype.toString.call(value);
const type = Object.prototype.toString.call(value);
if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
return true;
}
@ -62,9 +60,7 @@ export function isObject(value) {
* @param {*} value - The value to test.
* @returns {boolean}
*/
const isNumberFinite = (value) => {
return (typeof value === 'number' || value instanceof Number) && isFinite(+value);
};
const isNumberFinite = (value) => (typeof value === 'number' || value instanceof Number) && isFinite(+value);
export {
isNumberFinite as isFinite,
};
@ -114,7 +110,7 @@ export function callback(fn, args, thisArg) {
* @param {boolean} [reverse] - If true, iterates backward on the loopable.
*/
export function each(loopable, fn, thisArg, reverse) {
var i, len, keys;
let i, len, keys;
if (isArray(loopable)) {
len = loopable.length;
if (reverse) {
@ -143,7 +139,7 @@ export function each(loopable, fn, thisArg, reverse) {
* @returns {boolean}
*/
export function arrayEquals(a0, a1) {
var i, ilen, v0, v1;
let i, ilen, v0, v1;
if (!a0 || !a1 || a0.length !== a1.length) {
return false;
@ -203,10 +199,10 @@ export function clone(source) {
}
if (isObject(source)) {
var target = {};
var keys = Object.keys(source);
var klen = keys.length;
var k = 0;
const target = {};
const keys = Object.keys(source);
const klen = keys.length;
let k = 0;
for (; k < klen; ++k) {
target[keys[k]] = clone(source[keys[k]]);
@ -224,8 +220,8 @@ export function clone(source) {
* @private
*/
export function _merger(key, target, source, options) {
var tval = target[key];
var sval = source[key];
const tval = target[key];
const sval = source[key];
if (isObject(tval) && isObject(sval)) {
// eslint-disable-next-line no-use-before-define
@ -245,25 +241,24 @@ export function _merger(key, target, source, options) {
* @returns {object} The `target` object.
*/
export function merge(target, source, options) {
var sources = isArray(source) ? source : [source];
var ilen = sources.length;
var merger, i, keys, klen, k;
const sources = isArray(source) ? source : [source];
const ilen = sources.length;
if (!isObject(target)) {
return target;
}
options = options || {};
merger = options.merger || _merger;
const merger = options.merger || _merger;
for (i = 0; i < ilen; ++i) {
for (let i = 0; i < ilen; ++i) {
source = sources[i];
if (!isObject(source)) {
continue;
}
keys = Object.keys(source);
for (k = 0, klen = keys.length; k < klen; ++k) {
const keys = Object.keys(source);
for (let k = 0, klen = keys.length; k < klen; ++k) {
merger(keys[k], target, source, options);
}
}
@ -288,8 +283,8 @@ export function mergeIf(target, source) {
* @private
*/
export function _mergerIf(key, target, source) {
var tval = target[key];
var sval = source[key];
const tval = target[key];
const sval = source[key];
if (isObject(tval) && isObject(sval)) {
mergeIf(tval, sval);
@ -305,9 +300,9 @@ export function _mergerIf(key, target, source) {
* @param {object} argN - Additional objects containing properties to merge in target.
* @returns {object} The `target` object.
*/
export const extend = Object.assign || function(target) {
return merge(target, [].slice.call(arguments, 1), {
merger: function(key, dst, src) {
export const extend = Object.assign || function(target, ...args) {
return merge(target, args, {
merger(key, dst, src) {
dst[key] = src[key];
}
});
@ -317,12 +312,14 @@ export const extend = Object.assign || function(target) {
* Basic javascript inheritance based on the model created in Backbone.js
*/
export function inherits(extensions) {
var me = this;
var ChartElement = (extensions && Object.prototype.hasOwnProperty.call(extensions, 'constructor')) ? extensions.constructor : function() {
// eslint-disable-next-line no-invalid-this
const me = this;
const ChartElement = (extensions && Object.prototype.hasOwnProperty.call(extensions, 'constructor')) ? extensions.constructor : function() {
// eslint-disable-next-line prefer-rest-params
return me.apply(this, arguments);
};
var Surrogate = function() {
const Surrogate = function() {
this.constructor = ChartElement;
};

View File

@ -9,22 +9,22 @@ export function splineCurve(firstPoint, middlePoint, afterPoint, t) {
// This function must also respect "skipped" points
var previous = firstPoint.skip ? middlePoint : firstPoint;
var current = middlePoint;
var next = afterPoint.skip ? middlePoint : afterPoint;
const previous = firstPoint.skip ? middlePoint : firstPoint;
const current = middlePoint;
const next = afterPoint.skip ? middlePoint : afterPoint;
var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
const d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
const d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
var s01 = d01 / (d01 + d12);
var s12 = d12 / (d01 + d12);
let s01 = d01 / (d01 + d12);
let s12 = d12 / (d01 + d12);
// If all points are the same, s01 & s02 will be inf
s01 = isNaN(s01) ? 0 : s01;
s12 = isNaN(s12) ? 0 : s12;
var fa = t * s01; // scaling factor for triangle Ta
var fb = t * s12;
const fa = t * s01; // scaling factor for triangle Ta
const fb = t * s12;
return {
previous: {
@ -44,17 +44,15 @@ export function splineCurveMonotone(points) {
// between the dataset discrete points due to the interpolation.
// See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
var pointsWithTangents = (points || []).map(function(point) {
return {
const pointsWithTangents = (points || []).map((point) => ({
model: point,
deltaK: 0,
mK: 0
};
});
}));
// Calculate slopes (deltaK) and initialize tangents (mK)
var pointsLen = pointsWithTangents.length;
var i, pointBefore, pointCurrent, pointAfter;
const pointsLen = pointsWithTangents.length;
let i, pointBefore, pointCurrent, pointAfter;
for (i = 0; i < pointsLen; ++i) {
pointCurrent = pointsWithTangents[i];
if (pointCurrent.model.skip) {
@ -64,7 +62,7 @@ export function splineCurveMonotone(points) {
pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
if (pointAfter && !pointAfter.model.skip) {
var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
const slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
// In the case of two points that appear at the same x pixel, slopeDeltaX is 0
pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
@ -82,7 +80,7 @@ export function splineCurveMonotone(points) {
}
// Adjust tangents to ensure monotonic properties
var alphaK, betaK, tauK, squaredMagnitude;
let alphaK, betaK, tauK, squaredMagnitude;
for (i = 0; i < pointsLen - 1; ++i) {
pointCurrent = pointsWithTangents[i];
pointAfter = pointsWithTangents[i + 1];
@ -108,7 +106,7 @@ export function splineCurveMonotone(points) {
}
// Compute control points
var deltaX;
let deltaX;
for (i = 0; i < pointsLen; ++i) {
pointCurrent = pointsWithTangents[i];
if (pointCurrent.model.skip) {
@ -135,7 +133,7 @@ function capControlPoint(pt, min, max) {
}
function capBezierPoints(points, area) {
var i, ilen, point;
let i, ilen, point;
for (i = 0, ilen = points.length; i < ilen; ++i) {
point = points[i];
if (!_isPointInArea(point, area)) {
@ -156,13 +154,11 @@ function capBezierPoints(points, area) {
* @private
*/
export function _updateBezierControlPoints(points, options, area, loop) {
var i, ilen, point, controlPoints;
let i, ilen, point, controlPoints;
// Only consider points that are drawn in case the spanGaps option is used
if (options.spanGaps) {
points = points.filter(function(pt) {
return !pt.skip;
});
points = points.filter((pt) => !pt.skip);
}
if (options.cubicInterpolationMode === 'monotone') {

View File

@ -10,7 +10,7 @@ function isConstrainedValue(value) {
* @private
*/
function _getParentNode(domNode) {
var parent = domNode.parentNode;
let parent = domNode.parentNode;
if (parent && parent.toString() === '[object ShadowRoot]') {
parent = parent.host;
}
@ -19,7 +19,7 @@ function _getParentNode(domNode) {
// Private helper function to convert max-width/max-height values that may be percentages into a number
function parseMaxStyle(styleValue, node, parentProperty) {
var valueInPixels;
let valueInPixels;
if (typeof styleValue === 'string') {
valueInPixels = parseInt(styleValue, 10);
@ -43,13 +43,13 @@ function parseMaxStyle(styleValue, node, parentProperty) {
* @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
*/
function getConstraintDimension(domNode, maxStyle, percentageProperty) {
var view = document.defaultView;
var parentNode = _getParentNode(domNode);
var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
var hasCNode = isConstrainedValue(constrainedNode);
var hasCContainer = isConstrainedValue(constrainedContainer);
var infinity = Number.POSITIVE_INFINITY;
const view = document.defaultView;
const parentNode = _getParentNode(domNode);
const constrainedNode = view.getComputedStyle(domNode)[maxStyle];
const constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
const hasCNode = isConstrainedValue(constrainedNode);
const hasCContainer = isConstrainedValue(constrainedContainer);
const infinity = Number.POSITIVE_INFINITY;
if (hasCNode || hasCContainer) {
return Math.min(
@ -84,12 +84,12 @@ function _calculatePadding(container, padding, parentDimension) {
}
export function getRelativePosition(evt, chart) {
var mouseX, mouseY;
var e = evt.originalEvent || evt;
var canvasElement = evt.target || evt.srcElement;
var boundingRect = canvasElement.getBoundingClientRect();
let mouseX, mouseY;
const e = evt.originalEvent || evt;
const canvasElement = evt.target || evt.srcElement;
const boundingRect = canvasElement.getBoundingClientRect();
var touches = e.touches;
const touches = e.touches;
if (touches && touches.length > 0) {
mouseX = touches[0].clientX;
mouseY = touches[0].clientY;
@ -102,12 +102,12 @@ export function getRelativePosition(evt, chart) {
// Scale mouse coordinates into canvas coordinates
// by following the pattern laid out by 'jerryj' in the comments of
// https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
var paddingLeft = parseFloat(getStyle(canvasElement, 'padding-left'));
var paddingTop = parseFloat(getStyle(canvasElement, 'padding-top'));
var paddingRight = parseFloat(getStyle(canvasElement, 'padding-right'));
var paddingBottom = parseFloat(getStyle(canvasElement, 'padding-bottom'));
var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
const paddingLeft = parseFloat(getStyle(canvasElement, 'padding-left'));
const paddingTop = parseFloat(getStyle(canvasElement, 'padding-top'));
const paddingRight = parseFloat(getStyle(canvasElement, 'padding-right'));
const paddingBottom = parseFloat(getStyle(canvasElement, 'padding-bottom'));
const width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
const height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
// We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
// the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
@ -121,32 +121,32 @@ export function getRelativePosition(evt, chart) {
}
export function getMaximumWidth(domNode) {
var container = _getParentNode(domNode);
const container = _getParentNode(domNode);
if (!container) {
return domNode.clientWidth;
}
var clientWidth = container.clientWidth;
var paddingLeft = _calculatePadding(container, 'padding-left', clientWidth);
var paddingRight = _calculatePadding(container, 'padding-right', clientWidth);
const clientWidth = container.clientWidth;
const paddingLeft = _calculatePadding(container, 'padding-left', clientWidth);
const paddingRight = _calculatePadding(container, 'padding-right', clientWidth);
var w = clientWidth - paddingLeft - paddingRight;
var cw = getConstraintWidth(domNode);
const w = clientWidth - paddingLeft - paddingRight;
const cw = getConstraintWidth(domNode);
return isNaN(cw) ? w : Math.min(w, cw);
}
export function getMaximumHeight(domNode) {
var container = _getParentNode(domNode);
const container = _getParentNode(domNode);
if (!container) {
return domNode.clientHeight;
}
var clientHeight = container.clientHeight;
var paddingTop = _calculatePadding(container, 'padding-top', clientHeight);
var paddingBottom = _calculatePadding(container, 'padding-bottom', clientHeight);
const clientHeight = container.clientHeight;
const paddingTop = _calculatePadding(container, 'padding-top', clientHeight);
const paddingBottom = _calculatePadding(container, 'padding-bottom', clientHeight);
var h = clientHeight - paddingTop - paddingBottom;
var ch = getConstraintHeight(domNode);
const h = clientHeight - paddingTop - paddingBottom;
const ch = getConstraintHeight(domNode);
return isNaN(ch) ? h : Math.min(h, ch);
}

View File

@ -1,96 +1,94 @@
'use strict';
/**
* Easing functions adapted from Robert Penner's easing equations.
* @namespace Chart.helpers.easing.effects
* @see http://www.robertpenner.com/easing/
*/
export const effects = {
linear: function(t) {
const effects = {
linear(t) {
return t;
},
easeInQuad: function(t) {
easeInQuad(t) {
return t * t;
},
easeOutQuad: function(t) {
easeOutQuad(t) {
return -t * (t - 2);
},
easeInOutQuad: function(t) {
easeInOutQuad(t) {
if ((t /= 0.5) < 1) {
return 0.5 * t * t;
}
return -0.5 * ((--t) * (t - 2) - 1);
},
easeInCubic: function(t) {
easeInCubic(t) {
return t * t * t;
},
easeOutCubic: function(t) {
return (t = t - 1) * t * t + 1;
easeOutCubic(t) {
return (t -= 1) * t * t + 1;
},
easeInOutCubic: function(t) {
easeInOutCubic(t) {
if ((t /= 0.5) < 1) {
return 0.5 * t * t * t;
}
return 0.5 * ((t -= 2) * t * t + 2);
},
easeInQuart: function(t) {
easeInQuart(t) {
return t * t * t * t;
},
easeOutQuart: function(t) {
return -((t = t - 1) * t * t * t - 1);
easeOutQuart(t) {
return -((t -= 1) * t * t * t - 1);
},
easeInOutQuart: function(t) {
easeInOutQuart(t) {
if ((t /= 0.5) < 1) {
return 0.5 * t * t * t * t;
}
return -0.5 * ((t -= 2) * t * t * t - 2);
},
easeInQuint: function(t) {
easeInQuint(t) {
return t * t * t * t * t;
},
easeOutQuint: function(t) {
return (t = t - 1) * t * t * t * t + 1;
easeOutQuint(t) {
return (t -= 1) * t * t * t * t + 1;
},
easeInOutQuint: function(t) {
easeInOutQuint(t) {
if ((t /= 0.5) < 1) {
return 0.5 * t * t * t * t * t;
}
return 0.5 * ((t -= 2) * t * t * t * t + 2);
},
easeInSine: function(t) {
easeInSine(t) {
return -Math.cos(t * (Math.PI / 2)) + 1;
},
easeOutSine: function(t) {
easeOutSine(t) {
return Math.sin(t * (Math.PI / 2));
},
easeInOutSine: function(t) {
easeInOutSine(t) {
return -0.5 * (Math.cos(Math.PI * t) - 1);
},
easeInExpo: function(t) {
easeInExpo(t) {
return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
},
easeOutExpo: function(t) {
easeOutExpo(t) {
return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
},
easeInOutExpo: function(t) {
easeInOutExpo(t) {
if (t === 0) {
return 0;
}
@ -103,28 +101,28 @@ export const effects = {
return 0.5 * (-Math.pow(2, -10 * --t) + 2);
},
easeInCirc: function(t) {
easeInCirc(t) {
if (t >= 1) {
return t;
}
return -(Math.sqrt(1 - t * t) - 1);
},
easeOutCirc: function(t) {
return Math.sqrt(1 - (t = t - 1) * t);
easeOutCirc(t) {
return Math.sqrt(1 - (t -= 1) * t);
},
easeInOutCirc: function(t) {
easeInOutCirc(t) {
if ((t /= 0.5) < 1) {
return -0.5 * (Math.sqrt(1 - t * t) - 1);
}
return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
},
easeInElastic: function(t) {
var s = 1.70158;
var p = 0;
var a = 1;
easeInElastic(t) {
let s = 1.70158;
let p = 0;
let a = 1;
if (t === 0) {
return 0;
}
@ -143,10 +141,10 @@ export const effects = {
return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
},
easeOutElastic: function(t) {
var s = 1.70158;
var p = 0;
var a = 1;
easeOutElastic(t) {
let s = 1.70158;
let p = 0;
let a = 1;
if (t === 0) {
return 0;
}
@ -165,10 +163,10 @@ export const effects = {
return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
},
easeInOutElastic: function(t) {
var s = 1.70158;
var p = 0;
var a = 1;
easeInOutElastic(t) {
let s = 1.70158;
let p = 0;
let a = 1;
if (t === 0) {
return 0;
}
@ -189,29 +187,29 @@ export const effects = {
}
return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
},
easeInBack: function(t) {
var s = 1.70158;
easeInBack(t) {
const s = 1.70158;
return t * t * ((s + 1) * t - s);
},
easeOutBack: function(t) {
var s = 1.70158;
return (t = t - 1) * t * ((s + 1) * t + s) + 1;
easeOutBack(t) {
const s = 1.70158;
return (t -= 1) * t * ((s + 1) * t + s) + 1;
},
easeInOutBack: function(t) {
var s = 1.70158;
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: function(t) {
easeInBounce(t) {
return 1 - effects.easeOutBounce(1 - t);
},
easeOutBounce: function(t) {
easeOutBounce(t) {
if (t < (1 / 2.75)) {
return 7.5625 * t * t;
}
@ -224,10 +222,12 @@ export const effects = {
return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
},
easeInOutBounce: function(t) {
easeInOutBounce(t) {
if (t < 0.5) {
return effects.easeInBounce(t * 2) * 0.5;
}
return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
}
};
export default effects;

View File

@ -1,5 +1,3 @@
'use strict';
/**
* @private
*/

View File

@ -1,5 +1,3 @@
'use strict';
import {isFinite as isFiniteNumber} from './helpers.core';
const PI = Math.PI;
@ -16,9 +14,9 @@ const PITAU = TAU + PI;
* @private
*/
export function _factorize(value) {
var result = [];
var sqrt = Math.sqrt(value);
var i;
const result = [];
const sqrt = Math.sqrt(value);
let i;
for (i = 1; i < sqrt; i++) {
if (value % i === 0) {
@ -30,18 +28,16 @@ export function _factorize(value) {
result.push(sqrt);
}
result.sort(function(a, b) {
return a - b;
}).pop();
result.sort((a, b) => a - b).pop();
return result;
}
export const log10 = Math.log10 || function(x) {
var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
const exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
// Check for whole powers of 10,
// which due to floating point rounding error should be corrected.
var powerOf10 = Math.round(exponent);
var isPowerOf10 = x === Math.pow(10, powerOf10);
const powerOf10 = Math.round(exponent);
const isPowerOf10 = x === Math.pow(10, powerOf10);
return isPowerOf10 ? powerOf10 : exponent;
};
@ -55,7 +51,7 @@ export function almostEquals(x, y, epsilon) {
}
export function almostWhole(x, epsilon) {
var rounded = Math.round(x);
const rounded = Math.round(x);
return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
}
@ -63,7 +59,7 @@ export function almostWhole(x, epsilon) {
* @private
*/
export function _setMinAndMaxByKey(array, target, property) {
var i, ilen, value;
let i, ilen, value;
for (i = 0, ilen = array.length; i < ilen; i++) {
value = array[i][property];
@ -105,8 +101,8 @@ export function _decimalPlaces(x) {
if (!isFiniteNumber(x)) {
return;
}
var e = 1;
var p = 0;
let e = 1;
let p = 0;
while (Math.round(x * e) / e !== x) {
e *= 10;
p++;
@ -116,18 +112,18 @@ export function _decimalPlaces(x) {
// Gets the angle from vertical upright to the point about a centre.
export function getAngleFromPoint(centrePoint, anglePoint) {
var distanceFromXCenter = anglePoint.x - centrePoint.x;
var distanceFromYCenter = anglePoint.y - centrePoint.y;
var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
const distanceFromXCenter = anglePoint.x - centrePoint.x;
const distanceFromYCenter = anglePoint.y - centrePoint.y;
const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
if (angle < (-0.5 * PI)) {
angle += TAU; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
}
return {
angle: angle,
angle,
distance: radialDistanceFromCenter
};
}

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from '../core/core.defaults';
import {isNullOrUndef, isArray, isObject, valueOrDefault} from './helpers.core';
@ -33,7 +31,7 @@ function toFontString(font) {
* @since 2.7.0
*/
export function toLineHeight(value, size) {
var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
const matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
if (!matches || matches[1] === 'normal') {
return size * 1.2;
}
@ -61,7 +59,7 @@ export function toLineHeight(value, size) {
* @since 2.7.0
*/
export function toPadding(value) {
var t, r, b, l;
let t, r, b, l;
if (isObject(value)) {
t = +value.top || 0;
@ -99,7 +97,7 @@ export function _parseFont(options) {
const font = {
family: valueOrDefault(options.fontFamily, defaults.fontFamily),
lineHeight: toLineHeight(valueOrDefault(options.lineHeight, defaults.lineHeight), size),
size: size,
size,
style: valueOrDefault(options.fontStyle, defaults.fontStyle),
weight: null,
string: ''
@ -121,8 +119,8 @@ export function _parseFont(options) {
* @since 2.7.0
*/
export function resolve(inputs, context, index, info) {
var cacheable = true;
var i, ilen, value;
let cacheable = true;
let i, ilen, value;
for (i = 0, ilen = inputs.length; i < ilen; ++i) {
value = inputs[i];

View File

@ -1,42 +1,40 @@
'use strict';
var getRtlAdapter = function(rectX, width) {
const getRtlAdapter = function(rectX, width) {
return {
x: function(x) {
x(x) {
return rectX + rectX + width - x;
},
setWidth: function(w) {
setWidth(w) {
width = w;
},
textAlign: function(align) {
textAlign(align) {
if (align === 'center') {
return align;
}
return align === 'right' ? 'left' : 'right';
},
xPlus: function(x, value) {
xPlus(x, value) {
return x - value;
},
leftForLtr: function(x, itemWidth) {
leftForLtr(x, itemWidth) {
return x - itemWidth;
},
};
};
var getLtrAdapter = function() {
const getLtrAdapter = function() {
return {
x: function(x) {
x(x) {
return x;
},
setWidth: function(w) { // eslint-disable-line no-unused-vars
setWidth(w) { // eslint-disable-line no-unused-vars
},
textAlign: function(align) {
textAlign(align) {
return align;
},
xPlus: function(x, value) {
xPlus(x, value) {
return x + value;
},
leftForLtr: function(x, _itemWidth) { // eslint-disable-line no-unused-vars
leftForLtr(x, _itemWidth) { // eslint-disable-line no-unused-vars
return x;
},
};
@ -47,7 +45,7 @@ const getAdapter = function(rtl, rectX, width) {
};
const overrideTextDirection = function(ctx, direction) {
var style, original;
let style, original;
if (direction === 'ltr' || direction === 'rtl') {
style = ctx.canvas.style;
original = [

View File

@ -1,5 +1,3 @@
'use strict';
import {_angleBetween, _angleDiff, _normalizeAngle} from './helpers.math';
/**
@ -34,6 +32,7 @@ function getSegment(segment, points, bounds) {
const {property, start: startBound, end: endBound} = bounds;
const {between, normalize} = propertyFn(property);
const count = points.length;
// eslint-disable-next-line prefer-const
let {start, end, loop} = segment;
let i, ilen;
@ -124,8 +123,8 @@ export function _boundSegment(segment, points, bounds) {
export function _boundSegments(line, bounds) {
const result = [];
for (let segment of line.segments) {
let sub = _boundSegment(segment, line.points, bounds);
for (const segment of line.segments) {
const sub = _boundSegment(segment, line.points, bounds);
if (sub.length) {
result.push(...sub);
}

View File

@ -1,4 +1,4 @@
'use strict';
/* eslint-disable import/no-namespace */
import color from '@kurkle/color';
@ -6,7 +6,7 @@ import * as coreHelpers from './helpers.core';
import * as canvas from './helpers.canvas';
import * as curve from './helpers.curve';
import * as dom from './helpers.dom';
import * as easing from './helpers.easing';
import effects from './helpers.easing';
import * as options from './helpers.options';
import * as math from './helpers.math';
import * as rtl from './helpers.rtl';
@ -27,7 +27,7 @@ export default {
canvas,
curve,
dom,
easing,
easing: {effects},
options,
math,
rtl,
@ -42,11 +42,11 @@ export default {
return window.requestAnimationFrame;
}()),
// -- Canvas methods
fontString: function(pixelSize, fontStyle, fontFamily) {
fontString(pixelSize, fontStyle, fontFamily) {
return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
},
color: colorHelper,
getHoverColor: function(colorValue) {
getHoverColor(colorValue) {
return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
colorValue :
colorHelper(colorValue).saturate(0.5).darken(0.1).hexString();

View File

@ -43,7 +43,7 @@ Chart.Ticks = Ticks;
// Register built-in scales
import scales from './scales/index';
Object.keys(scales).forEach(function(type) {
Object.keys(scales).forEach((type) => {
const scale = scales[type];
Chart.scaleService.registerScaleType(type, scale, scale._defaults);
});
@ -53,7 +53,7 @@ import './adapters/index';
// Loading built-in plugins
import plugins from './plugins/index';
for (var k in plugins) {
for (const k in plugins) {
if (Object.prototype.hasOwnProperty.call(plugins, k)) {
Chart.plugins.register(plugins[k]);
}

View File

@ -1,4 +1,3 @@
'use strict';
/**
* @typedef { import("../core/core.controller").default } Chart
@ -8,11 +7,6 @@
* Abstract class that allows abstracting platform dependencies away from the chart.
*/
export default class BasePlatform {
/**
* @constructor
*/
constructor() {}
/**
* Called at chart construction time, returns a context2d instance implementing
* the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.

View File

@ -3,8 +3,6 @@
* @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
*/
'use strict';
import BasePlatform from './platform.base';
/**

View File

@ -2,8 +2,6 @@
* Chart.Platform implementation for targeting a web browser
*/
'use strict';
import helpers from '../helpers/index';
import BasePlatform from './platform.base';
import platform from './platform';
@ -115,7 +113,7 @@ const supportsEventListenerOptions = (function() {
try {
const options = Object.defineProperty({}, 'passive', {
// eslint-disable-next-line getter-return
get: function() {
get() {
supports = true;
}
});
@ -140,8 +138,8 @@ function removeListener(node, type, listener) {
function createEvent(type, chart, x, y, nativeEvent) {
return {
type: type,
chart: chart,
type,
chart,
native: nativeEvent || null,
x: x !== undefined ? x : null,
y: y !== undefined ? y : null,
@ -158,13 +156,12 @@ function throttled(fn, thisArg) {
let ticking = false;
let args = [];
return function() {
args = Array.prototype.slice.call(arguments);
thisArg = thisArg || this;
return function(...rest) {
args = Array.prototype.slice.call(rest);
if (!ticking) {
ticking = true;
helpers.requestAnimFrame.call(window, function() {
helpers.requestAnimFrame.call(window, () => {
ticking = false;
fn.apply(thisArg, args);
});
@ -220,7 +217,7 @@ function watchForRender(node, handler) {
}
};
ANIMATION_START_EVENTS.forEach(function(type) {
ANIMATION_START_EVENTS.forEach((type) => {
addListener(node, type, proxy);
});
@ -239,7 +236,7 @@ function unwatchForRender(node) {
const proxy = expando.renderProxy;
if (proxy) {
ANIMATION_START_EVENTS.forEach(function(type) {
ANIMATION_START_EVENTS.forEach((type) => {
removeListener(node, type, proxy);
});
@ -253,7 +250,7 @@ function addResizeListener(node, listener, chart, domPlatform) {
const expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
// Let's keep track of this added resizer and thus avoid DOM query when removing it.
const resizer = expando.resizer = createResizer(domPlatform, throttled(function() {
const resizer = expando.resizer = createResizer(domPlatform, throttled(() => {
if (expando.resizer) {
const container = chart.options.maintainAspectRatio && node.parentNode;
const w = container ? container.clientWidth : 0;
@ -273,7 +270,7 @@ function addResizeListener(node, listener, chart, domPlatform) {
// The resizer needs to be attached to the node parent, so we first need to be
// sure that `node` is attached to the DOM before injecting the resizer element.
watchForRender(node, function() {
watchForRender(node, () => {
if (expando.resizer) {
const container = node.parentNode;
if (container && container !== resizer.parentNode) {
@ -309,7 +306,7 @@ function injectCSS(rootNode, css) {
if (!expando.containsStyles) {
expando.containsStyles = true;
css = '/* Chart.js */\n' + css;
var style = document.createElement('style');
const style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.appendChild(document.createTextNode(css));
rootNode.appendChild(style);
@ -385,7 +382,7 @@ export default class DomPlatform extends BasePlatform {
}
const initial = canvas[EXPANDO_KEY].initial;
['height', 'width'].forEach(function(prop) {
['height', 'width'].forEach((prop) => {
const value = initial[prop];
if (helpers.isNullOrUndef(value)) {
canvas.removeAttribute(prop);
@ -395,7 +392,7 @@ export default class DomPlatform extends BasePlatform {
});
const style = initial.style || {};
Object.keys(style).forEach(function(key) {
Object.keys(style).forEach((key) => {
canvas.style[key] = style[key];
});
@ -420,7 +417,7 @@ export default class DomPlatform extends BasePlatform {
const expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
const proxies = expando.proxies || (expando.proxies = {});
const proxy = proxies[chart.id + '_' + type] = throttled(function(event) {
const proxy = proxies[chart.id + '_' + type] = throttled((event) => {
listener(fromNativeEvent(event, chart));
}, chart);

View File

@ -1,3 +1,2 @@
'use strict';
export default {disableCSSInjection: false};

View File

@ -1,5 +1,3 @@
'use strict';
import BasePlatform from './platform.base';
import BasicPlatform from './platform.basic';
import DomPlatform from './platform.dom';

View File

@ -1,5 +1,3 @@
'use strict';
import filler from './plugin.filler';
import legend from './plugin.legend';
import title from './plugin.title';

View File

@ -4,8 +4,6 @@
* @see https://github.com/chartjs/Chart.js/issues/2440#issuecomment-256461897
*/
'use strict';
import defaults from '../core/core.defaults';
import Line from '../elements/element.line';
import {_boundSegment, _boundSegments} from '../helpers/helpers.segment';
@ -66,8 +64,8 @@ function decodeFill(line, index, count) {
function computeLinearBoundary(source) {
const {scale = {}, fill} = source;
var target = null;
var horizontal;
let target = null;
let horizontal;
if (fill === 'start') {
target = scale.bottom;
@ -125,14 +123,10 @@ function computeCircularBoundary(source) {
const options = scale.options;
const length = scale._getLabels().length;
const target = [];
let start, end, value, i, center;
start = options.reverse ? scale.max : scale.min;
end = options.reverse ? scale.min : scale.max;
value = fill === 'start' ? start
: fill === 'end' ? end
: scale.getBaseValue();
const start = options.reverse ? scale.max : scale.min;
const end = options.reverse ? scale.min : scale.max;
const value = fill === 'start' ? start : fill === 'end' ? end : scale.getBaseValue();
let i, center;
if (options.gridLines.circular) {
center = scale.getPointPositionForValue(0, start);
@ -150,7 +144,7 @@ function computeCircularBoundary(source) {
}
function computeBoundary(source) {
var scale = source.scale || {};
const scale = source.scale || {};
if (scale.getPointPositionForValue) {
return computeCircularBoundary(source);
@ -210,10 +204,10 @@ function getTarget(source) {
}
function resolveTarget(sources, index, propagate) {
var source = sources[index];
var fill = source.fill;
var visited = [index];
var target;
const source = sources[index];
let fill = source.fill;
const visited = [index];
let target;
if (!propagate) {
return fill;
@ -286,7 +280,7 @@ function _segments(line, target, property) {
}
}
for (let segment of line.segments) {
for (const segment of line.segments) {
const bounds = getBounds(property, points[segment.start], points[segment.end], segment.loop);
if (!target.segments) {
@ -304,11 +298,11 @@ function _segments(line, target, property) {
// Get all segments from `target` that intersect the bounds of current segment of `line`
const subs = _boundSegments(target, bounds);
for (let sub of subs) {
for (const sub of subs) {
const subBounds = getBounds(property, tpoints[sub.start], tpoints[sub.end], sub.loop);
const fillSources = _boundSegment(segment, points, subBounds);
for (let source of fillSources) {
for (const source of fillSources) {
parts.push({
source,
target: sub,
@ -398,11 +392,11 @@ function doFill(ctx, cfg) {
export default {
id: 'filler',
afterDatasetsUpdate: function(chart, options) {
var count = (chart.data.datasets || []).length;
var propagate = options.propagate;
var sources = [];
var meta, i, line, source;
afterDatasetsUpdate(chart, options) {
const count = (chart.data.datasets || []).length;
const propagate = options.propagate;
const sources = [];
let meta, i, line, source;
for (i = 0; i < count; ++i) {
meta = chart.getDatasetMeta(i);
@ -413,7 +407,7 @@ export default {
source = {
visible: chart.isDatasetVisible(i),
fill: decodeFill(line, i, count),
chart: chart,
chart,
scale: meta.vScale,
line,
target: undefined
@ -435,7 +429,7 @@ export default {
}
},
beforeDatasetsDraw: function(chart) {
beforeDatasetsDraw(chart) {
const metasets = chart._getSortedVisibleDatasetMetas();
const area = chart.chartArea;
const ctx = chart.ctx;

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from '../core/core.defaults';
import Element from '../core/core.element';
import layouts from '../core/core.layouts';
@ -21,9 +19,9 @@ defaults.set('legend', {
weight: 1000,
// a callback that will handle
onClick: function(e, legendItem) {
var index = legendItem.datasetIndex;
var ci = this.chart;
onClick(e, legendItem) {
const index = legendItem.datasetIndex;
const ci = this.chart;
if (ci.isDatasetVisible(index)) {
ci.hide(index);
legendItem.hidden = true;
@ -50,13 +48,13 @@ defaults.set('legend', {
// lineDashOffset :
// lineJoin :
// lineWidth :
generateLabels: function(chart) {
var datasets = chart.data.datasets;
var options = chart.options.legend || {};
var usePointStyle = options.labels && options.labels.usePointStyle;
generateLabels(chart) {
const datasets = chart.data.datasets;
const options = chart.options.legend || {};
const usePointStyle = options.labels && options.labels.usePointStyle;
return chart._getSortedDatasetMetas().map(function(meta) {
var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
return chart._getSortedDatasetMetas().map((meta) => {
const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
return {
text: datasets[meta.index].label,
@ -151,7 +149,7 @@ class Legend extends Element {
beforeUpdate() {}
update(maxWidth, maxHeight, margins) {
var me = this;
const me = this;
// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
me.beforeUpdate();
@ -180,12 +178,10 @@ class Legend extends Element {
afterUpdate() {}
//
beforeSetDimensions() {}
setDimensions() {
var me = this;
const me = this;
// Set the unconstrained dimension before label rotation
if (me.isHorizontal()) {
// Reset position before calculating rotation
@ -215,19 +211,15 @@ class Legend extends Element {
afterSetDimensions() {}
//
beforeBuildLabels() {}
buildLabels() {
var me = this;
var labelOpts = me.options.labels || {};
var legendItems = call(labelOpts.generateLabels, [me.chart], me) || [];
const me = this;
const labelOpts = me.options.labels || {};
let legendItems = call(labelOpts.generateLabels, [me.chart], me) || [];
if (labelOpts.filter) {
legendItems = legendItems.filter(function(item) {
return labelOpts.filter(item, me.chart.data);
});
legendItems = legendItems.filter((item) => labelOpts.filter(item, me.chart.data));
}
if (me.options.reverse) {
@ -239,8 +231,6 @@ class Legend extends Element {
afterBuildLabels() {}
//
beforeFit() {}
fit() {
@ -283,7 +273,7 @@ class Legend extends Element {
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
me.legendItems.forEach(function(legendItem, i) {
me.legendItems.forEach((legendItem, i) => {
const boxWidth = getBoxWidth(labelOpts, fontSize);
const width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
@ -296,7 +286,7 @@ class Legend extends Element {
hitboxes[i] = {
left: 0,
top: 0,
width: width,
width,
height: fontSize
};
@ -313,8 +303,8 @@ class Legend extends Element {
let currentColWidth = 0;
let currentColHeight = 0;
let heightLimit = minSize.height - titleHeight;
me.legendItems.forEach(function(legendItem, i) {
const heightLimit = minSize.height - titleHeight;
me.legendItems.forEach((legendItem, i) => {
const boxWidth = getBoxWidth(labelOpts, fontSize);
const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
@ -389,11 +379,11 @@ class Legend extends Element {
ctx.fillStyle = fontColor; // render in correct colour
ctx.font = labelFont.string;
var boxWidth = getBoxWidth(labelOpts, fontSize);
var hitboxes = me.legendHitBoxes;
const boxWidth = getBoxWidth(labelOpts, fontSize);
const hitboxes = me.legendHitBoxes;
// current position
var drawLegendBox = function(x, y, legendItem) {
const drawLegendBox = function(x, y, legendItem) {
if (isNaN(boxWidth) || boxWidth <= 0) {
return;
}
@ -401,7 +391,7 @@ class Legend extends Element {
// Set the ctx for the box
ctx.save();
var lineWidth = valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth);
const lineWidth = valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth);
ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);
ctx.lineCap = valueOrDefault(legendItem.lineCap, lineDefault.borderCapStyle);
ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, lineDefault.borderDashOffset);
@ -423,8 +413,8 @@ class Legend extends Element {
rotation: legendItem.rotation,
borderWidth: lineWidth
};
var centerX = rtlHelper.xPlus(x, boxWidth / 2);
var centerY = y + fontSize / 2;
const centerX = rtlHelper.xPlus(x, boxWidth / 2);
const centerY = y + fontSize / 2;
// Draw pointStyle as legend symbol
drawPoint(ctx, drawOptions, centerX, centerY);
@ -439,10 +429,10 @@ class Legend extends Element {
ctx.restore();
};
var fillText = function(x, y, legendItem, textWidth) {
var halfFontSize = fontSize / 2;
var xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize);
var yMiddle = y + halfFontSize;
const fillText = function(x, y, legendItem, textWidth) {
const halfFontSize = fontSize / 2;
const xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize);
const yMiddle = y + halfFontSize;
ctx.fillText(legendItem.text, xLeft, yMiddle);
@ -456,7 +446,7 @@ class Legend extends Element {
}
};
var alignmentOffset = function(dimension, blockSize) {
const alignmentOffset = function(dimension, blockSize) {
switch (opts.align) {
case 'start':
return labelOpts.padding;
@ -486,12 +476,12 @@ class Legend extends Element {
overrideTextDirection(me.ctx, opts.textDirection);
var itemHeight = fontSize + labelOpts.padding;
me.legendItems.forEach(function(legendItem, i) {
var textWidth = ctx.measureText(legendItem.text).width;
var width = boxWidth + (fontSize / 2) + textWidth;
var x = cursor.x;
var y = cursor.y;
const itemHeight = fontSize + labelOpts.padding;
me.legendItems.forEach((legendItem, i) => {
const textWidth = ctx.measureText(legendItem.text).width;
const width = boxWidth + (fontSize / 2) + textWidth;
let x = cursor.x;
let y = cursor.y;
rtlHelper.setWidth(me._minSize.width);
@ -510,7 +500,7 @@ class Legend extends Element {
y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]);
}
var realX = rtlHelper.x(x);
const realX = rtlHelper.x(x);
drawLegendBox(realX, y, legendItem);
@ -629,8 +619,8 @@ class Legend extends Element {
* @private
*/
_getLegendItemAt(x, y) {
var me = this;
var i, hitBox, lh;
const me = this;
let i, hitBox, lh;
if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
// See if we are touching one of the dataset boxes
@ -653,10 +643,9 @@ class Legend extends Element {
* @param {IEvent} e - The event to handle
*/
handleEvent(e) {
var me = this;
var opts = me.options;
var type = e.type === 'mouseup' ? 'click' : e.type;
var hoveredItem;
const me = this;
const opts = me.options;
const type = e.type === 'mouseup' ? 'click' : e.type;
if (type === 'mousemove') {
if (!opts.onHover && !opts.onLeave) {
@ -671,7 +660,7 @@ class Legend extends Element {
}
// Chart event already has relative position in it
hoveredItem = me._getLegendItemAt(e.x, e.y);
const hoveredItem = me._getLegendItemAt(e.x, e.y);
if (type === 'click') {
if (hoveredItem && opts.onClick) {
@ -695,10 +684,10 @@ class Legend extends Element {
}
function createNewLegendAndAttach(chart, legendOpts) {
var legend = new Legend({
const legend = new Legend({
ctx: chart.ctx,
options: legendOpts,
chart: chart
chart
});
layouts.configure(chart, legend, legendOpts);
@ -718,17 +707,17 @@ export default {
*/
_element: Legend,
beforeInit: function(chart) {
var legendOpts = chart.options.legend;
beforeInit(chart) {
const legendOpts = chart.options.legend;
if (legendOpts) {
createNewLegendAndAttach(chart, legendOpts);
}
},
afterUpdate: function(chart) {
var legendOpts = chart.options.legend;
var legend = chart.legend;
afterUpdate(chart) {
const legendOpts = chart.options.legend;
const legend = chart.legend;
if (legendOpts) {
mergeIf(legendOpts, defaults.legend);
@ -746,8 +735,8 @@ export default {
}
},
afterEvent: function(chart, e) {
var legend = chart.legend;
afterEvent(chart, e) {
const legend = chart.legend;
if (legend) {
legend.handleEvent(e);
}

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from '../core/core.defaults';
import Element from '../core/core.element';
import helpers from '../helpers/index';
@ -46,9 +44,11 @@ class Title extends Element {
// These methods are ordered by lifecycle. Utilities then follow.
beforeUpdate() {}
update(maxWidth, maxHeight, margins) {
var me = this;
const me = this;
// Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
me.beforeUpdate();
@ -75,13 +75,14 @@ class Title extends Element {
me.afterUpdate();
}
afterUpdate() {}
//
beforeSetDimensions() {}
setDimensions() {
var me = this;
const me = this;
// Set the unconstrained dimension before label rotation
if (me.isHorizontal()) {
// Reset position before calculating rotation
@ -96,40 +97,40 @@ class Title extends Element {
me.bottom = me.height;
}
}
afterSetDimensions() {}
//
beforeBuildLabels() {}
buildLabels() {}
afterBuildLabels() {}
//
beforeFit() {}
fit() {
var me = this;
var opts = me.options;
var minSize = {};
var isHorizontal = me.isHorizontal();
var lineCount, textSize;
const me = this;
const opts = me.options;
const minSize = {};
const isHorizontal = me.isHorizontal();
if (!opts.display) {
me.width = minSize.width = me.height = minSize.height = 0;
return;
}
lineCount = helpers.isArray(opts.text) ? opts.text.length : 1;
const lineCount = helpers.isArray(opts.text) ? opts.text.length : 1;
me._padding = helpers.options.toPadding(opts.padding);
textSize = lineCount * helpers.options._parseFont(opts).lineHeight + me._padding.height;
const textSize = lineCount * helpers.options._parseFont(opts).lineHeight + me._padding.height;
me.width = minSize.width = isHorizontal ? me.maxWidth : textSize;
me.height = minSize.height = isHorizontal ? textSize : me.maxHeight;
}
afterFit() {}
// Shared Methods
isHorizontal() {
var pos = this.options.position;
const pos = this.options.position;
return pos === 'top' || pos === 'bottom';
}
@ -203,10 +204,10 @@ class Title extends Element {
ctx.textAlign = align;
ctx.textBaseline = 'middle';
var text = opts.text;
const text = opts.text;
if (helpers.isArray(text)) {
var y = 0;
for (var i = 0; i < text.length; ++i) {
let y = 0;
for (let i = 0; i < text.length; ++i) {
ctx.fillText(text[i], 0, y, maxWidth);
y += lineHeight;
}
@ -219,10 +220,10 @@ class Title extends Element {
}
function createNewTitleBlockAndAttach(chart, titleOpts) {
var title = new Title({
const title = new Title({
ctx: chart.ctx,
options: titleOpts,
chart: chart
chart
});
layouts.configure(chart, title, titleOpts);
@ -242,17 +243,17 @@ export default {
*/
_element: Title,
beforeInit: function(chart) {
var titleOpts = chart.options.title;
beforeInit(chart) {
const titleOpts = chart.options.title;
if (titleOpts) {
createNewTitleBlockAndAttach(chart, titleOpts);
}
},
beforeUpdate: function(chart) {
var titleOpts = chart.options.title;
var titleBlock = chart.titleBlock;
beforeUpdate(chart) {
const titleOpts = chart.options.title;
const titleBlock = chart.titleBlock;
if (titleOpts) {
helpers.mergeIf(titleOpts, defaults.title);

View File

@ -1,5 +1,3 @@
'use strict';
import Animations from '../core/core.animations';
import defaults from '../core/core.defaults';
import Element from '../core/core.element';
@ -57,13 +55,13 @@ defaults.set('tooltips', {
callbacks: {
// Args are: (tooltipItems, data)
beforeTitle: helpers.noop,
title: function(tooltipItems, data) {
var title = '';
var labels = data.labels;
var labelCount = labels ? labels.length : 0;
title(tooltipItems, data) {
let title = '';
const labels = data.labels;
const labelCount = labels ? labels.length : 0;
if (tooltipItems.length > 0) {
var item = tooltipItems[0];
const item = tooltipItems[0];
if (item.label) {
title = item.label;
} else if (labelCount > 0 && item.index < labelCount) {
@ -80,7 +78,7 @@ defaults.set('tooltips', {
// Args are: (tooltipItem, data)
beforeLabel: helpers.noop,
label: function(tooltipItem, data) {
label(tooltipItem, data) {
let label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
@ -92,15 +90,15 @@ defaults.set('tooltips', {
}
return label;
},
labelColor: function(tooltipItem, chart) {
var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
var options = meta.controller.getStyle(tooltipItem.index);
labelColor(tooltipItem, chart) {
const meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
const options = meta.controller.getStyle(tooltipItem.index);
return {
borderColor: options.borderColor,
backgroundColor: options.backgroundColor
};
},
labelTextColor: function() {
labelTextColor() {
return this.options.bodyFontColor;
},
afterLabel: helpers.noop,
@ -115,27 +113,27 @@ defaults.set('tooltips', {
}
});
var positioners = {
const positioners = {
/**
* Average mode places the tooltip at the average position of the elements shown
* @function Chart.Tooltip.positioners.average
* @param items {object[]} the items being displayed in the tooltip
* @returns {object} tooltip position
*/
average: function(items) {
average(items) {
if (!items.length) {
return false;
}
var i, len;
var x = 0;
var y = 0;
var count = 0;
let i, len;
let x = 0;
let y = 0;
let count = 0;
for (i = 0, len = items.length; i < len; ++i) {
var el = items[i].element;
const el = items[i].element;
if (el && el.hasValue()) {
var pos = el.tooltipPosition();
const pos = el.tooltipPosition();
x += pos.x;
y += pos.y;
++count;
@ -155,17 +153,17 @@ var positioners = {
* @param eventPosition {object} the position of the event in canvas coordinates
* @returns {object} the tooltip position
*/
nearest: function(items, eventPosition) {
var x = eventPosition.x;
var y = eventPosition.y;
var minDistance = Number.POSITIVE_INFINITY;
var i, len, nearestElement;
nearest(items, eventPosition) {
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) {
var el = items[i].element;
const el = items[i].element;
if (el && el.hasValue()) {
var center = el.getCenterPoint();
var d = helpers.math.distanceBetweenPoints(eventPosition, center);
const center = el.getCenterPoint();
const d = helpers.math.distanceBetweenPoints(eventPosition, center);
if (d < minDistance) {
minDistance = d;
@ -175,14 +173,14 @@ var positioners = {
}
if (nearestElement) {
var tp = nearestElement.tooltipPosition();
const tp = nearestElement.tooltipPosition();
x = tp.x;
y = tp.y;
}
return {
x: x,
y: y
x,
y
};
}
};
@ -269,9 +267,7 @@ function getTooltipSize(tooltip) {
let width = 0;
// Count of all lines in the body
var combinedBodyLength = body.reduce(function(count, bodyItem) {
return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
}, 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) {
@ -290,8 +286,8 @@ function getTooltipSize(tooltip) {
}
// Title width
var widthPadding = 0;
var maxLineWidth = function(line) {
let widthPadding = 0;
const maxLineWidth = function(line) {
width = Math.max(width, ctx.measureText(line).width + widthPadding);
};
@ -304,7 +300,7 @@ function getTooltipSize(tooltip) {
// Body lines may include some extra width due to the color box
widthPadding = options.displayColors ? (bodyFontSize + 2) : 0;
helpers.each(body, function(bodyItem) {
helpers.each(body, (bodyItem) => {
helpers.each(bodyItem.before, maxLineWidth);
helpers.each(bodyItem.lines, maxLineWidth);
helpers.each(bodyItem.after, maxLineWidth);
@ -328,9 +324,9 @@ function getTooltipSize(tooltip) {
*/
function determineAlignment(chart, options, size) {
const {x, y, width, height} = size;
var chartArea = chart.chartArea;
var xAlign = 'center';
var yAlign = 'center';
const chartArea = chart.chartArea;
let xAlign = 'center';
let yAlign = 'center';
if (y < height) {
yAlign = 'top';
@ -338,11 +334,9 @@ function determineAlignment(chart, options, size) {
yAlign = 'bottom';
}
var lf, rf; // functions to determine left, right alignment
var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
var midX = (chartArea.left + chartArea.right) / 2;
var midY = (chartArea.top + chartArea.bottom) / 2;
let lf, rf; // functions to determine left, right alignment
const midX = (chartArea.left + chartArea.right) / 2;
const midY = (chartArea.top + chartArea.bottom) / 2;
if (yAlign === 'center') {
lf = (value) => value <= midX;
@ -352,9 +346,11 @@ function determineAlignment(chart, options, size) {
rf = (value) => value >= (chart.width - (width / 2));
}
olf = (value) => value + width + options.caretSize + options.caretPadding > chart.width;
orf = (value) => value - width - options.caretSize - options.caretPadding < 0;
yf = (value) => value <= midY ? 'top' : 'bottom';
// functions to determine if left/right alignment causes tooltip to go outside chart
const olf = (value) => value + width + options.caretSize + options.caretPadding > chart.width;
const orf = (value) => value - width - options.caretSize - options.caretPadding < 0;
// function to get the y alignment if the tooltip goes outside of the left or right edges
const yf = (value) => value <= midY ? 'top' : 'bottom';
if (lf(x)) {
xAlign = 'left';
@ -381,6 +377,7 @@ function determineAlignment(chart, options, size) {
}
function alignX(size, xAlign, chartWidth) {
// eslint-disable-next-line prefer-const
let {x, width} = size;
if (xAlign === 'right') {
x -= width;
@ -397,6 +394,7 @@ function alignX(size, xAlign, chartWidth) {
}
function alignY(size, yAlign, paddingAndSize) {
// eslint-disable-next-line prefer-const
let {y, height} = size;
if (yAlign === 'top') {
y += paddingAndSize;
@ -418,7 +416,7 @@ function getBackgroundPoint(options, size, alignment, chart) {
const radiusAndPadding = cornerRadius + caretPadding;
let x = alignX(size, xAlign, chart.width);
let y = alignY(size, yAlign, paddingAndSize);
const y = alignY(size, yAlign, paddingAndSize);
if (yAlign === 'center') {
if (xAlign === 'left') {
@ -508,16 +506,16 @@ class Tooltip extends Element {
// Get the title
// Args are: (tooltipItem, data)
getTitle() {
var me = this;
var opts = me.options;
var callbacks = opts.callbacks;
getTitle(tooltipitem, data) {
const me = this;
const opts = me.options;
const callbacks = opts.callbacks;
var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
var title = callbacks.title.apply(me, arguments);
var afterTitle = callbacks.afterTitle.apply(me, arguments);
const beforeTitle = callbacks.beforeTitle.apply(me, [tooltipitem, data]);
const title = callbacks.title.apply(me, [tooltipitem, data]);
const afterTitle = callbacks.afterTitle.apply(me, [tooltipitem, data]);
var lines = [];
let lines = [];
lines = pushOrConcat(lines, splitNewlines(beforeTitle));
lines = pushOrConcat(lines, splitNewlines(title));
lines = pushOrConcat(lines, splitNewlines(afterTitle));
@ -526,18 +524,18 @@ class Tooltip extends Element {
}
// Args are: (tooltipItem, data)
getBeforeBody() {
return getBeforeAfterBodyLines(this.options.callbacks.beforeBody.apply(this, arguments));
getBeforeBody(tooltipitem, data) {
return getBeforeAfterBodyLines(this.options.callbacks.beforeBody.apply(this, [tooltipitem, data]));
}
// Args are: (tooltipItem, data)
getBody(tooltipItems, data) {
var me = this;
var callbacks = me.options.callbacks;
var bodyItems = [];
const me = this;
const callbacks = me.options.callbacks;
const bodyItems = [];
helpers.each(tooltipItems, function(tooltipItem) {
var bodyItem = {
helpers.each(tooltipItems, (tooltipItem) => {
const bodyItem = {
before: [],
lines: [],
after: []
@ -553,21 +551,21 @@ class Tooltip extends Element {
}
// Args are: (tooltipItem, data)
getAfterBody() {
return getBeforeAfterBodyLines(this.options.callbacks.afterBody.apply(this, arguments));
getAfterBody(tooltipitem, data) {
return getBeforeAfterBodyLines(this.options.callbacks.afterBody.apply(this, [tooltipitem, data]));
}
// Get the footer and beforeFooter and afterFooter lines
// Args are: (tooltipItem, data)
getFooter() {
var me = this;
var callbacks = me.options.callbacks;
getFooter(tooltipitem, data) {
const me = this;
const callbacks = me.options.callbacks;
var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
var footer = callbacks.footer.apply(me, arguments);
var afterFooter = callbacks.afterFooter.apply(me, arguments);
const beforeFooter = callbacks.beforeFooter.apply(me, [tooltipitem, data]);
const footer = callbacks.footer.apply(me, [tooltipitem, data]);
const afterFooter = callbacks.afterFooter.apply(me, [tooltipitem, data]);
var lines = [];
let lines = [];
lines = pushOrConcat(lines, splitNewlines(beforeFooter));
lines = pushOrConcat(lines, splitNewlines(footer));
lines = pushOrConcat(lines, splitNewlines(afterFooter));
@ -594,20 +592,16 @@ class Tooltip extends Element {
// If the user provided a filter function, use it to modify the tooltip items
if (options.filter) {
tooltipItems = tooltipItems.filter(function(a) {
return options.filter(a, data);
});
tooltipItems = tooltipItems.filter((a) => options.filter(a, data));
}
// If the user provided a sorting function, use it to modify the tooltip items
if (options.itemSort) {
tooltipItems = tooltipItems.sort(function(a, b) {
return options.itemSort(a, b, data);
});
tooltipItems = tooltipItems.sort((a, b) => options.itemSort(a, b, data));
}
// Determine colors for boxes
helpers.each(tooltipItems, function(tooltipItem) {
helpers.each(tooltipItems, (tooltipItem) => {
labelColors.push(options.callbacks.labelColor.call(me, tooltipItem, me._chart));
labelTextColors.push(options.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
});
@ -670,7 +664,7 @@ class Tooltip extends Element {
}
drawCaret(tooltipPoint, ctx, size) {
var caretPosition = this.getCaretPosition(tooltipPoint, size);
const caretPosition = this.getCaretPosition(tooltipPoint, size);
ctx.lineTo(caretPosition.x1, caretPosition.y1);
ctx.lineTo(caretPosition.x2, caretPosition.y2);
@ -722,12 +716,12 @@ class Tooltip extends Element {
drawTitle(pt, ctx) {
const me = this;
const options = me.options;
var title = me.title;
var length = title.length;
var titleFontSize, titleSpacing, i;
const title = me.title;
const length = title.length;
let titleFontSize, titleSpacing, i;
if (length) {
var rtlHelper = getRtlHelper(options.rtl, me.x, me.width);
const rtlHelper = getRtlHelper(options.rtl, me.x, me.width);
pt.x = getAlignedX(me, options.titleAlign);
@ -783,17 +777,17 @@ class Tooltip extends Element {
const me = this;
const {body, options} = me;
const {bodyFontSize, bodySpacing, bodyAlign, displayColors} = options;
var xLinePadding = 0;
let xLinePadding = 0;
var rtlHelper = getRtlHelper(options.rtl, me.x, me.width);
const rtlHelper = getRtlHelper(options.rtl, me.x, me.width);
var fillLineOfText = function(line) {
const fillLineOfText = function(line) {
ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyFontSize / 2);
pt.y += bodyFontSize + bodySpacing;
};
var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
var bodyItem, textColor, lines, i, j, ilen, jlen;
const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
let bodyItem, textColor, lines, i, j, ilen, jlen;
ctx.textAlign = bodyAlign;
ctx.textBaseline = 'middle';
@ -841,12 +835,12 @@ class Tooltip extends Element {
drawFooter(pt, ctx) {
const me = this;
const options = me.options;
var footer = me.footer;
var length = footer.length;
var footerFontSize, i;
const footer = me.footer;
const length = footer.length;
let footerFontSize, i;
if (length) {
var rtlHelper = getRtlHelper(options.rtl, me.x, me.width);
const rtlHelper = getRtlHelper(options.rtl, me.x, me.width);
pt.x = getAlignedX(me, options.footerAlign);
pt.y += options.footerMarginTop;
@ -943,11 +937,11 @@ class Tooltip extends Element {
me._updateAnimationTarget();
var tooltipSize = {
const tooltipSize = {
width: me.width,
height: me.height
};
var pt = {
const pt = {
x: me.x,
y: me.y
};
@ -956,7 +950,7 @@ class Tooltip extends Element {
opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
// Truthy/falsey value for empty tooltip
var hasTooltipContent = me.title.length || me.beforeBody.length || me.body.length || me.afterBody.length || me.footer.length;
const hasTooltipContent = me.title.length || me.beforeBody.length || me.body.length || me.afterBody.length || me.footer.length;
if (options.enabled && hasTooltipContent) {
ctx.save();
@ -1035,7 +1029,7 @@ export default {
_element: Tooltip,
positioners,
afterInit: function(chart) {
afterInit(chart) {
const tooltipOpts = chart.options.tooltips;
if (tooltipOpts) {
@ -1043,19 +1037,19 @@ export default {
}
},
beforeUpdate: function(chart) {
beforeUpdate(chart) {
if (chart.tooltip) {
chart.tooltip.initialize();
}
},
reset: function(chart) {
reset(chart) {
if (chart.tooltip) {
chart.tooltip.initialize();
}
},
afterDraw: function(chart) {
afterDraw(chart) {
const tooltip = chart.tooltip;
const args = {
tooltip
@ -1070,7 +1064,7 @@ export default {
plugins.notify(chart, 'afterTooltipDraw', [args]);
},
afterEvent: function(chart, e) {
afterEvent(chart, e) {
if (chart.tooltip) {
chart.tooltip.handleEvent(e);
}

View File

@ -1,5 +1,3 @@
'use strict';
import category from './scale.category';
import linear from './scale.linear';
import logarithmic from './scale.logarithmic';
@ -7,9 +5,9 @@ import radialLinear from './scale.radialLinear';
import time from './scale.time';
export default {
category: category,
linear: linear,
logarithmic: logarithmic,
radialLinear: radialLinear,
time: time
category,
linear,
logarithmic,
radialLinear,
time
};

View File

@ -1,5 +1,3 @@
'use strict';
import Scale from '../core/core.scale';
const defaultConfig = {
@ -53,9 +51,7 @@ class CategoryScale extends Scale {
me._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);
me._startValue = me.min - (offset ? 0.5 : 0);
return labels.map(function(l) {
return {value: l};
});
return labels.map((l) => ({value: l}));
}
getLabelForValue(value) {
@ -84,7 +80,7 @@ class CategoryScale extends Scale {
// Used to get data value locations. Value can either be an index or a numerical value
getPixelForValue(value) {
var me = this;
const me = this;
if (typeof value !== 'number') {
value = me._parse(value);

View File

@ -1,5 +1,3 @@
'use strict';
import {isFinite, valueOrDefault} from '../helpers/helpers.core';
import {_parseFont} from '../helpers/helpers.options';
import LinearScaleBase from './scale.linearbase';
@ -16,8 +14,8 @@ class LinearScale extends LinearScaleBase {
const me = this;
const options = me.options;
const minmax = me._getMinMax(true);
let min = minmax.min;
let max = minmax.max;
const min = minmax.min;
const max = minmax.max;
me.min = isFinite(min) ? min : valueOrDefault(options.suggestedMin, 0);
me.max = isFinite(max) ? max : valueOrDefault(options.suggestedMax, 1);
@ -36,13 +34,12 @@ class LinearScale extends LinearScaleBase {
* @private
*/
_computeTickLimit() {
var me = this;
var tickFont;
const me = this;
if (me.isHorizontal()) {
return Math.ceil(me.width / 40);
}
tickFont = _parseFont(me.options.ticks);
const tickFont = _parseFont(me.options.ticks);
return Math.ceil(me.height / tickFont.lineHeight);
}
@ -57,7 +54,7 @@ class LinearScale extends LinearScaleBase {
// Utils
getPixelForValue(value) {
var me = this;
const me = this;
return me.getPixelForDecimal((value - me._startValue) / me._valueRange);
}

View File

@ -1,5 +1,3 @@
'use strict';
import {isNullOrUndef, valueOrDefault} from '../helpers/helpers.core';
import {almostEquals, almostWhole, log10, _decimalPlaces, _setMinAndMaxByKey, sign} from '../helpers/helpers.math';
import Scale from '../core/core.scale';
@ -97,7 +95,7 @@ function generateTicks(generationOptions, dataRange) {
niceMin = Math.round(niceMin * factor) / factor;
niceMax = Math.round(niceMax * factor) / factor;
ticks.push({value: isNullOrUndef(min) ? niceMin : min});
for (var j = 1; j < numSpaces; ++j) {
for (let j = 1; j < numSpaces; ++j) {
ticks.push({value: Math.round((niceMin + j * spacing) * factor) / factor});
}
ticks.push({value: isNullOrUndef(max) ? niceMax : max});
@ -205,6 +203,7 @@ class LinearScaleBase extends Scale {
getTickLimit() {
const me = this;
const tickOpts = me.options.ticks;
// eslint-disable-next-line prefer-const
let {maxTicksLimit, stepSize} = tickOpts;
let maxTicks;
@ -249,7 +248,7 @@ class LinearScaleBase extends Scale {
maxTicks = Math.max(2, maxTicks);
const numericGeneratorOptions = {
maxTicks: maxTicks,
maxTicks,
min: opts.min,
max: opts.max,
precision: tickOpts.precision,

View File

@ -1,5 +1,3 @@
'use strict';
import {isFinite} from '../helpers/helpers.core';
import {_setMinAndMaxByKey, log10} from '../helpers/helpers.math';
import Scale from '../core/core.scale';
@ -77,8 +75,8 @@ class LogarithmicScale extends Scale {
/**
* @private
*/
_parse(raw, index) { // eslint-disable-line no-unused-vars
const value = LinearScaleBase.prototype._parse.apply(this, arguments);
_parse(raw, index) {
const value = LinearScaleBase.prototype._parse.apply(this, [raw, index]);
if (value === 0) {
return undefined;
}
@ -173,7 +171,7 @@ class LogarithmicScale extends Scale {
*/
_configure() {
const me = this;
let start = me.min;
const start = me.min;
Scale.prototype._configure.call(me);

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from '../core/core.defaults';
import helpers from '../helpers/index';
import {_longestText} from '../helpers/helpers.canvas';
@ -55,14 +53,14 @@ const defaultConfig = {
fontSize: 10,
// Function - Used to convert point labels
callback: function(label) {
callback(label) {
return label;
}
}
};
function getTickBackdropHeight(opts) {
var tickOpts = opts.ticks;
const tickOpts = opts.ticks;
if (tickOpts.display && opts.display) {
return valueOrDefault(tickOpts.fontSize, defaults.fontSize) + tickOpts.backdropPaddingY * 2;
@ -134,33 +132,33 @@ function fitWithPointLabels(scale) {
//
// https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
var plFont = helpers.options._parseFont(scale.options.pointLabels);
const plFont = helpers.options._parseFont(scale.options.pointLabels);
// Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
// Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
var furthestLimits = {
const furthestLimits = {
l: 0,
r: scale.width,
t: 0,
b: scale.height - scale.paddingTop
};
var furthestAngles = {};
var i, textSize, pointPosition;
const furthestAngles = {};
let i, textSize, pointPosition;
scale.ctx.font = plFont.string;
scale._pointLabelSizes = [];
var valueCount = scale.chart.data.labels.length;
const valueCount = scale.chart.data.labels.length;
for (i = 0; i < valueCount; i++) {
pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);
scale._pointLabelSizes[i] = textSize;
// Add quarter circle to make degree 0 mean top of circle
var angleRadians = scale.getIndexAngle(i);
var angle = toDegrees(angleRadians);
var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
const angleRadians = scale.getIndexAngle(i);
const angle = toDegrees(angleRadians);
const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
if (hLimits.start < furthestLimits.l) {
furthestLimits.l = hLimits.start;
@ -197,8 +195,8 @@ function getTextAlignForAngle(angle) {
}
function fillText(ctx, text, position, lineHeight) {
var y = position.y + lineHeight / 2;
var i, ilen;
let y = position.y + lineHeight / 2;
let i, ilen;
if (helpers.isArray(text)) {
for (i = 0, ilen = text.length; i < ilen; ++i) {
@ -219,29 +217,29 @@ function adjustPointPositionForLabelHeight(angle, textSize, position) {
}
function drawPointLabels(scale) {
var ctx = scale.ctx;
var opts = scale.options;
var pointLabelOpts = opts.pointLabels;
var tickBackdropHeight = getTickBackdropHeight(opts);
var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
var plFont = helpers.options._parseFont(pointLabelOpts);
const ctx = scale.ctx;
const opts = scale.options;
const pointLabelOpts = opts.pointLabels;
const tickBackdropHeight = getTickBackdropHeight(opts);
const outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
const plFont = helpers.options._parseFont(pointLabelOpts);
ctx.save();
ctx.font = plFont.string;
ctx.textBaseline = 'middle';
for (var i = scale.chart.data.labels.length - 1; i >= 0; i--) {
for (let i = scale.chart.data.labels.length - 1; i >= 0; i--) {
// Extra pixels out for some label spacing
var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
const extra = (i === 0 ? tickBackdropHeight / 2 : 0);
const pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
// Keep this in loop since we may support array properties here
var pointLabelFontColor = valueAtIndexOrDefault(pointLabelOpts.fontColor, i, defaults.fontColor);
const pointLabelFontColor = valueAtIndexOrDefault(pointLabelOpts.fontColor, i, defaults.fontColor);
ctx.fillStyle = pointLabelFontColor;
var angleRadians = scale.getIndexAngle(i);
var angle = toDegrees(angleRadians);
const angleRadians = scale.getIndexAngle(i);
const angle = toDegrees(angleRadians);
ctx.textAlign = getTextAlignForAngle(angle);
adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
fillText(ctx, scale.pointLabels[i], pointLabelPosition, plFont.lineHeight);
@ -250,12 +248,12 @@ function drawPointLabels(scale) {
}
function drawRadiusLine(scale, gridLineOpts, radius, index) {
var ctx = scale.ctx;
var circular = gridLineOpts.circular;
var valueCount = scale.chart.data.labels.length;
var lineColor = valueAtIndexOrDefault(gridLineOpts.color, index - 1, undefined);
var lineWidth = valueAtIndexOrDefault(gridLineOpts.lineWidth, index - 1, undefined);
var pointPosition;
const ctx = scale.ctx;
const circular = gridLineOpts.circular;
const valueCount = scale.chart.data.labels.length;
const lineColor = valueAtIndexOrDefault(gridLineOpts.color, index - 1, undefined);
const lineWidth = valueAtIndexOrDefault(gridLineOpts.lineWidth, index - 1, undefined);
let pointPosition;
if ((!circular && !valueCount) || !lineColor || !lineWidth) {
return;
@ -278,7 +276,7 @@ function drawRadiusLine(scale, gridLineOpts, radius, index) {
pointPosition = scale.getPointPosition(0, radius);
ctx.moveTo(pointPosition.x, pointPosition.y);
for (var i = 1; i < valueCount; i++) {
for (let i = 1; i < valueCount; i++) {
pointPosition = scale.getPointPosition(i, radius);
ctx.lineTo(pointPosition.x, pointPosition.y);
}
@ -308,7 +306,7 @@ class RadialLinearScale extends LinearScaleBase {
}
setDimensions() {
var me = this;
const me = this;
// Set the unconstrained dimension before label rotation
me.width = me.maxWidth;
@ -320,10 +318,10 @@ class RadialLinearScale extends LinearScaleBase {
}
determineDataLimits() {
var me = this;
var minmax = me._getMinMax(false);
var min = minmax.min;
var max = minmax.max;
const me = this;
const minmax = me._getMinMax(false);
const min = minmax.min;
const max = minmax.max;
me.min = helpers.isFinite(min) && !isNaN(min) ? min : 0;
me.max = helpers.isFinite(max) && !isNaN(max) ? max : 0;
@ -341,20 +339,20 @@ class RadialLinearScale extends LinearScaleBase {
}
generateTickLabels(ticks) {
var me = this;
const me = this;
LinearScaleBase.prototype.generateTickLabels.call(me, ticks);
// Point labels
me.pointLabels = me.chart.data.labels.map(function(value, index) {
var label = helpers.callback(me.options.pointLabels.callback, [value, index], me);
me.pointLabels = me.chart.data.labels.map((value, index) => {
const label = helpers.callback(me.options.pointLabels.callback, [value, index], me);
return label || label === 0 ? label : '';
});
}
fit() {
var me = this;
var opts = me.options;
const me = this;
const opts = me.options;
if (opts.display && opts.pointLabels.display) {
fitWithPointLabels(me);
@ -368,11 +366,11 @@ class RadialLinearScale extends LinearScaleBase {
* @private
*/
_setReductions(largestPossibleRadius, furthestLimits, furthestAngles) {
var me = this;
var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
const me = this;
let radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
let radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
let radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
let radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
radiusReductionLeft = numberOrZero(radiusReductionLeft);
radiusReductionRight = numberOrZero(radiusReductionRight);
@ -386,34 +384,34 @@ class RadialLinearScale extends LinearScaleBase {
}
setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {
var me = this;
var maxRight = me.width - rightMovement - me.drawingArea;
var maxLeft = leftMovement + me.drawingArea;
var maxTop = topMovement + me.drawingArea;
var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
const me = this;
const maxRight = me.width - rightMovement - me.drawingArea;
const maxLeft = leftMovement + me.drawingArea;
const maxTop = topMovement + me.drawingArea;
const maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
}
getIndexAngle(index) {
var chart = this.chart;
var angleMultiplier = Math.PI * 2 / chart.data.labels.length;
var options = chart.options || {};
var startAngle = options.startAngle || 0;
const chart = this.chart;
const angleMultiplier = Math.PI * 2 / chart.data.labels.length;
const options = chart.options || {};
const startAngle = options.startAngle || 0;
return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));
}
getDistanceFromCenterForValue(value) {
var me = this;
const me = this;
if (helpers.isNullOrUndef(value)) {
return NaN;
}
// Take into account half font size + the yPadding of the top value
var scalingFactor = me.drawingArea / (me.max - me.min);
const scalingFactor = me.drawingArea / (me.max - me.min);
if (me.options.reverse) {
return (me.max - value) * scalingFactor;
}
@ -421,8 +419,8 @@ class RadialLinearScale extends LinearScaleBase {
}
getPointPosition(index, distanceFromCenter) {
var me = this;
var angle = me.getIndexAngle(index) - (Math.PI / 2);
const me = this;
const angle = me.getIndexAngle(index) - (Math.PI / 2);
return {
x: Math.cos(angle) * distanceFromCenter + me.xCenter,
y: Math.sin(angle) * distanceFromCenter + me.yCenter,
@ -442,21 +440,21 @@ class RadialLinearScale extends LinearScaleBase {
* @private
*/
_drawGrid() {
var me = this;
var ctx = me.ctx;
var opts = me.options;
var gridLineOpts = opts.gridLines;
var angleLineOpts = opts.angleLines;
var lineWidth = valueOrDefault(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
var lineColor = valueOrDefault(angleLineOpts.color, gridLineOpts.color);
var i, offset, position;
const me = this;
const ctx = me.ctx;
const opts = me.options;
const gridLineOpts = opts.gridLines;
const angleLineOpts = opts.angleLines;
const lineWidth = valueOrDefault(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
const lineColor = valueOrDefault(angleLineOpts.color, gridLineOpts.color);
let i, offset, position;
if (opts.pointLabels.display) {
drawPointLabels(me);
}
if (gridLineOpts.display) {
me.ticks.forEach(function(tick, index) {
me.ticks.forEach((tick, index) => {
if (index !== 0) {
offset = me.getDistanceFromCenterForValue(me.ticks[index].value);
drawRadiusLine(me, gridLineOpts, offset, index);
@ -490,19 +488,19 @@ class RadialLinearScale extends LinearScaleBase {
* @private
*/
_drawLabels() {
var me = this;
var ctx = me.ctx;
var opts = me.options;
var tickOpts = opts.ticks;
const me = this;
const ctx = me.ctx;
const opts = me.options;
const tickOpts = opts.ticks;
if (!tickOpts.display) {
return;
}
var startAngle = me.getIndexAngle(0);
var tickFont = helpers.options._parseFont(tickOpts);
var tickFontColor = valueOrDefault(tickOpts.fontColor, defaults.fontColor);
var offset, width;
const startAngle = me.getIndexAngle(0);
const tickFont = helpers.options._parseFont(tickOpts);
const tickFontColor = valueOrDefault(tickOpts.fontColor, defaults.fontColor);
let offset, width;
ctx.save();
ctx.font = tickFont.string;
@ -511,7 +509,7 @@ class RadialLinearScale extends LinearScaleBase {
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
me.ticks.forEach(function(tick, index) {
me.ticks.forEach((tick, index) => {
if (index === 0 && !opts.reverse) {
return;
}

View File

@ -1,5 +1,3 @@
'use strict';
import adapters from '../core/core.adapters';
import defaults from '../core/core.defaults';
import {isFinite, isNullOrUndef, mergeIf, valueOrDefault} from '../helpers/helpers.core';
@ -102,13 +100,13 @@ function parse(scale, input) {
function getDataTimestamps(scale) {
const isSeries = scale.options.distribution === 'series';
let timestamps = scale._cache.data || [];
let i, ilen, metas;
let i, ilen;
if (timestamps.length) {
return timestamps;
}
metas = scale._getMatchingVisibleMetas();
const metas = scale._getMatchingVisibleMetas();
if (isSeries && metas.length) {
return metas[0].controller._getAllParsedValues(scale);
@ -129,13 +127,13 @@ function getDataTimestamps(scale) {
function getLabelTimestamps(scale) {
const isSeries = scale.options.distribution === 'series';
const timestamps = scale._cache.labels || [];
let i, ilen, labels;
let i, ilen;
if (timestamps.length) {
return timestamps;
}
labels = scale._getLabels();
const labels = scale._getLabels();
for (i = 0, ilen = labels.length; i < ilen; ++i) {
timestamps.push(parse(scale, labels[i]));
}
@ -149,14 +147,13 @@ function getLabelTimestamps(scale) {
*/
function getAllTimestamps(scale) {
let timestamps = scale._cache.all || [];
let label, data;
if (timestamps.length) {
return timestamps;
}
data = getDataTimestamps(scale);
label = getLabelTimestamps(scale);
const data = getDataTimestamps(scale);
const label = getLabelTimestamps(scale);
if (data.length && label.length) {
// If combining labels and data (data might not contain all labels),
// we need to recheck uniqueness and sort
@ -298,7 +295,7 @@ function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
* @return {object}
*/
function determineMajorUnit(unit) {
for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
for (let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
if (INTERVALS.get(UNITS[i]).common) {
return UNITS[i];
}
@ -349,7 +346,7 @@ function generate(scale) {
// Prevent browser from freezing in case user options request millions of milliseconds
if (adapter.diff(max, min, minor) > 100000 * stepSize) {
throw min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor;
throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);
}
if (scale.options.ticks.source === 'data') {
@ -408,7 +405,7 @@ function computeOffsets(table, timestamps, min, max, options) {
}
}
return {start: start, end: end, factor: 1 / (start + 1 + end)};
return {start, end, factor: 1 / (start + 1 + end)};
}
/**
@ -450,7 +447,7 @@ function ticksFromTimestamps(scale, values, majorUnit) {
map[value] = i;
ticks.push({
value: value,
value,
major: false
});
}
@ -647,6 +644,7 @@ class TimeScale extends Scale {
const options = me.options;
const adapter = me._adapter;
const unit = options.time.unit || 'day';
// eslint-disable-next-line prefer-const
let {min, max, minDefined, maxDefined} = me._getUserBounds();
/**
@ -754,7 +752,7 @@ class TimeScale extends Scale {
const majorFormat = majorUnit && formats[majorUnit];
const tick = ticks[index];
const major = majorUnit && majorFormat && tick && tick.major;
const label = me._adapter.format(time, format ? format : major ? majorFormat : minorFormat);
const label = me._adapter.format(time, format || (major ? majorFormat : minorFormat));
const formatter = options.ticks.callback;
return formatter ? formatter(label, index, ticks) : label;
}

View File

@ -2,8 +2,11 @@ parserOptions:
ecmaVersion: 6
env:
es6: true # also changes default ecmaVersion to 6
es6: true
jasmine: true
commonjs: true
es2017: false
es2020: false
globals:
acquireChart: true
@ -16,4 +19,19 @@ globals:
rules:
# Best Practices
complexity: 0
max-statements: 0
max-statements: [0, 100]
# Loosen up for tests
no-var: 0
prefer-arrow-callback: 0
prefer-spread: 0
prefer-const: 0
object-shorthand: 0
import/no-commonjs: 0
no-invalid-this: 0
array-callback-return: 0
operator-assignment: 0
no-empty-function: 0
import/no-namespace: 0
prefer-rest-params: 0
no-unneeded-ternary: 0