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: env:
es6: true es6: true
browser: true browser: true
node: true node: true
parser: babel-eslint
parserOptions: parserOptions:
ecmaVersion: 2018 ecmaVersion: 7
sourceType: 'module' sourceType: module
ecmaFeatures:
impliedStrict: true
modules: true
experimentalObjectRestSpread: true
plugins: ['html'] 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=", "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=",
"dev": true "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": { "array-initial": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/array-initial/-/array-initial-1.1.0.tgz", "resolved": "https://registry.npmjs.org/array-initial/-/array-initial-1.1.0.tgz",
@ -2404,6 +2415,16 @@
"integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=",
"dev": true "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": { "arraybuffer.slice": {
"version": "0.0.7", "version": "0.0.7",
"resolved": "https://registry.npmjs.org/arraybuffer.slice/-/arraybuffer.slice-0.0.7.tgz", "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": { "babel-generator": {
"version": "6.26.1", "version": "6.26.1",
"resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", "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": { "content-type": {
"version": "1.0.4", "version": "1.0.4",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz",
@ -4446,6 +4487,44 @@
"is-arrayish": "^0.2.1" "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": { "es5-ext": {
"version": "0.10.52", "version": "0.10.52",
"resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.52.tgz", "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.52.tgz",
@ -4636,6 +4715,293 @@
"integrity": "sha512-9NbZlmn5clHbzFc+EK7zp7KhgU2vhcbJNb4OrSrm9nMOMTs7yVdzP00jqqfs7dhDkhT4CfVxQlV1DMfjhGBLIA==", "integrity": "sha512-9NbZlmn5clHbzFc+EK7zp7KhgU2vhcbJNb4OrSrm9nMOMTs7yVdzP00jqqfs7dhDkhT4CfVxQlV1DMfjhGBLIA==",
"dev": true "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": { "eslint-plugin-html": {
"version": "6.0.0", "version": "6.0.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-html/-/eslint-plugin-html-6.0.0.tgz", "resolved": "https://registry.npmjs.org/eslint-plugin-html/-/eslint-plugin-html-6.0.0.tgz",
@ -4645,6 +5011,156 @@
"htmlparser2": "^3.10.1" "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": { "eslint-scope": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.0.0.tgz", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.0.0.tgz",
@ -6482,6 +6998,15 @@
"har-schema": "^2.0.0" "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": { "has-ansi": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz",
@ -6826,6 +7351,12 @@
"integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==",
"dev": true "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": { "is-data-descriptor": {
"version": "0.1.4", "version": "0.1.4",
"resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", "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": { "is-descriptor": {
"version": "0.1.6", "version": "0.1.6",
"resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz",
@ -6957,6 +7494,15 @@
"@types/estree": "0.0.39" "@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": { "is-relative": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-relative/-/is-relative-1.0.0.tgz", "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-1.0.0.tgz",
@ -6966,6 +7512,29 @@
"is-unc-path": "^1.0.0" "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": { "is-typedarray": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", "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": { "object-keys": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
@ -12953,6 +13528,18 @@
"make-iterator": "^1.0.0" "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": { "on-finished": {
"version": "2.3.0", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
@ -13190,6 +13777,12 @@
"integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=",
"dev": true "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": { "path-key": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz",
@ -13279,6 +13872,66 @@
"pngjs": "^3.4.0" "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": { "plexer": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/plexer/-/plexer-1.0.1.tgz", "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": { "string_decoder": {
"version": "1.3.0", "version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,3 @@
'use strict';
import defaults from './core.defaults'; import defaults from './core.defaults';
import {clone, each, extend, merge} from '../helpers/helpers.core'; import {clone, each, extend, merge} from '../helpers/helpers.core';
import layouts from './core.layouts'; import layouts from './core.layouts';
@ -13,26 +11,26 @@ export default {
// Scale config defaults // Scale config defaults
defaults: {}, defaults: {},
registerScaleType: function(type, scaleConstructor, scaleDefaults) { registerScaleType(type, scaleConstructor, scaleDefaults) {
this.constructors[type] = scaleConstructor; this.constructors[type] = scaleConstructor;
this.defaults[type] = clone(scaleDefaults); this.defaults[type] = clone(scaleDefaults);
}, },
getScaleConstructor: function(type) { getScaleConstructor(type) {
return Object.prototype.hasOwnProperty.call(this.constructors, type) ? this.constructors[type] : undefined; 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 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]]) : {}; return Object.prototype.hasOwnProperty.call(this.defaults, type) ? merge({}, [defaults.scale, this.defaults[type]]) : {};
}, },
updateScaleDefaults: function(type, additions) { updateScaleDefaults(type, additions) {
var me = this; const me = this;
if (Object.prototype.hasOwnProperty.call(me.defaults, type)) { if (Object.prototype.hasOwnProperty.call(me.defaults, type)) {
me.defaults[type] = extend(me.defaults[type], additions); 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 // 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 // Set ILayoutItem parameters for backwards compatibility
scale.fullWidth = scale.options.fullWidth; scale.fullWidth = scale.options.fullWidth;
scale.position = scale.options.position; scale.position = scale.options.position;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -10,7 +10,7 @@ function isConstrainedValue(value) {
* @private * @private
*/ */
function _getParentNode(domNode) { function _getParentNode(domNode) {
var parent = domNode.parentNode; let parent = domNode.parentNode;
if (parent && parent.toString() === '[object ShadowRoot]') { if (parent && parent.toString() === '[object ShadowRoot]') {
parent = parent.host; 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 // Private helper function to convert max-width/max-height values that may be percentages into a number
function parseMaxStyle(styleValue, node, parentProperty) { function parseMaxStyle(styleValue, node, parentProperty) {
var valueInPixels; let valueInPixels;
if (typeof styleValue === 'string') { if (typeof styleValue === 'string') {
valueInPixels = parseInt(styleValue, 10); 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} * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
*/ */
function getConstraintDimension(domNode, maxStyle, percentageProperty) { function getConstraintDimension(domNode, maxStyle, percentageProperty) {
var view = document.defaultView; const view = document.defaultView;
var parentNode = _getParentNode(domNode); const parentNode = _getParentNode(domNode);
var constrainedNode = view.getComputedStyle(domNode)[maxStyle]; const constrainedNode = view.getComputedStyle(domNode)[maxStyle];
var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle]; const constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
var hasCNode = isConstrainedValue(constrainedNode); const hasCNode = isConstrainedValue(constrainedNode);
var hasCContainer = isConstrainedValue(constrainedContainer); const hasCContainer = isConstrainedValue(constrainedContainer);
var infinity = Number.POSITIVE_INFINITY; const infinity = Number.POSITIVE_INFINITY;
if (hasCNode || hasCContainer) { if (hasCNode || hasCContainer) {
return Math.min( return Math.min(
@ -84,12 +84,12 @@ function _calculatePadding(container, padding, parentDimension) {
} }
export function getRelativePosition(evt, chart) { export function getRelativePosition(evt, chart) {
var mouseX, mouseY; let mouseX, mouseY;
var e = evt.originalEvent || evt; const e = evt.originalEvent || evt;
var canvasElement = evt.target || evt.srcElement; const canvasElement = evt.target || evt.srcElement;
var boundingRect = canvasElement.getBoundingClientRect(); const boundingRect = canvasElement.getBoundingClientRect();
var touches = e.touches; const touches = e.touches;
if (touches && touches.length > 0) { if (touches && touches.length > 0) {
mouseX = touches[0].clientX; mouseX = touches[0].clientX;
mouseY = touches[0].clientY; mouseY = touches[0].clientY;
@ -102,12 +102,12 @@ export function getRelativePosition(evt, chart) {
// Scale mouse coordinates into canvas coordinates // Scale mouse coordinates into canvas coordinates
// by following the pattern laid out by 'jerryj' in the comments of // by following the pattern laid out by 'jerryj' in the comments of
// https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/ // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
var paddingLeft = parseFloat(getStyle(canvasElement, 'padding-left')); const paddingLeft = parseFloat(getStyle(canvasElement, 'padding-left'));
var paddingTop = parseFloat(getStyle(canvasElement, 'padding-top')); const paddingTop = parseFloat(getStyle(canvasElement, 'padding-top'));
var paddingRight = parseFloat(getStyle(canvasElement, 'padding-right')); const paddingRight = parseFloat(getStyle(canvasElement, 'padding-right'));
var paddingBottom = parseFloat(getStyle(canvasElement, 'padding-bottom')); const paddingBottom = parseFloat(getStyle(canvasElement, 'padding-bottom'));
var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight; const width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom; 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 // 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 // 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) { export function getMaximumWidth(domNode) {
var container = _getParentNode(domNode); const container = _getParentNode(domNode);
if (!container) { if (!container) {
return domNode.clientWidth; return domNode.clientWidth;
} }
var clientWidth = container.clientWidth; const clientWidth = container.clientWidth;
var paddingLeft = _calculatePadding(container, 'padding-left', clientWidth); const paddingLeft = _calculatePadding(container, 'padding-left', clientWidth);
var paddingRight = _calculatePadding(container, 'padding-right', clientWidth); const paddingRight = _calculatePadding(container, 'padding-right', clientWidth);
var w = clientWidth - paddingLeft - paddingRight; const w = clientWidth - paddingLeft - paddingRight;
var cw = getConstraintWidth(domNode); const cw = getConstraintWidth(domNode);
return isNaN(cw) ? w : Math.min(w, cw); return isNaN(cw) ? w : Math.min(w, cw);
} }
export function getMaximumHeight(domNode) { export function getMaximumHeight(domNode) {
var container = _getParentNode(domNode); const container = _getParentNode(domNode);
if (!container) { if (!container) {
return domNode.clientHeight; return domNode.clientHeight;
} }
var clientHeight = container.clientHeight; const clientHeight = container.clientHeight;
var paddingTop = _calculatePadding(container, 'padding-top', clientHeight); const paddingTop = _calculatePadding(container, 'padding-top', clientHeight);
var paddingBottom = _calculatePadding(container, 'padding-bottom', clientHeight); const paddingBottom = _calculatePadding(container, 'padding-bottom', clientHeight);
var h = clientHeight - paddingTop - paddingBottom; const h = clientHeight - paddingTop - paddingBottom;
var ch = getConstraintHeight(domNode); const ch = getConstraintHeight(domNode);
return isNaN(ch) ? h : Math.min(h, ch); 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. * Easing functions adapted from Robert Penner's easing equations.
* @namespace Chart.helpers.easing.effects * @namespace Chart.helpers.easing.effects
* @see http://www.robertpenner.com/easing/ * @see http://www.robertpenner.com/easing/
*/ */
export const effects = { const effects = {
linear: function(t) { linear(t) {
return t; return t;
}, },
easeInQuad: function(t) { easeInQuad(t) {
return t * t; return t * t;
}, },
easeOutQuad: function(t) { easeOutQuad(t) {
return -t * (t - 2); return -t * (t - 2);
}, },
easeInOutQuad: function(t) { easeInOutQuad(t) {
if ((t /= 0.5) < 1) { if ((t /= 0.5) < 1) {
return 0.5 * t * t; return 0.5 * t * t;
} }
return -0.5 * ((--t) * (t - 2) - 1); return -0.5 * ((--t) * (t - 2) - 1);
}, },
easeInCubic: function(t) { easeInCubic(t) {
return t * t * t; return t * t * t;
}, },
easeOutCubic: function(t) { easeOutCubic(t) {
return (t = t - 1) * t * t + 1; return (t -= 1) * t * t + 1;
}, },
easeInOutCubic: function(t) { easeInOutCubic(t) {
if ((t /= 0.5) < 1) { if ((t /= 0.5) < 1) {
return 0.5 * t * t * t; return 0.5 * t * t * t;
} }
return 0.5 * ((t -= 2) * t * t + 2); return 0.5 * ((t -= 2) * t * t + 2);
}, },
easeInQuart: function(t) { easeInQuart(t) {
return t * t * t * t; return t * t * t * t;
}, },
easeOutQuart: function(t) { easeOutQuart(t) {
return -((t = t - 1) * t * t * t - 1); return -((t -= 1) * t * t * t - 1);
}, },
easeInOutQuart: function(t) { easeInOutQuart(t) {
if ((t /= 0.5) < 1) { if ((t /= 0.5) < 1) {
return 0.5 * t * t * t * t; return 0.5 * t * t * t * t;
} }
return -0.5 * ((t -= 2) * t * t * t - 2); return -0.5 * ((t -= 2) * t * t * t - 2);
}, },
easeInQuint: function(t) { easeInQuint(t) {
return t * t * t * t * t; return t * t * t * t * t;
}, },
easeOutQuint: function(t) { easeOutQuint(t) {
return (t = t - 1) * t * t * t * t + 1; return (t -= 1) * t * t * t * t + 1;
}, },
easeInOutQuint: function(t) { easeInOutQuint(t) {
if ((t /= 0.5) < 1) { if ((t /= 0.5) < 1) {
return 0.5 * t * t * t * t * t; return 0.5 * t * t * t * t * t;
} }
return 0.5 * ((t -= 2) * t * t * t * t + 2); return 0.5 * ((t -= 2) * t * t * t * t + 2);
}, },
easeInSine: function(t) { easeInSine(t) {
return -Math.cos(t * (Math.PI / 2)) + 1; return -Math.cos(t * (Math.PI / 2)) + 1;
}, },
easeOutSine: function(t) { easeOutSine(t) {
return Math.sin(t * (Math.PI / 2)); return Math.sin(t * (Math.PI / 2));
}, },
easeInOutSine: function(t) { easeInOutSine(t) {
return -0.5 * (Math.cos(Math.PI * t) - 1); return -0.5 * (Math.cos(Math.PI * t) - 1);
}, },
easeInExpo: function(t) { easeInExpo(t) {
return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)); 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; return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
}, },
easeInOutExpo: function(t) { easeInOutExpo(t) {
if (t === 0) { if (t === 0) {
return 0; return 0;
} }
@ -103,28 +101,28 @@ export const effects = {
return 0.5 * (-Math.pow(2, -10 * --t) + 2); return 0.5 * (-Math.pow(2, -10 * --t) + 2);
}, },
easeInCirc: function(t) { easeInCirc(t) {
if (t >= 1) { if (t >= 1) {
return t; return t;
} }
return -(Math.sqrt(1 - t * t) - 1); return -(Math.sqrt(1 - t * t) - 1);
}, },
easeOutCirc: function(t) { easeOutCirc(t) {
return Math.sqrt(1 - (t = t - 1) * t); return Math.sqrt(1 - (t -= 1) * t);
}, },
easeInOutCirc: function(t) { easeInOutCirc(t) {
if ((t /= 0.5) < 1) { if ((t /= 0.5) < 1) {
return -0.5 * (Math.sqrt(1 - t * t) - 1); return -0.5 * (Math.sqrt(1 - t * t) - 1);
} }
return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1); return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
}, },
easeInElastic: function(t) { easeInElastic(t) {
var s = 1.70158; let s = 1.70158;
var p = 0; let p = 0;
var a = 1; let a = 1;
if (t === 0) { if (t === 0) {
return 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)); return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
}, },
easeOutElastic: function(t) { easeOutElastic(t) {
var s = 1.70158; let s = 1.70158;
var p = 0; let p = 0;
var a = 1; let a = 1;
if (t === 0) { if (t === 0) {
return 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; return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
}, },
easeInOutElastic: function(t) { easeInOutElastic(t) {
var s = 1.70158; let s = 1.70158;
var p = 0; let p = 0;
var a = 1; let a = 1;
if (t === 0) { if (t === 0) {
return 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; return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
}, },
easeInBack: function(t) { easeInBack(t) {
var s = 1.70158; const s = 1.70158;
return t * t * ((s + 1) * t - s); return t * t * ((s + 1) * t - s);
}, },
easeOutBack: function(t) { easeOutBack(t) {
var s = 1.70158; const s = 1.70158;
return (t = t - 1) * t * ((s + 1) * t + s) + 1; return (t -= 1) * t * ((s + 1) * t + s) + 1;
}, },
easeInOutBack: function(t) { easeInOutBack(t) {
var s = 1.70158; let s = 1.70158;
if ((t /= 0.5) < 1) { if ((t /= 0.5) < 1) {
return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s)); return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
} }
return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2); return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
}, },
easeInBounce: function(t) { easeInBounce(t) {
return 1 - effects.easeOutBounce(1 - t); return 1 - effects.easeOutBounce(1 - t);
}, },
easeOutBounce: function(t) { easeOutBounce(t) {
if (t < (1 / 2.75)) { if (t < (1 / 2.75)) {
return 7.5625 * t * t; return 7.5625 * t * t;
} }
@ -224,10 +222,12 @@ export const effects = {
return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375; return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
}, },
easeInOutBounce: function(t) { easeInOutBounce(t) {
if (t < 0.5) { if (t < 0.5) {
return effects.easeInBounce(t * 2) * 0.5; return effects.easeInBounce(t * 2) * 0.5;
} }
return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5; return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
} }
}; };
export default effects;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,8 +2,11 @@ parserOptions:
ecmaVersion: 6 ecmaVersion: 6
env: env:
es6: true # also changes default ecmaVersion to 6 es6: true
jasmine: true jasmine: true
commonjs: true
es2017: false
es2020: false
globals: globals:
acquireChart: true acquireChart: true
@ -16,4 +19,19 @@ globals:
rules: rules:
# Best Practices # Best Practices
complexity: 0 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