language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
chartjs
Chart.js
52b9793ba0c5155e599b5e03e1d66638ad68de04.json
Use HTTPS instead of HTTP for URLs supporting it
src/platforms/platform.dom.js
@@ -305,7 +305,7 @@ function removeResizeListener(node) { } function injectCSS(platform, css) { - // http://stackoverflow.com/q/3922139 + // https://stackoverflow.com/q/3922139 var style = platform._style || document.createElement('style'); if (!platform._style) { platform._style = style;
true
Other
chartjs
Chart.js
52b9793ba0c5155e599b5e03e1d66638ad68de04.json
Use HTTPS instead of HTTP for URLs supporting it
src/scales/scale.linearbase.js
@@ -12,7 +12,7 @@ var Scale = require('../core/core.scale'); function generateTicks(generationOptions, dataRange) { var ticks = []; // To get a "nice" value for the tick spacing, we will use the appropriately named - // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks + // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks // for details. var stepSize = generationOptions.stepSize;
true
Other
chartjs
Chart.js
52b9793ba0c5155e599b5e03e1d66638ad68de04.json
Use HTTPS instead of HTTP for URLs supporting it
src/scales/scale.time.js
@@ -130,7 +130,7 @@ function buildLookupTable(timestamps, min, max, distribution) { return table; } -// @see adapted from http://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/ +// @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/ function lookup(table, key, value) { var lo = 0; var hi = table.length - 1; @@ -179,7 +179,7 @@ function interpolate(table, skey, sval, tkey) { /** * Convert the given value to a moment object using the given time options. - * @see http://momentjs.com/docs/#/parsing/ + * @see https://momentjs.com/docs/#/parsing/ */ function momentify(value, options) { var parser = options.parser; @@ -448,15 +448,15 @@ module.exports = function() { bounds: 'data', time: { - parser: false, // false == a pattern string from http://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment - format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/ + parser: false, // false == a pattern string from https://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment + format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from https://momentjs.com/docs/#/parsing/string-format/ unit: false, // false == automatic or override with week, month, year, etc. round: false, // none, or override with week, month, year, etc. displayFormat: false, // DEPRECATED - isoWeekday: false, // override week start day - see http://momentjs.com/docs/#/get-set/iso-weekday/ + isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/ minUnit: 'millisecond', - // defaults to unit's corresponding unitFormat below or override using pattern string from http://momentjs.com/docs/#/displaying/format/ + // defaults to unit's corresponding unitFormat below or override using pattern string from https://momentjs.com/docs/#/displaying/format/ displayFormats: { millisecond: 'h:mm:ss.SSS a', // 11:20:01.123 AM, second: 'h:mm:ss a', // 11:20:01 AM
true
Other
chartjs
Chart.js
52b9793ba0c5155e599b5e03e1d66638ad68de04.json
Use HTTPS instead of HTTP for URLs supporting it
test/.eslintrc.yml
@@ -7,7 +7,7 @@ globals: moment: true waitForResize: true -# http://eslint.org/docs/rules/ +# https://eslint.org/docs/rules/ rules: # Best Practices complexity: 0
true
Other
chartjs
Chart.js
52b9793ba0c5155e599b5e03e1d66638ad68de04.json
Use HTTPS instead of HTTP for URLs supporting it
test/context.js
@@ -1,4 +1,4 @@ -// Code from http://stackoverflow.com/questions/4406864/html-canvas-unit-testing +// Code from https://stackoverflow.com/questions/4406864/html-canvas-unit-testing var Context = function() { this._calls = []; // names/args of recorded calls this._initMethods();
true
Other
chartjs
Chart.js
52b9793ba0c5155e599b5e03e1d66638ad68de04.json
Use HTTPS instead of HTTP for URLs supporting it
test/specs/core.layouts.tests.js
@@ -11,7 +11,7 @@ describe('Chart.layouts', function() { // Disable tests which need to be rewritten based on changes introduced by // the following changes: https://github.com/chartjs/Chart.js/pull/2346 - // using xit marks the test as pending: http://jasmine.github.io/2.0/introduction.html#section-Pending_Specs + // using xit marks the test as pending: https://jasmine.github.io/2.0/introduction.html#section-Pending_Specs xit('should fit a simple chart with 2 scales', function() { var chart = window.acquireChart({ type: 'bar',
true
Other
chartjs
Chart.js
52b9793ba0c5155e599b5e03e1d66638ad68de04.json
Use HTTPS instead of HTTP for URLs supporting it
test/specs/plugin.legend.tests.js
@@ -217,7 +217,7 @@ describe('Legend block tests', function() { // NOTE(SB) We should get ride of the following tests and use image diff instead. // For now, as discussed with Evert Timberg, simply comment out. - // See http://humblesoftware.github.io/js-imagediff/test.html + // See https://humblesoftware.github.io/js-imagediff/test.html /* chart.legend.ctx = window.createMockContext(); chart.update();
true
Other
chartjs
Chart.js
52b9793ba0c5155e599b5e03e1d66638ad68de04.json
Use HTTPS instead of HTTP for URLs supporting it
test/utils.js
@@ -85,7 +85,7 @@ function releaseChart(chart) { } function injectCSS(css) { - // http://stackoverflow.com/q/3922139 + // https://stackoverflow.com/q/3922139 var head = document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.setAttribute('type', 'text/css');
true
Other
chartjs
Chart.js
3a29b99e3b24e4d7dbfcb22df5e1f98ba9a0be4b.json
Use HTTPS in documentation links where possible (#5915)
docs/README.md
@@ -58,8 +58,8 @@ var myChart = new Chart(ctx, { Before submitting an issue or a pull request to the project, please take a moment to look over the [contributing guidelines](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md) first. -For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](http://stackoverflow.com/questions/tagged/chartjs). +For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](https://stackoverflow.com/questions/tagged/chartjs). ## License -Chart.js is available under the [MIT license](http://opensource.org/licenses/MIT). +Chart.js is available under the [MIT license](https://opensource.org/licenses/MIT).
true
Other
chartjs
Chart.js
3a29b99e3b24e4d7dbfcb22df5e1f98ba9a0be4b.json
Use HTTPS in documentation links where possible (#5915)
docs/axes/cartesian/time.md
@@ -19,7 +19,7 @@ The x-axis data points may additionally be specified via the `t` or `x` attribut ### Date Formats -When providing data for the time scale, Chart.js supports all of the formats that Moment.js accepts. See [Moment.js docs](http://momentjs.com/docs/#/parsing/) for details. +When providing data for the time scale, Chart.js supports all of the formats that Moment.js accepts. See [Moment.js docs](https://momentjs.com/docs/#/parsing/) for details. ## Configuration Options @@ -75,7 +75,7 @@ var chart = new Chart(ctx, { ``` ### Display Formats -The following display formats are used to configure how different time units are formed into strings for the axis tick marks. See [moment.js](http://momentjs.com/docs/#/displaying/format/) for the allowable format strings. +The following display formats are used to configure how different time units are formed into strings for the axis tick marks. See [moment.js](https://momentjs.com/docs/#/displaying/format/) for the allowable format strings. Name | Default | Example --- | --- | ---
true
Other
chartjs
Chart.js
3a29b99e3b24e4d7dbfcb22df5e1f98ba9a0be4b.json
Use HTTPS in documentation links where possible (#5915)
docs/charts/line.md
@@ -162,7 +162,7 @@ When charting a lot of data, the chart render time may start to get quite large. Decimating your data will achieve the best results. When there is a lot of data to display on the graph, it doesn't make sense to show tens of thousands of data points on a graph that is only a few hundred pixels wide. -There are many approaches to data decimation and selection of an algorithm will depend on your data and the results you want to achieve. For instance, [min/max](http://digital.ni.com/public.nsf/allkb/F694FFEEA0ACF282862576020075F784) decimation will preserve peaks in your data but could require up to 4 points for each pixel. This type of decimation would work well for a very noisy signal where you need to see data peaks. +There are many approaches to data decimation and selection of an algorithm will depend on your data and the results you want to achieve. For instance, [min/max](https://digital.ni.com/public.nsf/allkb/F694FFEEA0ACF282862576020075F784) decimation will preserve peaks in your data but could require up to 4 points for each pixel. This type of decimation would work well for a very noisy signal where you need to see data peaks. ## Disable Bezier Curves
true
Other
chartjs
Chart.js
3a29b99e3b24e4d7dbfcb22df5e1f98ba9a0be4b.json
Use HTTPS in documentation links where possible (#5915)
docs/configuration/tooltip.md
@@ -269,7 +269,7 @@ var myPieChart = new Chart(ctx, { }); ``` -See [samples](http://www.chartjs.org/samples/) for examples on how to get started with custom tooltips. +See [samples](https://www.chartjs.org/samples/) for examples on how to get started with custom tooltips. ## Tooltip Model The tooltip model contains parameters that can be used to render the tooltip.
true
Other
chartjs
Chart.js
3a29b99e3b24e4d7dbfcb22df5e1f98ba9a0be4b.json
Use HTTPS in documentation links where possible (#5915)
docs/developers/README.md
@@ -6,15 +6,15 @@ Developer features allow extending and enhancing Chart.js in many different ways Latest documentation and samples, including unreleased features, are available at: - - http://www.chartjs.org/docs/master/ - - http://www.chartjs.org/samples/master/ + - https://www.chartjs.org/docs/master/ + - https://www.chartjs.org/samples/master/ # Development releases Latest builds are available for testing at: - - http://www.chartjs.org/dist/master/Chart.min.js - - http://www.chartjs.org/dist/master/Chart.bundle.min.js + - https://www.chartjs.org/dist/master/Chart.min.js + - https://www.chartjs.org/dist/master/Chart.bundle.min.js > Note: Development builds are currently only available via HTTP, so in order to include them in [JSFiddle](http://jsfiddle.net) or [CodePen](http://codepen.io), you need to access these tools via HTTP as well. @@ -29,7 +29,7 @@ Chart.js offers support for the following browsers: * Edge 14+ * Safari 9+ -Browser support for the canvas element is available in all modern & major mobile browsers. [CanIUse](http://caniuse.com/#feat=canvas) +Browser support for the canvas element is available in all modern & major mobile browsers. [CanIUse](https://caniuse.com/#feat=canvas) Thanks to [BrowserStack](https://browserstack.com) for allowing our team to test on thousands of browsers. @@ -39,7 +39,7 @@ Version 2 has a completely different API than earlier versions. Most earlier version options have current equivalents or are the same. -Please use the documentation that is available on [chartjs.org](http://www.chartjs.org/docs/) for the current version of Chart.js. +Please use the documentation that is available on [chartjs.org](https://www.chartjs.org/docs/) for the current version of Chart.js. Please note - documentation for previous versions are available on the GitHub repo.
true
Other
chartjs
Chart.js
3a29b99e3b24e4d7dbfcb22df5e1f98ba9a0be4b.json
Use HTTPS in documentation links where possible (#5915)
docs/developers/contributing.md
@@ -16,7 +16,7 @@ New contributions to the library are welcome, but we ask that you please follow # Building and Testing -Chart.js uses <a href="http://gulpjs.com/" target="_blank">gulp</a> to build the library into a single JavaScript file. +Chart.js uses <a href="https://gulpjs.com/" target="_blank">gulp</a> to build the library into a single JavaScript file. Firstly, we need to ensure development dependencies are installed. With node and npm installed, after cloning the Chart.js repo to a local directory, and navigating to that directory in the command line, we can run the following: @@ -25,7 +25,7 @@ Firstly, we need to ensure development dependencies are installed. With node and > npm install -g gulp ``` -This will install the local development dependencies for Chart.js, along with a CLI for the JavaScript task runner <a href="http://gulpjs.com/" target="_blank">gulp</a>. +This will install the local development dependencies for Chart.js, along with a CLI for the JavaScript task runner <a href="https://gulpjs.com/" target="_blank">gulp</a>. The following commands are now available from the repository root: @@ -45,14 +45,14 @@ More information can be found in [gulpfile.js](https://github.com/chartjs/Chart. # Bugs and Issues -Please report these on the GitHub page - at <a href="https://github.com/chartjs/Chart.js" target="_blank">github.com/chartjs/Chart.js</a>. Please do not use issues for support requests. For help using Chart.js, please take a look at the [`chartjs`](http://stackoverflow.com/questions/tagged/chartjs) tag on Stack Overflow. +Please report these on the GitHub page - at <a href="https://github.com/chartjs/Chart.js" target="_blank">github.com/chartjs/Chart.js</a>. Please do not use issues for support requests. For help using Chart.js, please take a look at the [`chartjs`](https://stackoverflow.com/questions/tagged/chartjs) tag on Stack Overflow. Well structured, detailed bug reports are hugely valuable for the project. Guidelines for reporting bugs: - Check the issue search to see if it has already been reported - Isolate the problem to a simple test case - - Please include a demonstration of the bug on a website such as [JS Bin](http://jsbin.com/), [JS Fiddle](http://jsfiddle.net/), or [Codepen](http://codepen.io/pen/). ([Template](http://codepen.io/pen?template=JXVYzq)) + - Please include a demonstration of the bug on a website such as [JS Bin](https://jsbin.com/), [JS Fiddle](https://jsfiddle.net/), or [Codepen](https://codepen.io/pen/). ([Template](https://codepen.io/pen?template=JXVYzq)) Please provide any additional details associated with the bug, if it's browser or screen density specific, or only happens with a certain configuration or data.
true
Other
chartjs
Chart.js
3a29b99e3b24e4d7dbfcb22df5e1f98ba9a0be4b.json
Use HTTPS in documentation links where possible (#5915)
docs/getting-started/installation.md
@@ -27,7 +27,7 @@ https://cdnjs.com/libraries/Chart.js ### jsDelivr [![jsdelivr](https://img.shields.io/npm/v/chart.js.svg?label=jsdelivr&style=flat-square&maxAge=600)](https://cdn.jsdelivr.net/npm/chart.js@latest/dist/) [![jsdelivr hits](https://data.jsdelivr.com/v1/package/npm/chart.js/badge)](https://www.jsdelivr.com/package/npm/chart.js) -Chart.js built files are also available through [jsDelivr](http://www.jsdelivr.com/): +Chart.js built files are also available through [jsDelivr](https://www.jsdelivr.com/): https://www.jsdelivr.com/package/npm/chart.js?path=dist @@ -47,7 +47,7 @@ Files: * `dist/Chart.js` * `dist/Chart.min.js` -The stand-alone build includes Chart.js as well as the color parsing library. If this version is used, you are required to include [Moment.js](http://momentjs.com/) before Chart.js for the functionality of the time axis. +The stand-alone build includes Chart.js as well as the color parsing library. If this version is used, you are required to include [Moment.js](https://momentjs.com/) before Chart.js for the functionality of the time axis. ## Bundled Build Files:
true
Other
chartjs
Chart.js
3a29b99e3b24e4d7dbfcb22df5e1f98ba9a0be4b.json
Use HTTPS in documentation links where possible (#5915)
docs/notes/license.md
@@ -1,3 +1,3 @@ # License -Chart.js is <a href="https://github.com/chartjs/Chart.js" target="_blank">open source</a> and available under the <a href="http://opensource.org/licenses/MIT" target="_blank">MIT license</a>. \ No newline at end of file +Chart.js is <a href="https://github.com/chartjs/Chart.js" target="_blank">open source</a> and available under the <a href="https://opensource.org/licenses/MIT" target="_blank">MIT license</a>. \ No newline at end of file
true
Other
chartjs
Chart.js
69fcba029b32fd2a290f6356cd857b8c2d6809e3.json
Remove autoSkip logic to always display last tick (#5891) This changes the behavior of `autoSkip` so that it does not force the display of the last tick. If the last tick can be displayed with equal spacing to the rest of the ticks, it will be. Otherwise, it is not.
src/core/core.scale.js
@@ -644,7 +644,7 @@ module.exports = Element.extend({ var cosRotation = Math.cos(labelRotationRadians); var longestRotatedLabel = me.longestLabelWidth * cosRotation; var result = []; - var i, tick, shouldSkip; + var i, tick; // figure out the maximum number of gridlines to show var maxTicks; @@ -669,9 +669,7 @@ module.exports = Element.extend({ for (i = 0; i < tickCount; i++) { tick = ticks[i]; - // Since we always show the last tick,we need may need to hide the last shown one before - shouldSkip = (skipRatio > 1 && i % skipRatio > 0) || (i % skipRatio === 0 && i + skipRatio >= tickCount); - if (shouldSkip && i !== tickCount - 1) { + if (skipRatio > 1 && i % skipRatio > 0) { // leave tick in place but make sure it's not displayed (#4635) delete tick.label; }
true
Other
chartjs
Chart.js
69fcba029b32fd2a290f6356cd857b8c2d6809e3.json
Remove autoSkip logic to always display last tick (#5891) This changes the behavior of `autoSkip` so that it does not force the display of the last tick. If the last tick can be displayed with equal spacing to the rest of the ticks, it will be. Otherwise, it is not.
test/specs/core.scale.tests.js
@@ -20,6 +20,60 @@ describe('Core.scale', function() { }); }); + describe('displaying xAxis ticks with autoSkip=true', function() { + function getChart(data) { + return window.acquireChart({ + type: 'line', + data: data, + options: { + scales: { + xAxes: [{ + ticks: { + autoSkip: true + } + }] + } + } + }); + } + + function lastTick(chart) { + var xAxis = chart.scales['x-axis-0']; + var ticks = xAxis.getTicks(); + return ticks[ticks.length - 1]; + } + + it('should display the last tick if it fits evenly with other ticks', function() { + var chart = getChart({ + labels: [ + 'January 2018', 'February 2018', 'March 2018', 'April 2018', + 'May 2018', 'June 2018', 'July 2018', 'August 2018', + 'September 2018' + ], + datasets: [{ + data: [12, 19, 3, 5, 2, 3, 7, 8, 9] + }] + }); + + expect(lastTick(chart).label).toEqual('September 2018'); + }); + + it('should not display the last tick if it does not fit evenly', function() { + var chart = getChart({ + labels: [ + 'January 2018', 'February 2018', 'March 2018', 'April 2018', + 'May 2018', 'June 2018', 'July 2018', 'August 2018', + 'September 2018', 'October 2018', 'November 2018', 'December 2018' + ], + datasets: [{ + data: [12, 19, 3, 5, 2, 3, 7, 8, 9, 10, 11, 12] + }] + }); + + expect(lastTick(chart).label).toBeUndefined(); + }); + }); + var gridLineTests = [{ labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'], offsetGridLines: false,
true
Other
chartjs
Chart.js
bfa635e55d6e494d9d032729c1475d6339e61d21.json
Fix docs about bar chart indexable options (#5876)
docs/charts/bar.md
@@ -73,9 +73,9 @@ the color of the bars is generally set this way. | [`borderSkipped`](#borderskipped) | `String` | Yes | Yes | `'bottom'` | [`borderWidth`](#styling) | `Number` | Yes | Yes | `0` | [`data`](#data-structure) | `Object[]` | - | - | **required** -| [`hoverBackgroundColor`](#interactions) | [`Color`](../general/colors.md) | - | - | `undefined` -| [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | - | - | `undefined` -| [`hoverBorderWidth`](#interactions) | `Number` | - | - | `1` +| [`hoverBackgroundColor`](#interactions) | [`Color`](../general/colors.md) | - | Yes | `undefined` +| [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | - | Yes | `undefined` +| [`hoverBorderWidth`](#interactions) | `Number` | - | Yes | `1` | [`label`](#general) | `String` | - | - | `''` | [`xAxisID`](#general) | `String` | - | - | first x axis | [`yAxisID`](#general) | `String` | - | - | first y axis
false
Other
chartjs
Chart.js
3cb2d7050e0976f92383beb48bee07e5d579a2c0.json
Remove gulp-connect and add jsdelivr/unpkg paths (#5875)
.travis.yml
@@ -1,6 +1,6 @@ language: node_js node_js: - - "6" + - lts/* before_install: - "export CHROME_BIN=/usr/bin/google-chrome"
true
Other
chartjs
Chart.js
3cb2d7050e0976f92383beb48bee07e5d579a2c0.json
Remove gulp-connect and add jsdelivr/unpkg paths (#5875)
gulpfile.js
@@ -1,6 +1,5 @@ var gulp = require('gulp'); var concat = require('gulp-concat'); -var connect = require('gulp-connect'); var eslint = require('gulp-eslint'); var file = require('gulp-file'); var insert = require('gulp-insert'); @@ -26,7 +25,7 @@ var argv = yargs .option('force-output', {default: false}) .option('silent-errors', {default: false}) .option('verbose', {default: false}) - .argv + .argv; var srcDir = './src/'; var outDir = './dist/'; @@ -53,15 +52,12 @@ gulp.task('lint-html', lintHtmlTask); gulp.task('lint-js', lintJsTask); gulp.task('lint', gulp.parallel('lint-html', 'lint-js')); gulp.task('docs', docsTask); -gulp.task('server', serverTask); gulp.task('unittest', unittestTask); gulp.task('test', gulp.parallel('lint', 'unittest')); gulp.task('library-size', librarySizeTask); gulp.task('module-sizes', moduleSizesTask); gulp.task('size', gulp.parallel('library-size', 'module-sizes')); -gulp.task('_open', _openTask); gulp.task('default', gulp.parallel('build', 'watch')); -gulp.task('dev', gulp.parallel('server', 'default')); /** * Generates the bower.json manifest file which will be pushed along release tags. @@ -136,7 +132,6 @@ function buildTask() { .pipe(gulp.dest(outDir)); return merge(bundled, nonBundled); - } function packageTask() { @@ -235,16 +230,3 @@ function moduleSizesTask() { function watchTask() { return gulp.watch('./src/**', gulp.parallel('build')); } - -function serverTask() { - connect.server({ - port: 8000 - }); -} - -// Convenience task for opening the project straight from the command line - -function _openTask() { - exec('open http://localhost:8000'); - exec('subl .'); -}
true
Other
chartjs
Chart.js
3cb2d7050e0976f92383beb48bee07e5d579a2c0.json
Remove gulp-connect and add jsdelivr/unpkg paths (#5875)
package.json
@@ -1,14 +1,27 @@ { "name": "chart.js", - "homepage": "http://www.chartjs.org", + "homepage": "https://www.chartjs.org", "description": "Simple HTML5 charts using the canvas element.", "version": "2.7.3", "license": "MIT", + "jsdelivr": "dist/Chart.min.js", + "unpkg": "dist/Chart.min.js", "main": "src/chart.js", + "keywords": [ + "canvas", + "charts", + "data", + "graphs", + "html5", + "responsive" + ], "repository": { "type": "git", "url": "https://github.com/chartjs/Chart.js.git" }, + "bugs": { + "url": "https://github.com/chartjs/Chart.js/issues" + }, "devDependencies": { "browserify": "^16.2.3", "browserify-istanbul": "^3.0.1", @@ -21,7 +34,6 @@ "gitbook-cli": "^2.3.2", "gulp": "^4.0.0", "gulp-concat": "^2.6.0", - "gulp-connect": "^5.6.1", "gulp-eslint": "^5.0.0", "gulp-file": "^0.4.0", "gulp-htmllint": "^0.0.16", @@ -39,16 +51,13 @@ "karma-chrome-launcher": "^2.2.0", "karma-coverage": "^1.1.1", "karma-firefox-launcher": "^1.0.1", - "karma-jasmine": "^2.0.0", + "karma-jasmine": "^2.0.1", "karma-jasmine-html-reporter": "^1.4.0", "merge-stream": "^1.0.1", "pixelmatch": "^4.0.2", "vinyl-source-stream": "^2.0.0", "watchify": "^3.9.0", - "yargs": "^12.0.2" - }, - "spm": { - "main": "Chart.js" + "yargs": "^12.0.5" }, "dependencies": { "chartjs-color": "^2.1.0",
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/chart.js
@@ -10,6 +10,8 @@ require('./core/core.helpers')(Chart); Chart.Animation = require('./core/core.animation'); Chart.animationService = require('./core/core.animations'); +Chart.controllers = require('./controllers/index'); +Chart.DatasetController = require('./core/core.datasetController'); Chart.defaults = require('./core/core.defaults'); Chart.Element = require('./core/core.element'); Chart.elements = require('./elements/index'); @@ -23,7 +25,6 @@ Chart.Ticks = require('./core/core.ticks'); Chart.Tooltip = require('./core/core.tooltip'); require('./core/core.controller')(Chart); -require('./core/core.datasetController')(Chart); require('./scales/scale.linearbase')(Chart); require('./scales/scale.category')(Chart); @@ -32,16 +33,6 @@ require('./scales/scale.logarithmic')(Chart); require('./scales/scale.radialLinear')(Chart); require('./scales/scale.time')(Chart); -// Controllers must be loaded after elements -// See Chart.core.datasetController.dataElementType -require('./controllers/controller.bar')(Chart); -require('./controllers/controller.bubble')(Chart); -require('./controllers/controller.doughnut')(Chart); -require('./controllers/controller.line')(Chart); -require('./controllers/controller.polarArea')(Chart); -require('./controllers/controller.radar')(Chart); -require('./controllers/controller.scatter')(Chart); - // Loading built-in plugins var plugins = require('./plugins'); for (var k in plugins) {
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/controllers/controller.bar.js
@@ -1,5 +1,6 @@ 'use strict'; +var DatasetController = require('../core/core.datasetController'); var defaults = require('../core/core.defaults'); var elements = require('../elements/index'); var helpers = require('../helpers/index'); @@ -12,15 +13,9 @@ defaults._set('bar', { scales: { xAxes: [{ type: 'category', - - // Specific to Bar Controller categoryPercentage: 0.8, barPercentage: 0.9, - - // offset settings offset: true, - - // grid line settings gridLines: { offsetGridLines: true } @@ -32,69 +27,6 @@ defaults._set('bar', { } }); -defaults._set('horizontalBar', { - hover: { - mode: 'index', - axis: 'y' - }, - - scales: { - xAxes: [{ - type: 'linear', - position: 'bottom' - }], - - yAxes: [{ - position: 'left', - type: 'category', - - // Specific to Horizontal Bar Controller - categoryPercentage: 0.8, - barPercentage: 0.9, - - // offset settings - offset: true, - - // grid line settings - gridLines: { - offsetGridLines: true - } - }] - }, - - elements: { - rectangle: { - borderSkipped: 'left' - } - }, - - tooltips: { - callbacks: { - title: function(item, data) { - // Pick first xLabel for now - var title = ''; - - if (item.length > 0) { - if (item[0].yLabel) { - title = item[0].yLabel; - } else if (data.labels.length > 0 && item[0].index < data.labels.length) { - title = data.labels[item[0].index]; - } - } - - return title; - }, - - label: function(item, data) { - var datasetLabel = data.datasets[item.datasetIndex].label || ''; - return datasetLabel + ': ' + item.xLabel; - } - }, - mode: 'index', - axis: 'y' - } -}); - /** * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap. * @private @@ -182,349 +114,330 @@ function computeFlexCategoryTraits(index, ruler, options) { }; } -module.exports = function(Chart) { +module.exports = DatasetController.extend({ - Chart.controllers.bar = Chart.DatasetController.extend({ + dataElementType: elements.Rectangle, - dataElementType: elements.Rectangle, + initialize: function() { + var me = this; + var meta; - initialize: function() { - var me = this; - var meta; + DatasetController.prototype.initialize.apply(me, arguments); - Chart.DatasetController.prototype.initialize.apply(me, arguments); + meta = me.getMeta(); + meta.stack = me.getDataset().stack; + meta.bar = true; + }, - meta = me.getMeta(); - meta.stack = me.getDataset().stack; - meta.bar = true; - }, + update: function(reset) { + var me = this; + var rects = me.getMeta().data; + var i, ilen; - update: function(reset) { - var me = this; - var rects = me.getMeta().data; - var i, ilen; + me._ruler = me.getRuler(); - me._ruler = me.getRuler(); + for (i = 0, ilen = rects.length; i < ilen; ++i) { + me.updateElement(rects[i], i, reset); + } + }, - for (i = 0, ilen = rects.length; i < ilen; ++i) { - me.updateElement(rects[i], i, reset); - } - }, - - updateElement: function(rectangle, index, reset) { - var me = this; - var meta = me.getMeta(); - var dataset = me.getDataset(); - var options = me._resolveElementOptions(rectangle, index); - - rectangle._xScale = me.getScaleForId(meta.xAxisID); - rectangle._yScale = me.getScaleForId(meta.yAxisID); - rectangle._datasetIndex = me.index; - rectangle._index = index; - rectangle._model = { - backgroundColor: options.backgroundColor, - borderColor: options.borderColor, - borderSkipped: options.borderSkipped, - borderWidth: options.borderWidth, - datasetLabel: dataset.label, - label: me.chart.data.labels[index] - }; - - me._updateElementGeometry(rectangle, index, reset); - - rectangle.pivot(); - }, - - /** - * @private - */ - _updateElementGeometry: function(rectangle, index, reset) { - var me = this; - var model = rectangle._model; - var vscale = me.getValueScale(); - var base = vscale.getBasePixel(); - var horizontal = vscale.isHorizontal(); - var ruler = me._ruler || me.getRuler(); - var vpixels = me.calculateBarValuePixels(me.index, index); - var ipixels = me.calculateBarIndexPixels(me.index, index, ruler); - - model.horizontal = horizontal; - model.base = reset ? base : vpixels.base; - model.x = horizontal ? reset ? base : vpixels.head : ipixels.center; - model.y = horizontal ? ipixels.center : reset ? base : vpixels.head; - model.height = horizontal ? ipixels.size : undefined; - model.width = horizontal ? undefined : ipixels.size; - }, - - /** - * @private - */ - getValueScaleId: function() { - return this.getMeta().yAxisID; - }, - - /** - * @private - */ - getIndexScaleId: function() { - return this.getMeta().xAxisID; - }, - - /** - * @private - */ - getValueScale: function() { - return this.getScaleForId(this.getValueScaleId()); - }, - - /** - * @private - */ - getIndexScale: function() { - return this.getScaleForId(this.getIndexScaleId()); - }, - - /** - * Returns the stacks based on groups and bar visibility. - * @param {Number} [last] - The dataset index - * @returns {Array} The stack list - * @private - */ - _getStacks: function(last) { - var me = this; - var chart = me.chart; - var scale = me.getIndexScale(); - var stacked = scale.options.stacked; - var ilen = last === undefined ? chart.data.datasets.length : last + 1; - var stacks = []; - var i, meta; - - for (i = 0; i < ilen; ++i) { - meta = chart.getDatasetMeta(i); - if (meta.bar && chart.isDatasetVisible(i) && - (stacked === false || - (stacked === true && stacks.indexOf(meta.stack) === -1) || - (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) { - stacks.push(meta.stack); - } - } + updateElement: function(rectangle, index, reset) { + var me = this; + var meta = me.getMeta(); + var dataset = me.getDataset(); + var options = me._resolveElementOptions(rectangle, index); + + rectangle._xScale = me.getScaleForId(meta.xAxisID); + rectangle._yScale = me.getScaleForId(meta.yAxisID); + rectangle._datasetIndex = me.index; + rectangle._index = index; + rectangle._model = { + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderSkipped: options.borderSkipped, + borderWidth: options.borderWidth, + datasetLabel: dataset.label, + label: me.chart.data.labels[index] + }; + + me._updateElementGeometry(rectangle, index, reset); + + rectangle.pivot(); + }, + + /** + * @private + */ + _updateElementGeometry: function(rectangle, index, reset) { + var me = this; + var model = rectangle._model; + var vscale = me.getValueScale(); + var base = vscale.getBasePixel(); + var horizontal = vscale.isHorizontal(); + var ruler = me._ruler || me.getRuler(); + var vpixels = me.calculateBarValuePixels(me.index, index); + var ipixels = me.calculateBarIndexPixels(me.index, index, ruler); + + model.horizontal = horizontal; + model.base = reset ? base : vpixels.base; + model.x = horizontal ? reset ? base : vpixels.head : ipixels.center; + model.y = horizontal ? ipixels.center : reset ? base : vpixels.head; + model.height = horizontal ? ipixels.size : undefined; + model.width = horizontal ? undefined : ipixels.size; + }, + + /** + * @private + */ + getValueScaleId: function() { + return this.getMeta().yAxisID; + }, + + /** + * @private + */ + getIndexScaleId: function() { + return this.getMeta().xAxisID; + }, + + /** + * @private + */ + getValueScale: function() { + return this.getScaleForId(this.getValueScaleId()); + }, - return stacks; - }, - - /** - * Returns the effective number of stacks based on groups and bar visibility. - * @private - */ - getStackCount: function() { - return this._getStacks().length; - }, - - /** - * Returns the stack index for the given dataset based on groups and bar visibility. - * @param {Number} [datasetIndex] - The dataset index - * @param {String} [name] - The stack name to find - * @returns {Number} The stack index - * @private - */ - getStackIndex: function(datasetIndex, name) { - var stacks = this._getStacks(datasetIndex); - var index = (name !== undefined) - ? stacks.indexOf(name) - : -1; // indexOf returns -1 if element is not present - - return (index === -1) - ? stacks.length - 1 - : index; - }, - - /** - * @private - */ - getRuler: function() { - var me = this; - var scale = me.getIndexScale(); - var stackCount = me.getStackCount(); - var datasetIndex = me.index; - var isHorizontal = scale.isHorizontal(); - var start = isHorizontal ? scale.left : scale.top; - var end = start + (isHorizontal ? scale.width : scale.height); - var pixels = []; - var i, ilen, min; - - for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) { - pixels.push(scale.getPixelForValue(null, i, datasetIndex)); + /** + * @private + */ + getIndexScale: function() { + return this.getScaleForId(this.getIndexScaleId()); + }, + + /** + * Returns the stacks based on groups and bar visibility. + * @param {Number} [last] - The dataset index + * @returns {Array} The stack list + * @private + */ + _getStacks: function(last) { + var me = this; + var chart = me.chart; + var scale = me.getIndexScale(); + var stacked = scale.options.stacked; + var ilen = last === undefined ? chart.data.datasets.length : last + 1; + var stacks = []; + var i, meta; + + for (i = 0; i < ilen; ++i) { + meta = chart.getDatasetMeta(i); + if (meta.bar && chart.isDatasetVisible(i) && + (stacked === false || + (stacked === true && stacks.indexOf(meta.stack) === -1) || + (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) { + stacks.push(meta.stack); } + } + + return stacks; + }, + + /** + * Returns the effective number of stacks based on groups and bar visibility. + * @private + */ + getStackCount: function() { + return this._getStacks().length; + }, + + /** + * Returns the stack index for the given dataset based on groups and bar visibility. + * @param {Number} [datasetIndex] - The dataset index + * @param {String} [name] - The stack name to find + * @returns {Number} The stack index + * @private + */ + getStackIndex: function(datasetIndex, name) { + var stacks = this._getStacks(datasetIndex); + var index = (name !== undefined) + ? stacks.indexOf(name) + : -1; // indexOf returns -1 if element is not present + + return (index === -1) + ? stacks.length - 1 + : index; + }, + + /** + * @private + */ + getRuler: function() { + var me = this; + var scale = me.getIndexScale(); + var stackCount = me.getStackCount(); + var datasetIndex = me.index; + var isHorizontal = scale.isHorizontal(); + var start = isHorizontal ? scale.left : scale.top; + var end = start + (isHorizontal ? scale.width : scale.height); + var pixels = []; + var i, ilen, min; + + for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) { + pixels.push(scale.getPixelForValue(null, i, datasetIndex)); + } + + min = helpers.isNullOrUndef(scale.options.barThickness) + ? computeMinSampleSize(scale, pixels) + : -1; + + return { + min: min, + pixels: pixels, + start: start, + end: end, + stackCount: stackCount, + scale: scale + }; + }, - min = helpers.isNullOrUndef(scale.options.barThickness) - ? computeMinSampleSize(scale, pixels) - : -1; - - return { - min: min, - pixels: pixels, - start: start, - end: end, - stackCount: stackCount, - scale: scale - }; - }, - - /** - * Note: pixel values are not clamped to the scale area. - * @private - */ - calculateBarValuePixels: function(datasetIndex, index) { - var me = this; - var chart = me.chart; - var meta = me.getMeta(); - var scale = me.getValueScale(); - var isHorizontal = scale.isHorizontal(); - var datasets = chart.data.datasets; - var value = scale.getRightValue(datasets[datasetIndex].data[index]); - var minBarLength = scale.options.minBarLength; - var stacked = scale.options.stacked; - var stack = meta.stack; - var start = 0; - var i, imeta, ivalue, base, head, size; - - if (stacked || (stacked === undefined && stack !== undefined)) { - for (i = 0; i < datasetIndex; ++i) { - imeta = chart.getDatasetMeta(i); - - if (imeta.bar && - imeta.stack === stack && - imeta.controller.getValueScaleId() === scale.id && - chart.isDatasetVisible(i)) { - - ivalue = scale.getRightValue(datasets[i].data[index]); - if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) { - start += ivalue; - } + /** + * Note: pixel values are not clamped to the scale area. + * @private + */ + calculateBarValuePixels: function(datasetIndex, index) { + var me = this; + var chart = me.chart; + var meta = me.getMeta(); + var scale = me.getValueScale(); + var isHorizontal = scale.isHorizontal(); + var datasets = chart.data.datasets; + var value = scale.getRightValue(datasets[datasetIndex].data[index]); + var minBarLength = scale.options.minBarLength; + var stacked = scale.options.stacked; + var stack = meta.stack; + var start = 0; + var i, imeta, ivalue, base, head, size; + + if (stacked || (stacked === undefined && stack !== undefined)) { + for (i = 0; i < datasetIndex; ++i) { + imeta = chart.getDatasetMeta(i); + + if (imeta.bar && + imeta.stack === stack && + imeta.controller.getValueScaleId() === scale.id && + chart.isDatasetVisible(i)) { + + ivalue = scale.getRightValue(datasets[i].data[index]); + if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) { + start += ivalue; } } } + } - base = scale.getPixelForValue(start); - head = scale.getPixelForValue(start + value); - size = (head - base) / 2; + base = scale.getPixelForValue(start); + head = scale.getPixelForValue(start + value); + size = (head - base) / 2; - if (minBarLength !== undefined && Math.abs(size) < minBarLength) { - size = minBarLength; - if (value >= 0 && !isHorizontal || value < 0 && isHorizontal) { - head = base - minBarLength; - } else { - head = base + minBarLength; - } + if (minBarLength !== undefined && Math.abs(size) < minBarLength) { + size = minBarLength; + if (value >= 0 && !isHorizontal || value < 0 && isHorizontal) { + head = base - minBarLength; + } else { + head = base + minBarLength; } + } - return { - size: size, - base: base, - head: head, - center: head + size / 2 - }; - }, - - /** - * @private - */ - calculateBarIndexPixels: function(datasetIndex, index, ruler) { - var me = this; - var options = ruler.scale.options; - var range = options.barThickness === 'flex' - ? computeFlexCategoryTraits(index, ruler, options) - : computeFitCategoryTraits(index, ruler, options); - - var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack); - var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2); - var size = Math.min( - helpers.valueOrDefault(options.maxBarThickness, Infinity), - range.chunk * range.ratio); - - return { - base: center - size / 2, - head: center + size / 2, - center: center, - size: size - }; - }, - - draw: function() { - var me = this; - var chart = me.chart; - var scale = me.getValueScale(); - var rects = me.getMeta().data; - var dataset = me.getDataset(); - var ilen = rects.length; - var i = 0; - - helpers.canvas.clipArea(chart.ctx, chart.chartArea); - - for (; i < ilen; ++i) { - if (!isNaN(scale.getRightValue(dataset.data[i]))) { - rects[i].draw(); - } - } + return { + size: size, + base: base, + head: head, + center: head + size / 2 + }; + }, - helpers.canvas.unclipArea(chart.ctx); - }, - - /** - * @private - */ - _resolveElementOptions: function(rectangle, index) { - var me = this; - var chart = me.chart; - var datasets = chart.data.datasets; - var dataset = datasets[me.index]; - var custom = rectangle.custom || {}; - var options = chart.options.elements.rectangle; - var resolve = helpers.options.resolve; - var values = {}; - var i, ilen, key; - - // Scriptable options - var context = { - chart: chart, - dataIndex: index, - dataset: dataset, - datasetIndex: me.index - }; - - var keys = [ - 'backgroundColor', - 'borderColor', - 'borderSkipped', - 'borderWidth' - ]; - - for (i = 0, ilen = keys.length; i < ilen; ++i) { - key = keys[i]; - values[key] = resolve([ - custom[key], - dataset[key], - options[key] - ], context, index); - } + /** + * @private + */ + calculateBarIndexPixels: function(datasetIndex, index, ruler) { + var me = this; + var options = ruler.scale.options; + var range = options.barThickness === 'flex' + ? computeFlexCategoryTraits(index, ruler, options) + : computeFitCategoryTraits(index, ruler, options); + + var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack); + var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2); + var size = Math.min( + helpers.valueOrDefault(options.maxBarThickness, Infinity), + range.chunk * range.ratio); + + return { + base: center - size / 2, + head: center + size / 2, + center: center, + size: size + }; + }, + + draw: function() { + var me = this; + var chart = me.chart; + var scale = me.getValueScale(); + var rects = me.getMeta().data; + var dataset = me.getDataset(); + var ilen = rects.length; + var i = 0; + + helpers.canvas.clipArea(chart.ctx, chart.chartArea); - return values; + for (; i < ilen; ++i) { + if (!isNaN(scale.getRightValue(dataset.data[i]))) { + rects[i].draw(); + } } - }); - - Chart.controllers.horizontalBar = Chart.controllers.bar.extend({ - /** - * @private - */ - getValueScaleId: function() { - return this.getMeta().xAxisID; - }, - - /** - * @private - */ - getIndexScaleId: function() { - return this.getMeta().yAxisID; + + helpers.canvas.unclipArea(chart.ctx); + }, + + /** + * @private + */ + _resolveElementOptions: function(rectangle, index) { + var me = this; + var chart = me.chart; + var datasets = chart.data.datasets; + var dataset = datasets[me.index]; + var custom = rectangle.custom || {}; + var options = chart.options.elements.rectangle; + var resolve = helpers.options.resolve; + var values = {}; + var i, ilen, key; + + // Scriptable options + var context = { + chart: chart, + dataIndex: index, + dataset: dataset, + datasetIndex: me.index + }; + + var keys = [ + 'backgroundColor', + 'borderColor', + 'borderSkipped', + 'borderWidth' + ]; + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + values[key] = resolve([ + custom[key], + dataset[key], + options[key] + ], context, index); } - }); -}; + + return values; + } +});
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/controllers/controller.bubble.js
@@ -1,5 +1,6 @@ 'use strict'; +var DatasetController = require('../core/core.datasetController'); var defaults = require('../core/core.defaults'); var elements = require('../elements/index'); var helpers = require('../helpers/index'); @@ -37,140 +38,136 @@ defaults._set('bubble', { } }); +module.exports = DatasetController.extend({ + /** + * @protected + */ + dataElementType: elements.Point, + + /** + * @protected + */ + update: function(reset) { + var me = this; + var meta = me.getMeta(); + var points = meta.data; + + // Update Points + helpers.each(points, function(point, index) { + me.updateElement(point, index, reset); + }); + }, -module.exports = function(Chart) { - - Chart.controllers.bubble = Chart.DatasetController.extend({ - /** - * @protected - */ - dataElementType: elements.Point, - - /** - * @protected - */ - update: function(reset) { - var me = this; - var meta = me.getMeta(); - var points = meta.data; - - // Update Points - helpers.each(points, function(point, index) { - me.updateElement(point, index, reset); - }); - }, - - /** - * @protected - */ - updateElement: function(point, index, reset) { - var me = this; - var meta = me.getMeta(); - var custom = point.custom || {}; - var xScale = me.getScaleForId(meta.xAxisID); - var yScale = me.getScaleForId(meta.yAxisID); - var options = me._resolveElementOptions(point, index); - var data = me.getDataset().data[index]; - var dsIndex = me.index; - - var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex); - var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex); - - point._xScale = xScale; - point._yScale = yScale; - point._options = options; - point._datasetIndex = dsIndex; - point._index = index; - point._model = { - backgroundColor: options.backgroundColor, - borderColor: options.borderColor, - borderWidth: options.borderWidth, - hitRadius: options.hitRadius, - pointStyle: options.pointStyle, - rotation: options.rotation, - radius: reset ? 0 : options.radius, - skip: custom.skip || isNaN(x) || isNaN(y), - x: x, - y: y, - }; - - point.pivot(); - }, - - /** - * @protected - */ - setHoverStyle: function(point) { - var model = point._model; - var options = point._options; - - point.$previousStyle = { - backgroundColor: model.backgroundColor, - borderColor: model.borderColor, - borderWidth: model.borderWidth, - radius: model.radius - }; - - model.backgroundColor = helpers.valueOrDefault(options.hoverBackgroundColor, helpers.getHoverColor(options.backgroundColor)); - model.borderColor = helpers.valueOrDefault(options.hoverBorderColor, helpers.getHoverColor(options.borderColor)); - model.borderWidth = helpers.valueOrDefault(options.hoverBorderWidth, options.borderWidth); - model.radius = options.radius + options.hoverRadius; - }, - - /** - * @private - */ - _resolveElementOptions: function(point, index) { - var me = this; - var chart = me.chart; - var datasets = chart.data.datasets; - var dataset = datasets[me.index]; - var custom = point.custom || {}; - var options = chart.options.elements.point; - var resolve = helpers.options.resolve; - var data = dataset.data[index]; - var values = {}; - var i, ilen, key; - - // Scriptable options - var context = { - chart: chart, - dataIndex: index, - dataset: dataset, - datasetIndex: me.index - }; - - var keys = [ - 'backgroundColor', - 'borderColor', - 'borderWidth', - 'hoverBackgroundColor', - 'hoverBorderColor', - 'hoverBorderWidth', - 'hoverRadius', - 'hitRadius', - 'pointStyle', - 'rotation' - ]; - - for (i = 0, ilen = keys.length; i < ilen; ++i) { - key = keys[i]; - values[key] = resolve([ - custom[key], - dataset[key], - options[key] - ], context, index); - } + /** + * @protected + */ + updateElement: function(point, index, reset) { + var me = this; + var meta = me.getMeta(); + var custom = point.custom || {}; + var xScale = me.getScaleForId(meta.xAxisID); + var yScale = me.getScaleForId(meta.yAxisID); + var options = me._resolveElementOptions(point, index); + var data = me.getDataset().data[index]; + var dsIndex = me.index; + + var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex); + var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex); + + point._xScale = xScale; + point._yScale = yScale; + point._options = options; + point._datasetIndex = dsIndex; + point._index = index; + point._model = { + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderWidth: options.borderWidth, + hitRadius: options.hitRadius, + pointStyle: options.pointStyle, + rotation: options.rotation, + radius: reset ? 0 : options.radius, + skip: custom.skip || isNaN(x) || isNaN(y), + x: x, + y: y, + }; + + point.pivot(); + }, - // Custom radius resolution - values.radius = resolve([ - custom.radius, - data ? data.r : undefined, - dataset.radius, - options.radius - ], context, index); + /** + * @protected + */ + setHoverStyle: function(point) { + var model = point._model; + var options = point._options; + + point.$previousStyle = { + backgroundColor: model.backgroundColor, + borderColor: model.borderColor, + borderWidth: model.borderWidth, + radius: model.radius + }; + + model.backgroundColor = helpers.valueOrDefault(options.hoverBackgroundColor, helpers.getHoverColor(options.backgroundColor)); + model.borderColor = helpers.valueOrDefault(options.hoverBorderColor, helpers.getHoverColor(options.borderColor)); + model.borderWidth = helpers.valueOrDefault(options.hoverBorderWidth, options.borderWidth); + model.radius = options.radius + options.hoverRadius; + }, - return values; + /** + * @private + */ + _resolveElementOptions: function(point, index) { + var me = this; + var chart = me.chart; + var datasets = chart.data.datasets; + var dataset = datasets[me.index]; + var custom = point.custom || {}; + var options = chart.options.elements.point; + var resolve = helpers.options.resolve; + var data = dataset.data[index]; + var values = {}; + var i, ilen, key; + + // Scriptable options + var context = { + chart: chart, + dataIndex: index, + dataset: dataset, + datasetIndex: me.index + }; + + var keys = [ + 'backgroundColor', + 'borderColor', + 'borderWidth', + 'hoverBackgroundColor', + 'hoverBorderColor', + 'hoverBorderWidth', + 'hoverRadius', + 'hitRadius', + 'pointStyle', + 'rotation' + ]; + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + values[key] = resolve([ + custom[key], + dataset[key], + options[key] + ], context, index); } - }); -}; + + // Custom radius resolution + values.radius = resolve([ + custom.radius, + data ? data.r : undefined, + dataset.radius, + options.radius + ], context, index); + + return values; + } +});
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/controllers/controller.doughnut.js
@@ -1,5 +1,6 @@ 'use strict'; +var DatasetController = require('../core/core.datasetController'); var defaults = require('../core/core.defaults'); var elements = require('../elements/index'); var helpers = require('../helpers/index'); @@ -118,184 +119,176 @@ defaults._set('doughnut', { } }); -defaults._set('pie', helpers.clone(defaults.doughnut)); -defaults._set('pie', { - cutoutPercentage: 0 -}); - -module.exports = function(Chart) { +module.exports = DatasetController.extend({ - Chart.controllers.doughnut = Chart.controllers.pie = Chart.DatasetController.extend({ + dataElementType: elements.Arc, - dataElementType: elements.Arc, + linkScales: helpers.noop, - linkScales: helpers.noop, + // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly + getRingIndex: function(datasetIndex) { + var ringIndex = 0; - // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly - getRingIndex: function(datasetIndex) { - var ringIndex = 0; - - for (var j = 0; j < datasetIndex; ++j) { - if (this.chart.isDatasetVisible(j)) { - ++ringIndex; - } + for (var j = 0; j < datasetIndex; ++j) { + if (this.chart.isDatasetVisible(j)) { + ++ringIndex; } + } - return ringIndex; - }, - - update: function(reset) { - var me = this; - var chart = me.chart; - var chartArea = chart.chartArea; - var opts = chart.options; - var arcOpts = opts.elements.arc; - var availableWidth = chartArea.right - chartArea.left - arcOpts.borderWidth; - var availableHeight = chartArea.bottom - chartArea.top - arcOpts.borderWidth; - var minSize = Math.min(availableWidth, availableHeight); - var offset = {x: 0, y: 0}; - var meta = me.getMeta(); - var cutoutPercentage = opts.cutoutPercentage; - var circumference = opts.circumference; - - // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc - if (circumference < Math.PI * 2.0) { - var startAngle = opts.rotation % (Math.PI * 2.0); - startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0); - var endAngle = startAngle + circumference; - var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)}; - var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)}; - var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle); - var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle); - var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle); - var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle); - var cutout = cutoutPercentage / 100.0; - var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))}; - var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))}; - var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5}; - minSize = Math.min(availableWidth / size.width, availableHeight / size.height); - offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5}; - } + return ringIndex; + }, - chart.borderWidth = me.getMaxBorderWidth(meta.data); - chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0); - chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0); - chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount(); - chart.offsetX = offset.x * chart.outerRadius; - chart.offsetY = offset.y * chart.outerRadius; + update: function(reset) { + var me = this; + var chart = me.chart; + var chartArea = chart.chartArea; + var opts = chart.options; + var arcOpts = opts.elements.arc; + var availableWidth = chartArea.right - chartArea.left - arcOpts.borderWidth; + var availableHeight = chartArea.bottom - chartArea.top - arcOpts.borderWidth; + var minSize = Math.min(availableWidth, availableHeight); + var offset = {x: 0, y: 0}; + var meta = me.getMeta(); + var cutoutPercentage = opts.cutoutPercentage; + var circumference = opts.circumference; + + // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc + if (circumference < Math.PI * 2.0) { + var startAngle = opts.rotation % (Math.PI * 2.0); + startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0); + var endAngle = startAngle + circumference; + var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)}; + var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)}; + var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle); + var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle); + var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle); + var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle); + var cutout = cutoutPercentage / 100.0; + var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))}; + var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))}; + var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5}; + minSize = Math.min(availableWidth / size.width, availableHeight / size.height); + offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5}; + } - meta.total = me.calculateTotal(); + chart.borderWidth = me.getMaxBorderWidth(meta.data); + chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0); + chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0); + chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount(); + chart.offsetX = offset.x * chart.outerRadius; + chart.offsetY = offset.y * chart.outerRadius; - me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index)); - me.innerRadius = Math.max(me.outerRadius - chart.radiusLength, 0); + meta.total = me.calculateTotal(); - helpers.each(meta.data, function(arc, index) { - me.updateElement(arc, index, reset); - }); - }, + me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index)); + me.innerRadius = Math.max(me.outerRadius - chart.radiusLength, 0); - updateElement: function(arc, index, reset) { - var me = this; - var chart = me.chart; - var chartArea = chart.chartArea; - var opts = chart.options; - var animationOpts = opts.animation; - var centerX = (chartArea.left + chartArea.right) / 2; - var centerY = (chartArea.top + chartArea.bottom) / 2; - var startAngle = opts.rotation; // non reset case handled later - var endAngle = opts.rotation; // non reset case handled later - var dataset = me.getDataset(); - var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI)); - var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius; - var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius; - var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault; - - helpers.extend(arc, { - // Utility - _datasetIndex: me.index, - _index: index, - - // Desired view properties - _model: { - x: centerX + chart.offsetX, - y: centerY + chart.offsetY, - startAngle: startAngle, - endAngle: endAngle, - circumference: circumference, - outerRadius: outerRadius, - innerRadius: innerRadius, - label: valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index]) - } - }); - - var model = arc._model; - - // Resets the visual styles - var custom = arc.custom || {}; - var valueOrDefault = helpers.valueAtIndexOrDefault; - var elementOpts = this.chart.options.elements.arc; - model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor); - model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor); - model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth); - - // Set correct angles if not resetting - if (!reset || !animationOpts.animateRotate) { - if (index === 0) { - model.startAngle = opts.rotation; - } else { - model.startAngle = me.getMeta().data[index - 1]._model.endAngle; - } + helpers.each(meta.data, function(arc, index) { + me.updateElement(arc, index, reset); + }); + }, - model.endAngle = model.startAngle + model.circumference; + updateElement: function(arc, index, reset) { + var me = this; + var chart = me.chart; + var chartArea = chart.chartArea; + var opts = chart.options; + var animationOpts = opts.animation; + var centerX = (chartArea.left + chartArea.right) / 2; + var centerY = (chartArea.top + chartArea.bottom) / 2; + var startAngle = opts.rotation; // non reset case handled later + var endAngle = opts.rotation; // non reset case handled later + var dataset = me.getDataset(); + var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI)); + var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius; + var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius; + var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault; + + helpers.extend(arc, { + // Utility + _datasetIndex: me.index, + _index: index, + + // Desired view properties + _model: { + x: centerX + chart.offsetX, + y: centerY + chart.offsetY, + startAngle: startAngle, + endAngle: endAngle, + circumference: circumference, + outerRadius: outerRadius, + innerRadius: innerRadius, + label: valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index]) + } + }); + + var model = arc._model; + + // Resets the visual styles + var custom = arc.custom || {}; + var valueOrDefault = helpers.valueAtIndexOrDefault; + var elementOpts = this.chart.options.elements.arc; + model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor); + model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor); + model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth); + + // Set correct angles if not resetting + if (!reset || !animationOpts.animateRotate) { + if (index === 0) { + model.startAngle = opts.rotation; + } else { + model.startAngle = me.getMeta().data[index - 1]._model.endAngle; } - arc.pivot(); - }, + model.endAngle = model.startAngle + model.circumference; + } - calculateTotal: function() { - var dataset = this.getDataset(); - var meta = this.getMeta(); - var total = 0; - var value; + arc.pivot(); + }, - helpers.each(meta.data, function(element, index) { - value = dataset.data[index]; - if (!isNaN(value) && !element.hidden) { - total += Math.abs(value); - } - }); + calculateTotal: function() { + var dataset = this.getDataset(); + var meta = this.getMeta(); + var total = 0; + var value; - /* if (total === 0) { - total = NaN; - }*/ + helpers.each(meta.data, function(element, index) { + value = dataset.data[index]; + if (!isNaN(value) && !element.hidden) { + total += Math.abs(value); + } + }); - return total; - }, + /* if (total === 0) { + total = NaN; + }*/ - calculateCircumference: function(value) { - var total = this.getMeta().total; - if (total > 0 && !isNaN(value)) { - return (Math.PI * 2.0) * (Math.abs(value) / total); - } - return 0; - }, + return total; + }, - // gets the max border or hover width to properly scale pie charts - getMaxBorderWidth: function(arcs) { - var max = 0; - var index = this.index; - var length = arcs.length; - var borderWidth; - var hoverWidth; + calculateCircumference: function(value) { + var total = this.getMeta().total; + if (total > 0 && !isNaN(value)) { + return (Math.PI * 2.0) * (Math.abs(value) / total); + } + return 0; + }, - for (var i = 0; i < length; i++) { - borderWidth = arcs[i]._model ? arcs[i]._model.borderWidth : 0; - hoverWidth = arcs[i]._chart ? arcs[i]._chart.config.data.datasets[index].hoverBorderWidth : 0; + // gets the max border or hover width to properly scale pie charts + getMaxBorderWidth: function(arcs) { + var max = 0; + var index = this.index; + var length = arcs.length; + var borderWidth; + var hoverWidth; - max = borderWidth > max ? borderWidth : max; - max = hoverWidth > max ? hoverWidth : max; - } - return max; + for (var i = 0; i < length; i++) { + borderWidth = arcs[i]._model ? arcs[i]._model.borderWidth : 0; + hoverWidth = arcs[i]._chart ? arcs[i]._chart.config.data.datasets[index].hoverBorderWidth : 0; + + max = borderWidth > max ? borderWidth : max; + max = hoverWidth > max ? hoverWidth : max; } - }); -}; + return max; + } +});
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/controllers/controller.horizontalBar.js
@@ -0,0 +1,79 @@ + +'use strict'; + +var BarController = require('./controller.bar'); +var defaults = require('../core/core.defaults'); + +defaults._set('horizontalBar', { + hover: { + mode: 'index', + axis: 'y' + }, + + scales: { + xAxes: [{ + type: 'linear', + position: 'bottom' + }], + + yAxes: [{ + type: 'category', + position: 'left', + categoryPercentage: 0.8, + barPercentage: 0.9, + offset: true, + gridLines: { + offsetGridLines: true + } + }] + }, + + elements: { + rectangle: { + borderSkipped: 'left' + } + }, + + tooltips: { + callbacks: { + title: function(item, data) { + // Pick first xLabel for now + var title = ''; + + if (item.length > 0) { + if (item[0].yLabel) { + title = item[0].yLabel; + } else if (data.labels.length > 0 && item[0].index < data.labels.length) { + title = data.labels[item[0].index]; + } + } + + return title; + }, + + label: function(item, data) { + var datasetLabel = data.datasets[item.datasetIndex].label || ''; + return datasetLabel + ': ' + item.xLabel; + } + }, + mode: 'index', + axis: 'y' + } +}); + +module.exports = BarController.extend({ + /** + * @private + */ + getValueScaleId: function() { + return this.getMeta().xAxisID; + }, + + /** + * @private + */ + getIndexScaleId: function() { + return this.getMeta().yAxisID; + } +}); +
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/controllers/controller.line.js
@@ -1,5 +1,6 @@ 'use strict'; +var DatasetController = require('../core/core.datasetController'); var defaults = require('../core/core.defaults'); var elements = require('../elements/index'); var helpers = require('../helpers/index'); @@ -24,321 +25,318 @@ defaults._set('line', { } }); -module.exports = function(Chart) { +function lineEnabled(dataset, options) { + return helpers.valueOrDefault(dataset.showLine, options.showLines); +} - function lineEnabled(dataset, options) { - return helpers.valueOrDefault(dataset.showLine, options.showLines); - } +module.exports = DatasetController.extend({ - Chart.controllers.line = Chart.DatasetController.extend({ + datasetElementType: elements.Line, - datasetElementType: elements.Line, + dataElementType: elements.Point, - dataElementType: elements.Point, + update: function(reset) { + var me = this; + var meta = me.getMeta(); + var line = meta.dataset; + var points = meta.data || []; + var options = me.chart.options; + var lineElementOptions = options.elements.line; + var scale = me.getScaleForId(meta.yAxisID); + var i, ilen, custom; + var dataset = me.getDataset(); + var showLine = lineEnabled(dataset, options); - update: function(reset) { - var me = this; - var meta = me.getMeta(); - var line = meta.dataset; - var points = meta.data || []; - var options = me.chart.options; - var lineElementOptions = options.elements.line; - var scale = me.getScaleForId(meta.yAxisID); - var i, ilen, custom; - var dataset = me.getDataset(); - var showLine = lineEnabled(dataset, options); + // Update Line + if (showLine) { + custom = line.custom || {}; - // Update Line - if (showLine) { - custom = line.custom || {}; + // Compatibility: If the properties are defined with only the old name, use those values + if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) { + dataset.lineTension = dataset.tension; + } - // Compatibility: If the properties are defined with only the old name, use those values - if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) { - dataset.lineTension = dataset.tension; - } + // Utility + line._scale = scale; + line._datasetIndex = me.index; + // Data + line._children = points; + // Model + line._model = { + // Appearance + // The default behavior of lines is to break at null values, according + // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158 + // This option gives lines the ability to span gaps + spanGaps: dataset.spanGaps ? dataset.spanGaps : options.spanGaps, + tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension), + backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor), + borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth), + borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor), + borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle), + borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash), + borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset), + borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle), + fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill), + steppedLine: custom.steppedLine ? custom.steppedLine : helpers.valueOrDefault(dataset.steppedLine, lineElementOptions.stepped), + cubicInterpolationMode: custom.cubicInterpolationMode ? custom.cubicInterpolationMode : helpers.valueOrDefault(dataset.cubicInterpolationMode, lineElementOptions.cubicInterpolationMode), + }; - // Utility - line._scale = scale; - line._datasetIndex = me.index; - // Data - line._children = points; - // Model - line._model = { - // Appearance - // The default behavior of lines is to break at null values, according - // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158 - // This option gives lines the ability to span gaps - spanGaps: dataset.spanGaps ? dataset.spanGaps : options.spanGaps, - tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension), - backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor), - borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth), - borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor), - borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle), - borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash), - borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset), - borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle), - fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill), - steppedLine: custom.steppedLine ? custom.steppedLine : helpers.valueOrDefault(dataset.steppedLine, lineElementOptions.stepped), - cubicInterpolationMode: custom.cubicInterpolationMode ? custom.cubicInterpolationMode : helpers.valueOrDefault(dataset.cubicInterpolationMode, lineElementOptions.cubicInterpolationMode), - }; - - line.pivot(); - } + line.pivot(); + } - // Update Points - for (i = 0, ilen = points.length; i < ilen; ++i) { - me.updateElement(points[i], i, reset); - } + // Update Points + for (i = 0, ilen = points.length; i < ilen; ++i) { + me.updateElement(points[i], i, reset); + } - if (showLine && line._model.tension !== 0) { - me.updateBezierControlPoints(); - } + if (showLine && line._model.tension !== 0) { + me.updateBezierControlPoints(); + } - // Now pivot the point for animation - for (i = 0, ilen = points.length; i < ilen; ++i) { - points[i].pivot(); - } - }, - - getPointBackgroundColor: function(point, index) { - var backgroundColor = this.chart.options.elements.point.backgroundColor; - var dataset = this.getDataset(); - var custom = point.custom || {}; - - if (custom.backgroundColor) { - backgroundColor = custom.backgroundColor; - } else if (dataset.pointBackgroundColor) { - backgroundColor = helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, backgroundColor); - } else if (dataset.backgroundColor) { - backgroundColor = dataset.backgroundColor; - } + // Now pivot the point for animation + for (i = 0, ilen = points.length; i < ilen; ++i) { + points[i].pivot(); + } + }, - return backgroundColor; - }, + getPointBackgroundColor: function(point, index) { + var backgroundColor = this.chart.options.elements.point.backgroundColor; + var dataset = this.getDataset(); + var custom = point.custom || {}; - getPointBorderColor: function(point, index) { - var borderColor = this.chart.options.elements.point.borderColor; - var dataset = this.getDataset(); - var custom = point.custom || {}; + if (custom.backgroundColor) { + backgroundColor = custom.backgroundColor; + } else if (dataset.pointBackgroundColor) { + backgroundColor = helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, backgroundColor); + } else if (dataset.backgroundColor) { + backgroundColor = dataset.backgroundColor; + } - if (custom.borderColor) { - borderColor = custom.borderColor; - } else if (dataset.pointBorderColor) { - borderColor = helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, borderColor); - } else if (dataset.borderColor) { - borderColor = dataset.borderColor; - } + return backgroundColor; + }, - return borderColor; - }, + getPointBorderColor: function(point, index) { + var borderColor = this.chart.options.elements.point.borderColor; + var dataset = this.getDataset(); + var custom = point.custom || {}; - getPointBorderWidth: function(point, index) { - var borderWidth = this.chart.options.elements.point.borderWidth; - var dataset = this.getDataset(); - var custom = point.custom || {}; + if (custom.borderColor) { + borderColor = custom.borderColor; + } else if (dataset.pointBorderColor) { + borderColor = helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, borderColor); + } else if (dataset.borderColor) { + borderColor = dataset.borderColor; + } - if (!isNaN(custom.borderWidth)) { - borderWidth = custom.borderWidth; - } else if (!isNaN(dataset.pointBorderWidth) || helpers.isArray(dataset.pointBorderWidth)) { - borderWidth = helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth); - } else if (!isNaN(dataset.borderWidth)) { - borderWidth = dataset.borderWidth; - } + return borderColor; + }, - return borderWidth; - }, + getPointBorderWidth: function(point, index) { + var borderWidth = this.chart.options.elements.point.borderWidth; + var dataset = this.getDataset(); + var custom = point.custom || {}; - getPointRotation: function(point, index) { - var pointRotation = this.chart.options.elements.point.rotation; - var dataset = this.getDataset(); - var custom = point.custom || {}; + if (!isNaN(custom.borderWidth)) { + borderWidth = custom.borderWidth; + } else if (!isNaN(dataset.pointBorderWidth) || helpers.isArray(dataset.pointBorderWidth)) { + borderWidth = helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth); + } else if (!isNaN(dataset.borderWidth)) { + borderWidth = dataset.borderWidth; + } - if (!isNaN(custom.rotation)) { - pointRotation = custom.rotation; - } else if (!isNaN(dataset.pointRotation) || helpers.isArray(dataset.pointRotation)) { - pointRotation = helpers.valueAtIndexOrDefault(dataset.pointRotation, index, pointRotation); - } - return pointRotation; - }, - - updateElement: function(point, index, reset) { - var me = this; - var meta = me.getMeta(); - var custom = point.custom || {}; - var dataset = me.getDataset(); - var datasetIndex = me.index; - var value = dataset.data[index]; - var yScale = me.getScaleForId(meta.yAxisID); - var xScale = me.getScaleForId(meta.xAxisID); - var pointOptions = me.chart.options.elements.point; - var x, y; + return borderWidth; + }, - // Compatibility: If the properties are defined with only the old name, use those values - if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) { - dataset.pointRadius = dataset.radius; - } - if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) { - dataset.pointHitRadius = dataset.hitRadius; - } + getPointRotation: function(point, index) { + var pointRotation = this.chart.options.elements.point.rotation; + var dataset = this.getDataset(); + var custom = point.custom || {}; + + if (!isNaN(custom.rotation)) { + pointRotation = custom.rotation; + } else if (!isNaN(dataset.pointRotation) || helpers.isArray(dataset.pointRotation)) { + pointRotation = helpers.valueAtIndexOrDefault(dataset.pointRotation, index, pointRotation); + } + return pointRotation; + }, - x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex); - y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex); + updateElement: function(point, index, reset) { + var me = this; + var meta = me.getMeta(); + var custom = point.custom || {}; + var dataset = me.getDataset(); + var datasetIndex = me.index; + var value = dataset.data[index]; + var yScale = me.getScaleForId(meta.yAxisID); + var xScale = me.getScaleForId(meta.xAxisID); + var pointOptions = me.chart.options.elements.point; + var x, y; + + // Compatibility: If the properties are defined with only the old name, use those values + if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) { + dataset.pointRadius = dataset.radius; + } + if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) { + dataset.pointHitRadius = dataset.hitRadius; + } + + x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex); + y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex); + + // Utility + point._xScale = xScale; + point._yScale = yScale; + point._datasetIndex = datasetIndex; + point._index = index; + + // Desired view properties + point._model = { + x: x, + y: y, + skip: custom.skip || isNaN(x) || isNaN(y), + // Appearance + radius: custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius), + pointStyle: custom.pointStyle || helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle), + rotation: me.getPointRotation(point, index), + backgroundColor: me.getPointBackgroundColor(point, index), + borderColor: me.getPointBorderColor(point, index), + borderWidth: me.getPointBorderWidth(point, index), + tension: meta.dataset._model ? meta.dataset._model.tension : 0, + steppedLine: meta.dataset._model ? meta.dataset._model.steppedLine : false, + // Tooltip + hitRadius: custom.hitRadius || helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointOptions.hitRadius) + }; + }, - // Utility - point._xScale = xScale; - point._yScale = yScale; - point._datasetIndex = datasetIndex; - point._index = index; - - // Desired view properties - point._model = { - x: x, - y: y, - skip: custom.skip || isNaN(x) || isNaN(y), - // Appearance - radius: custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius), - pointStyle: custom.pointStyle || helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle), - rotation: me.getPointRotation(point, index), - backgroundColor: me.getPointBackgroundColor(point, index), - borderColor: me.getPointBorderColor(point, index), - borderWidth: me.getPointBorderWidth(point, index), - tension: meta.dataset._model ? meta.dataset._model.tension : 0, - steppedLine: meta.dataset._model ? meta.dataset._model.steppedLine : false, - // Tooltip - hitRadius: custom.hitRadius || helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointOptions.hitRadius) - }; - }, - - calculatePointY: function(value, index, datasetIndex) { - var me = this; - var chart = me.chart; - var meta = me.getMeta(); - var yScale = me.getScaleForId(meta.yAxisID); - var sumPos = 0; - var sumNeg = 0; - var i, ds, dsMeta; - - if (yScale.options.stacked) { - for (i = 0; i < datasetIndex; i++) { - ds = chart.data.datasets[i]; - dsMeta = chart.getDatasetMeta(i); - if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) { - var stackedRightValue = Number(yScale.getRightValue(ds.data[index])); - if (stackedRightValue < 0) { - sumNeg += stackedRightValue || 0; - } else { - sumPos += stackedRightValue || 0; - } + calculatePointY: function(value, index, datasetIndex) { + var me = this; + var chart = me.chart; + var meta = me.getMeta(); + var yScale = me.getScaleForId(meta.yAxisID); + var sumPos = 0; + var sumNeg = 0; + var i, ds, dsMeta; + + if (yScale.options.stacked) { + for (i = 0; i < datasetIndex; i++) { + ds = chart.data.datasets[i]; + dsMeta = chart.getDatasetMeta(i); + if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) { + var stackedRightValue = Number(yScale.getRightValue(ds.data[index])); + if (stackedRightValue < 0) { + sumNeg += stackedRightValue || 0; + } else { + sumPos += stackedRightValue || 0; } } - - var rightValue = Number(yScale.getRightValue(value)); - if (rightValue < 0) { - return yScale.getPixelForValue(sumNeg + rightValue); - } - return yScale.getPixelForValue(sumPos + rightValue); } - return yScale.getPixelForValue(value); - }, - - updateBezierControlPoints: function() { - var me = this; - var meta = me.getMeta(); - var area = me.chart.chartArea; - var points = (meta.data || []); - var i, ilen, point, model, controlPoints; - - // Only consider points that are drawn in case the spanGaps option is used - if (meta.dataset._model.spanGaps) { - points = points.filter(function(pt) { - return !pt._model.skip; - }); + var rightValue = Number(yScale.getRightValue(value)); + if (rightValue < 0) { + return yScale.getPixelForValue(sumNeg + rightValue); } + return yScale.getPixelForValue(sumPos + rightValue); + } - function capControlPoint(pt, min, max) { - return Math.max(Math.min(pt, max), min); - } + return yScale.getPixelForValue(value); + }, - if (meta.dataset._model.cubicInterpolationMode === 'monotone') { - helpers.splineCurveMonotone(points); - } else { - for (i = 0, ilen = points.length; i < ilen; ++i) { - point = points[i]; - model = point._model; - controlPoints = helpers.splineCurve( - helpers.previousItem(points, i)._model, - model, - helpers.nextItem(points, i)._model, - meta.dataset._model.tension - ); - model.controlPointPreviousX = controlPoints.previous.x; - model.controlPointPreviousY = controlPoints.previous.y; - model.controlPointNextX = controlPoints.next.x; - model.controlPointNextY = controlPoints.next.y; - } + updateBezierControlPoints: function() { + var me = this; + var meta = me.getMeta(); + var area = me.chart.chartArea; + var points = (meta.data || []); + var i, ilen, point, model, controlPoints; + + // Only consider points that are drawn in case the spanGaps option is used + if (meta.dataset._model.spanGaps) { + points = points.filter(function(pt) { + return !pt._model.skip; + }); + } + + function capControlPoint(pt, min, max) { + return Math.max(Math.min(pt, max), min); + } + + if (meta.dataset._model.cubicInterpolationMode === 'monotone') { + helpers.splineCurveMonotone(points); + } else { + for (i = 0, ilen = points.length; i < ilen; ++i) { + point = points[i]; + model = point._model; + controlPoints = helpers.splineCurve( + helpers.previousItem(points, i)._model, + model, + helpers.nextItem(points, i)._model, + meta.dataset._model.tension + ); + model.controlPointPreviousX = controlPoints.previous.x; + model.controlPointPreviousY = controlPoints.previous.y; + model.controlPointNextX = controlPoints.next.x; + model.controlPointNextY = controlPoints.next.y; } + } - if (me.chart.options.elements.line.capBezierPoints) { - for (i = 0, ilen = points.length; i < ilen; ++i) { - model = points[i]._model; - model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right); - model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom); - model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right); - model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom); - } - } - }, - - draw: function() { - var me = this; - var chart = me.chart; - var meta = me.getMeta(); - var points = meta.data || []; - var area = chart.chartArea; - var ilen = points.length; - var halfBorderWidth; - var i = 0; - - if (lineEnabled(me.getDataset(), chart.options)) { - halfBorderWidth = (meta.dataset._model.borderWidth || 0) / 2; - - helpers.canvas.clipArea(chart.ctx, { - left: area.left, - right: area.right, - top: area.top - halfBorderWidth, - bottom: area.bottom + halfBorderWidth - }); - - meta.dataset.draw(); - - helpers.canvas.unclipArea(chart.ctx); + if (me.chart.options.elements.line.capBezierPoints) { + for (i = 0, ilen = points.length; i < ilen; ++i) { + model = points[i]._model; + model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right); + model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom); + model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right); + model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom); } + } + }, - // Draw the points - for (; i < ilen; ++i) { - points[i].draw(area); - } - }, - - setHoverStyle: function(element) { - // Point - var dataset = this.chart.data.datasets[element._datasetIndex]; - var index = element._index; - var custom = element.custom || {}; - var model = element._model; - - element.$previousStyle = { - backgroundColor: model.backgroundColor, - borderColor: model.borderColor, - borderWidth: model.borderWidth, - radius: model.radius - }; + draw: function() { + var me = this; + var chart = me.chart; + var meta = me.getMeta(); + var points = meta.data || []; + var area = chart.chartArea; + var ilen = points.length; + var halfBorderWidth; + var i = 0; + + if (lineEnabled(me.getDataset(), chart.options)) { + halfBorderWidth = (meta.dataset._model.borderWidth || 0) / 2; + + helpers.canvas.clipArea(chart.ctx, { + left: area.left, + right: area.right, + top: area.top - halfBorderWidth, + bottom: area.bottom + halfBorderWidth + }); + + meta.dataset.draw(); + + helpers.canvas.unclipArea(chart.ctx); + } + + // Draw the points + for (; i < ilen; ++i) { + points[i].draw(area); + } + }, - model.backgroundColor = custom.hoverBackgroundColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor)); - model.borderColor = custom.hoverBorderColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor)); - model.borderWidth = custom.hoverBorderWidth || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth); - model.radius = custom.hoverRadius || helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius); - }, - }); -}; + setHoverStyle: function(element) { + // Point + var dataset = this.chart.data.datasets[element._datasetIndex]; + var index = element._index; + var custom = element.custom || {}; + var model = element._model; + + element.$previousStyle = { + backgroundColor: model.backgroundColor, + borderColor: model.borderColor, + borderWidth: model.borderWidth, + radius: model.radius + }; + + model.backgroundColor = custom.hoverBackgroundColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor)); + model.borderColor = custom.hoverBorderColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor)); + model.borderWidth = custom.hoverBorderWidth || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth); + model.radius = custom.hoverRadius || helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius); + } +});
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/controllers/controller.pie.js
@@ -0,0 +1,13 @@ +'use strict'; + +var DoughnutController = require('./controller.doughnut'); +var defaults = require('../core/core.defaults'); +var helpers = require('../helpers/index'); + +defaults._set('pie', helpers.clone(defaults.doughnut)); +defaults._set('pie', { + cutoutPercentage: 0 +}); + +// Pie charts are Doughnut chart with different defaults +module.exports = DoughnutController;
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/controllers/controller.polarArea.js
@@ -1,5 +1,6 @@ 'use strict'; +var DatasetController = require('../core/core.datasetController'); var defaults = require('../core/core.defaults'); var elements = require('../elements/index'); var helpers = require('../helpers/index'); @@ -108,148 +109,145 @@ defaults._set('polarArea', { } }); -module.exports = function(Chart) { +module.exports = DatasetController.extend({ - Chart.controllers.polarArea = Chart.DatasetController.extend({ + dataElementType: elements.Arc, - dataElementType: elements.Arc, + linkScales: helpers.noop, - linkScales: helpers.noop, + update: function(reset) { + var me = this; + var dataset = me.getDataset(); + var meta = me.getMeta(); + var start = me.chart.options.startAngle || 0; + var starts = me._starts = []; + var angles = me._angles = []; + var i, ilen, angle; - update: function(reset) { - var me = this; - var dataset = me.getDataset(); - var meta = me.getMeta(); - var start = me.chart.options.startAngle || 0; - var starts = me._starts = []; - var angles = me._angles = []; - var i, ilen, angle; + me._updateRadius(); - me._updateRadius(); + meta.count = me.countVisibleElements(); - meta.count = me.countVisibleElements(); - - for (i = 0, ilen = dataset.data.length; i < ilen; i++) { - starts[i] = start; - angle = me._computeAngle(i); - angles[i] = angle; - start += angle; - } - - helpers.each(meta.data, function(arc, index) { - me.updateElement(arc, index, reset); - }); - }, - - /** - * @private - */ - _updateRadius: function() { - var me = this; - var chart = me.chart; - var chartArea = chart.chartArea; - var opts = chart.options; - var arcOpts = opts.elements.arc; - var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); - - chart.outerRadius = Math.max((minSize - arcOpts.borderWidth / 2) / 2, 0); - chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0); - chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount(); - - me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index); - me.innerRadius = me.outerRadius - chart.radiusLength; - }, + for (i = 0, ilen = dataset.data.length; i < ilen; i++) { + starts[i] = start; + angle = me._computeAngle(i); + angles[i] = angle; + start += angle; + } - updateElement: function(arc, index, reset) { - var me = this; - var chart = me.chart; - var dataset = me.getDataset(); - var opts = chart.options; - var animationOpts = opts.animation; - var scale = chart.scale; - var labels = chart.data.labels; - - var centerX = scale.xCenter; - var centerY = scale.yCenter; - - // var negHalfPI = -0.5 * Math.PI; - var datasetStartAngle = opts.startAngle; - var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); - var startAngle = me._starts[index]; - var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]); - - var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); - - helpers.extend(arc, { - // Utility - _datasetIndex: me.index, - _index: index, - _scale: scale, - - // Desired view properties - _model: { - x: centerX, - y: centerY, - innerRadius: 0, - outerRadius: reset ? resetRadius : distance, - startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle, - endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle, - label: helpers.valueAtIndexOrDefault(labels, index, labels[index]) - } - }); + helpers.each(meta.data, function(arc, index) { + me.updateElement(arc, index, reset); + }); + }, - // Apply border and fill style - var elementOpts = this.chart.options.elements.arc; - var custom = arc.custom || {}; - var valueOrDefault = helpers.valueAtIndexOrDefault; - var model = arc._model; + /** + * @private + */ + _updateRadius: function() { + var me = this; + var chart = me.chart; + var chartArea = chart.chartArea; + var opts = chart.options; + var arcOpts = opts.elements.arc; + var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); + + chart.outerRadius = Math.max((minSize - arcOpts.borderWidth / 2) / 2, 0); + chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0); + chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount(); + + me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index); + me.innerRadius = me.outerRadius - chart.radiusLength; + }, - model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor); - model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor); - model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth); + updateElement: function(arc, index, reset) { + var me = this; + var chart = me.chart; + var dataset = me.getDataset(); + var opts = chart.options; + var animationOpts = opts.animation; + var scale = chart.scale; + var labels = chart.data.labels; + + var centerX = scale.xCenter; + var centerY = scale.yCenter; + + // var negHalfPI = -0.5 * Math.PI; + var datasetStartAngle = opts.startAngle; + var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); + var startAngle = me._starts[index]; + var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]); + + var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); + + helpers.extend(arc, { + // Utility + _datasetIndex: me.index, + _index: index, + _scale: scale, + + // Desired view properties + _model: { + x: centerX, + y: centerY, + innerRadius: 0, + outerRadius: reset ? resetRadius : distance, + startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle, + endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle, + label: helpers.valueAtIndexOrDefault(labels, index, labels[index]) + } + }); - arc.pivot(); - }, + // Apply border and fill style + var elementOpts = this.chart.options.elements.arc; + var custom = arc.custom || {}; + var valueOrDefault = helpers.valueAtIndexOrDefault; + var model = arc._model; - countVisibleElements: function() { - var dataset = this.getDataset(); - var meta = this.getMeta(); - var count = 0; + model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor); + model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor); + model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth); - helpers.each(meta.data, function(element, index) { - if (!isNaN(dataset.data[index]) && !element.hidden) { - count++; - } - }); + arc.pivot(); + }, - return count; - }, + countVisibleElements: function() { + var dataset = this.getDataset(); + var meta = this.getMeta(); + var count = 0; - /** - * @private - */ - _computeAngle: function(index) { - var me = this; - var count = this.getMeta().count; - var dataset = me.getDataset(); - var meta = me.getMeta(); - - if (isNaN(dataset.data[index]) || meta.data[index].hidden) { - return 0; + helpers.each(meta.data, function(element, index) { + if (!isNaN(dataset.data[index]) && !element.hidden) { + count++; } + }); - // Scriptable options - var context = { - chart: me.chart, - dataIndex: index, - dataset: dataset, - datasetIndex: me.index - }; - - return helpers.options.resolve([ - me.chart.options.elements.arc.angle, - (2 * Math.PI) / count - ], context, index); + return count; + }, + + /** + * @private + */ + _computeAngle: function(index) { + var me = this; + var count = this.getMeta().count; + var dataset = me.getDataset(); + var meta = me.getMeta(); + + if (isNaN(dataset.data[index]) || meta.data[index].hidden) { + return 0; } - }); -}; + + // Scriptable options + var context = { + chart: me.chart, + dataIndex: index, + dataset: dataset, + datasetIndex: me.index + }; + + return helpers.options.resolve([ + me.chart.options.elements.arc.angle, + (2 * Math.PI) / count + ], context, index); + } +});
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/controllers/controller.radar.js
@@ -1,5 +1,6 @@ 'use strict'; +var DatasetController = require('../core/core.datasetController'); var defaults = require('../core/core.defaults'); var elements = require('../elements/index'); var helpers = require('../helpers/index'); @@ -15,158 +16,157 @@ defaults._set('radar', { } }); -module.exports = function(Chart) { +module.exports = DatasetController.extend({ - Chart.controllers.radar = Chart.DatasetController.extend({ + datasetElementType: elements.Line, - datasetElementType: elements.Line, + dataElementType: elements.Point, - dataElementType: elements.Point, + linkScales: helpers.noop, - linkScales: helpers.noop, + update: function(reset) { + var me = this; + var meta = me.getMeta(); + var line = meta.dataset; + var points = meta.data || []; + var custom = line.custom || {}; + var dataset = me.getDataset(); + var lineElementOptions = me.chart.options.elements.line; + var scale = me.chart.scale; + var i, ilen; - update: function(reset) { - var me = this; - var meta = me.getMeta(); - var line = meta.dataset; - var points = meta.data || []; - var custom = line.custom || {}; - var dataset = me.getDataset(); - var lineElementOptions = me.chart.options.elements.line; - var scale = me.chart.scale; - var i, ilen; + // Compatibility: If the properties are defined with only the old name, use those values + if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) { + dataset.lineTension = dataset.tension; + } - // Compatibility: If the properties are defined with only the old name, use those values - if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) { - dataset.lineTension = dataset.tension; + helpers.extend(meta.dataset, { + // Utility + _datasetIndex: me.index, + _scale: scale, + // Data + _children: points, + _loop: true, + // Model + _model: { + // Appearance + tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension), + backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor), + borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth), + borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor), + fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill), + borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle), + borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash), + borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset), + borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle), } + }); - helpers.extend(meta.dataset, { - // Utility - _datasetIndex: me.index, - _scale: scale, - // Data - _children: points, - _loop: true, - // Model - _model: { - // Appearance - tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension), - backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor), - borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth), - borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor), - fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill), - borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle), - borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash), - borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset), - borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle), - } - }); - - meta.dataset.pivot(); - - // Update Points - for (i = 0, ilen = points.length; i < ilen; i++) { - me.updateElement(points[i], i, reset); - } + meta.dataset.pivot(); - // Update bezier control points - me.updateBezierControlPoints(); + // Update Points + for (i = 0, ilen = points.length; i < ilen; i++) { + me.updateElement(points[i], i, reset); + } - // Now pivot the point for animation - for (i = 0, ilen = points.length; i < ilen; i++) { - points[i].pivot(); - } - }, - updateElement: function(point, index, reset) { - var me = this; - var custom = point.custom || {}; - var dataset = me.getDataset(); - var scale = me.chart.scale; - var pointElementOptions = me.chart.options.elements.point; - var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]); - - // Compatibility: If the properties are defined with only the old name, use those values - if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) { - dataset.pointRadius = dataset.radius; - } - if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) { - dataset.pointHitRadius = dataset.hitRadius; - } + // Update bezier control points + me.updateBezierControlPoints(); - helpers.extend(point, { - // Utility - _datasetIndex: me.index, - _index: index, - _scale: scale, - - // Desired view properties - _model: { - x: reset ? scale.xCenter : pointPosition.x, // value not used in dataset scale, but we want a consistent API between scales - y: reset ? scale.yCenter : pointPosition.y, - - // Appearance - tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, me.chart.options.elements.line.tension), - radius: custom.radius ? custom.radius : helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius), - backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor), - borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor), - borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth), - pointStyle: custom.pointStyle ? custom.pointStyle : helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointElementOptions.pointStyle), - rotation: custom.rotation ? custom.rotation : helpers.valueAtIndexOrDefault(dataset.pointRotation, index, pointElementOptions.rotation), - - // Tooltip - hitRadius: custom.hitRadius ? custom.hitRadius : helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointElementOptions.hitRadius) - } - }); - - point._model.skip = custom.skip ? custom.skip : (isNaN(point._model.x) || isNaN(point._model.y)); - }, - updateBezierControlPoints: function() { - var me = this; - var meta = me.getMeta(); - var area = me.chart.chartArea; - var points = meta.data || []; - var i, ilen, model, controlPoints; - - function capControlPoint(pt, min, max) { - return Math.max(Math.min(pt, max), min); - } + // Now pivot the point for animation + for (i = 0, ilen = points.length; i < ilen; i++) { + points[i].pivot(); + } + }, + + updateElement: function(point, index, reset) { + var me = this; + var custom = point.custom || {}; + var dataset = me.getDataset(); + var scale = me.chart.scale; + var pointElementOptions = me.chart.options.elements.point; + var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]); + + // Compatibility: If the properties are defined with only the old name, use those values + if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) { + dataset.pointRadius = dataset.radius; + } + if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) { + dataset.pointHitRadius = dataset.hitRadius; + } - for (i = 0, ilen = points.length; i < ilen; i++) { - model = points[i]._model; - controlPoints = helpers.splineCurve( - helpers.previousItem(points, i, true)._model, - model, - helpers.nextItem(points, i, true)._model, - model.tension - ); - - // Prevent the bezier going outside of the bounds of the graph - model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right); - model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom); - model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right); - model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom); + helpers.extend(point, { + // Utility + _datasetIndex: me.index, + _index: index, + _scale: scale, + + // Desired view properties + _model: { + x: reset ? scale.xCenter : pointPosition.x, // value not used in dataset scale, but we want a consistent API between scales + y: reset ? scale.yCenter : pointPosition.y, + + // Appearance + tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, me.chart.options.elements.line.tension), + radius: custom.radius ? custom.radius : helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius), + backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor), + borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor), + borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth), + pointStyle: custom.pointStyle ? custom.pointStyle : helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointElementOptions.pointStyle), + rotation: custom.rotation ? custom.rotation : helpers.valueAtIndexOrDefault(dataset.pointRotation, index, pointElementOptions.rotation), + + // Tooltip + hitRadius: custom.hitRadius ? custom.hitRadius : helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointElementOptions.hitRadius) } - }, - - setHoverStyle: function(point) { - // Point - var dataset = this.chart.data.datasets[point._datasetIndex]; - var custom = point.custom || {}; - var index = point._index; - var model = point._model; - - point.$previousStyle = { - backgroundColor: model.backgroundColor, - borderColor: model.borderColor, - borderWidth: model.borderWidth, - radius: model.radius - }; - - model.radius = custom.hoverRadius ? custom.hoverRadius : helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius); - model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor)); - model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor)); - model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth); - }, - }); -}; + }); + + point._model.skip = custom.skip ? custom.skip : (isNaN(point._model.x) || isNaN(point._model.y)); + }, + + updateBezierControlPoints: function() { + var me = this; + var meta = me.getMeta(); + var area = me.chart.chartArea; + var points = meta.data || []; + var i, ilen, model, controlPoints; + + function capControlPoint(pt, min, max) { + return Math.max(Math.min(pt, max), min); + } + + for (i = 0, ilen = points.length; i < ilen; i++) { + model = points[i]._model; + controlPoints = helpers.splineCurve( + helpers.previousItem(points, i, true)._model, + model, + helpers.nextItem(points, i, true)._model, + model.tension + ); + + // Prevent the bezier going outside of the bounds of the graph + model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right); + model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom); + model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right); + model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom); + } + }, + + setHoverStyle: function(point) { + // Point + var dataset = this.chart.data.datasets[point._datasetIndex]; + var custom = point.custom || {}; + var index = point._index; + var model = point._model; + + point.$previousStyle = { + backgroundColor: model.backgroundColor, + borderColor: model.borderColor, + borderWidth: model.borderWidth, + radius: model.radius + }; + + model.radius = custom.hoverRadius ? custom.hoverRadius : helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius); + model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor)); + model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor)); + model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth); + } +});
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/controllers/controller.scatter.js
@@ -1,5 +1,6 @@ 'use strict'; +var LineController = require('./controller.line'); var defaults = require('../core/core.defaults'); defaults._set('scatter', { @@ -34,9 +35,5 @@ defaults._set('scatter', { } }); -module.exports = function(Chart) { - - // Scatter charts use line controllers - Chart.controllers.scatter = Chart.controllers.line; - -}; +// Scatter charts use line controllers +module.exports = LineController;
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/controllers/index.js
@@ -0,0 +1,18 @@ +'use strict'; + +// NOTE export a map in which the key represents the controller type, not +// the class, and so must be CamelCase in order to be correctly retrieved +// by the controller in core.controller.js (`controllers[meta.type]`). + +/* eslint-disable global-require */ +module.exports = { + bar: require('./controller.bar'), + bubble: require('./controller.bubble'), + doughnut: require('./controller.doughnut'), + horizontalBar: require('./controller.horizontalBar'), + line: require('./controller.line'), + polarArea: require('./controller.polarArea'), + pie: require('./controller.pie'), + radar: require('./controller.radar'), + scatter: require('./controller.scatter') +};
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/core/core.controller.js
@@ -2,6 +2,7 @@ var Animation = require('./core.animation'); var animations = require('./core.animations'); +var controllers = require('../controllers/index'); var defaults = require('./core.defaults'); var helpers = require('../helpers/index'); var Interaction = require('./core.interaction'); @@ -20,9 +21,6 @@ module.exports = function(Chart) { // Destroy method on the chart will remove the instance of the chart from this reference. Chart.instances = {}; - // Controllers available for dataset visualization eg. bar, line, slice, etc. - Chart.controllers = {}; - /** * Initializes the given config with global and chart default values. */ @@ -337,7 +335,7 @@ module.exports = function(Chart) { meta.controller.updateIndex(datasetIndex); meta.controller.linkScales(); } else { - var ControllerClass = Chart.controllers[meta.type]; + var ControllerClass = controllers[meta.type]; if (ControllerClass === undefined) { throw new Error('"' + meta.type + '" is not a chart type.'); }
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
src/core/core.datasetController.js
@@ -2,328 +2,325 @@ var helpers = require('../helpers/index'); -module.exports = function(Chart) { - - var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift']; +var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift']; + +/** + * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice', + * 'unshift') and notify the listener AFTER the array has been altered. Listeners are + * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments. + */ +function listenArrayEvents(array, listener) { + if (array._chartjs) { + array._chartjs.listeners.push(listener); + return; + } - /** - * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice', - * 'unshift') and notify the listener AFTER the array has been altered. Listeners are - * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments. - */ - function listenArrayEvents(array, listener) { - if (array._chartjs) { - array._chartjs.listeners.push(listener); - return; + Object.defineProperty(array, '_chartjs', { + configurable: true, + enumerable: false, + value: { + listeners: [listener] } + }); - Object.defineProperty(array, '_chartjs', { + arrayEvents.forEach(function(key) { + var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1); + var base = array[key]; + + Object.defineProperty(array, key, { configurable: true, enumerable: false, - value: { - listeners: [listener] + value: function() { + var args = Array.prototype.slice.call(arguments); + var res = base.apply(this, args); + + helpers.each(array._chartjs.listeners, function(object) { + if (typeof object[method] === 'function') { + object[method].apply(object, args); + } + }); + + return res; } }); + }); +} + +/** + * Removes the given array event listener and cleanup extra attached properties (such as + * the _chartjs stub and overridden methods) if array doesn't have any more listeners. + */ +function unlistenArrayEvents(array, listener) { + var stub = array._chartjs; + if (!stub) { + return; + } - arrayEvents.forEach(function(key) { - var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1); - var base = array[key]; - - Object.defineProperty(array, key, { - configurable: true, - enumerable: false, - value: function() { - var args = Array.prototype.slice.call(arguments); - var res = base.apply(this, args); - - helpers.each(array._chartjs.listeners, function(object) { - if (typeof object[method] === 'function') { - object[method].apply(object, args); - } - }); - - return res; - } - }); - }); + var listeners = stub.listeners; + var index = listeners.indexOf(listener); + if (index !== -1) { + listeners.splice(index, 1); + } + + if (listeners.length > 0) { + return; } + arrayEvents.forEach(function(key) { + delete array[key]; + }); + + delete array._chartjs; +} + +// Base class for all dataset controllers (line, bar, etc) +var DatasetController = module.exports = function(chart, datasetIndex) { + this.initialize(chart, datasetIndex); +}; + +helpers.extend(DatasetController.prototype, { + /** - * Removes the given array event listener and cleanup extra attached properties (such as - * the _chartjs stub and overridden methods) if array doesn't have any more listeners. + * Element type used to generate a meta dataset (e.g. Chart.element.Line). + * @type {Chart.core.element} */ - function unlistenArrayEvents(array, listener) { - var stub = array._chartjs; - if (!stub) { - return; - } + datasetElementType: null, - var listeners = stub.listeners; - var index = listeners.indexOf(listener); - if (index !== -1) { - listeners.splice(index, 1); + /** + * Element type used to generate a meta data (e.g. Chart.element.Point). + * @type {Chart.core.element} + */ + dataElementType: null, + + initialize: function(chart, datasetIndex) { + var me = this; + me.chart = chart; + me.index = datasetIndex; + me.linkScales(); + me.addElements(); + }, + + updateIndex: function(datasetIndex) { + this.index = datasetIndex; + }, + + linkScales: function() { + var me = this; + var meta = me.getMeta(); + var dataset = me.getDataset(); + + if (meta.xAxisID === null || !(meta.xAxisID in me.chart.scales)) { + meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id; } - - if (listeners.length > 0) { - return; + if (meta.yAxisID === null || !(meta.yAxisID in me.chart.scales)) { + meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id; } + }, + + getDataset: function() { + return this.chart.data.datasets[this.index]; + }, - arrayEvents.forEach(function(key) { - delete array[key]; + getMeta: function() { + return this.chart.getDatasetMeta(this.index); + }, + + getScaleForId: function(scaleID) { + return this.chart.scales[scaleID]; + }, + + reset: function() { + this.update(true); + }, + + /** + * @private + */ + destroy: function() { + if (this._data) { + unlistenArrayEvents(this._data, this); + } + }, + + createMetaDataset: function() { + var me = this; + var type = me.datasetElementType; + return type && new type({ + _chart: me.chart, + _datasetIndex: me.index + }); + }, + + createMetaData: function(index) { + var me = this; + var type = me.dataElementType; + return type && new type({ + _chart: me.chart, + _datasetIndex: me.index, + _index: index }); + }, - delete array._chartjs; - } + addElements: function() { + var me = this; + var meta = me.getMeta(); + var data = me.getDataset().data || []; + var metaData = meta.data; + var i, ilen; - // Base class for all dataset controllers (line, bar, etc) - Chart.DatasetController = function(chart, datasetIndex) { - this.initialize(chart, datasetIndex); - }; - - helpers.extend(Chart.DatasetController.prototype, { - - /** - * Element type used to generate a meta dataset (e.g. Chart.element.Line). - * @type {Chart.core.element} - */ - datasetElementType: null, - - /** - * Element type used to generate a meta data (e.g. Chart.element.Point). - * @type {Chart.core.element} - */ - dataElementType: null, - - initialize: function(chart, datasetIndex) { - var me = this; - me.chart = chart; - me.index = datasetIndex; - me.linkScales(); - me.addElements(); - }, - - updateIndex: function(datasetIndex) { - this.index = datasetIndex; - }, - - linkScales: function() { - var me = this; - var meta = me.getMeta(); - var dataset = me.getDataset(); - - if (meta.xAxisID === null || !(meta.xAxisID in me.chart.scales)) { - meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id; - } - if (meta.yAxisID === null || !(meta.yAxisID in me.chart.scales)) { - meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id; - } - }, - - getDataset: function() { - return this.chart.data.datasets[this.index]; - }, - - getMeta: function() { - return this.chart.getDatasetMeta(this.index); - }, - - getScaleForId: function(scaleID) { - return this.chart.scales[scaleID]; - }, - - reset: function() { - this.update(true); - }, - - /** - * @private - */ - destroy: function() { - if (this._data) { - unlistenArrayEvents(this._data, this); - } - }, - - createMetaDataset: function() { - var me = this; - var type = me.datasetElementType; - return type && new type({ - _chart: me.chart, - _datasetIndex: me.index - }); - }, - - createMetaData: function(index) { - var me = this; - var type = me.dataElementType; - return type && new type({ - _chart: me.chart, - _datasetIndex: me.index, - _index: index - }); - }, - - addElements: function() { - var me = this; - var meta = me.getMeta(); - var data = me.getDataset().data || []; - var metaData = meta.data; - var i, ilen; - - for (i = 0, ilen = data.length; i < ilen; ++i) { - metaData[i] = metaData[i] || me.createMetaData(i); - } + for (i = 0, ilen = data.length; i < ilen; ++i) { + metaData[i] = metaData[i] || me.createMetaData(i); + } - meta.dataset = meta.dataset || me.createMetaDataset(); - }, - - addElementAndReset: function(index) { - var element = this.createMetaData(index); - this.getMeta().data.splice(index, 0, element); - this.updateElement(element, index, true); - }, - - buildOrUpdateElements: function() { - var me = this; - var dataset = me.getDataset(); - var data = dataset.data || (dataset.data = []); - - // In order to correctly handle data addition/deletion animation (an thus simulate - // real-time charts), we need to monitor these data modifications and synchronize - // the internal meta data accordingly. - if (me._data !== data) { - if (me._data) { - // This case happens when the user replaced the data array instance. - unlistenArrayEvents(me._data, me); - } - - listenArrayEvents(data, me); - me._data = data; + meta.dataset = meta.dataset || me.createMetaDataset(); + }, + + addElementAndReset: function(index) { + var element = this.createMetaData(index); + this.getMeta().data.splice(index, 0, element); + this.updateElement(element, index, true); + }, + + buildOrUpdateElements: function() { + var me = this; + var dataset = me.getDataset(); + var data = dataset.data || (dataset.data = []); + + // In order to correctly handle data addition/deletion animation (an thus simulate + // real-time charts), we need to monitor these data modifications and synchronize + // the internal meta data accordingly. + if (me._data !== data) { + if (me._data) { + // This case happens when the user replaced the data array instance. + unlistenArrayEvents(me._data, me); } - // Re-sync meta data in case the user replaced the data array or if we missed - // any updates and so make sure that we handle number of datapoints changing. - me.resyncElements(); - }, + listenArrayEvents(data, me); + me._data = data; + } - update: helpers.noop, + // Re-sync meta data in case the user replaced the data array or if we missed + // any updates and so make sure that we handle number of datapoints changing. + me.resyncElements(); + }, - transition: function(easingValue) { - var meta = this.getMeta(); - var elements = meta.data || []; - var ilen = elements.length; - var i = 0; + update: helpers.noop, - for (; i < ilen; ++i) { - elements[i].transition(easingValue); - } + transition: function(easingValue) { + var meta = this.getMeta(); + var elements = meta.data || []; + var ilen = elements.length; + var i = 0; - if (meta.dataset) { - meta.dataset.transition(easingValue); - } - }, + for (; i < ilen; ++i) { + elements[i].transition(easingValue); + } - draw: function() { - var meta = this.getMeta(); - var elements = meta.data || []; - var ilen = elements.length; - var i = 0; + if (meta.dataset) { + meta.dataset.transition(easingValue); + } + }, - if (meta.dataset) { - meta.dataset.draw(); - } + draw: function() { + var meta = this.getMeta(); + var elements = meta.data || []; + var ilen = elements.length; + var i = 0; - for (; i < ilen; ++i) { - elements[i].draw(); - } - }, - - removeHoverStyle: function(element) { - helpers.merge(element._model, element.$previousStyle || {}); - delete element.$previousStyle; - }, - - setHoverStyle: function(element) { - var dataset = this.chart.data.datasets[element._datasetIndex]; - var index = element._index; - var custom = element.custom || {}; - var valueOrDefault = helpers.valueAtIndexOrDefault; - var getHoverColor = helpers.getHoverColor; - var model = element._model; - - element.$previousStyle = { - backgroundColor: model.backgroundColor, - borderColor: model.borderColor, - borderWidth: model.borderWidth - }; - - model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : valueOrDefault(dataset.hoverBackgroundColor, index, getHoverColor(model.backgroundColor)); - model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : valueOrDefault(dataset.hoverBorderColor, index, getHoverColor(model.borderColor)); - model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : valueOrDefault(dataset.hoverBorderWidth, index, model.borderWidth); - }, - - /** - * @private - */ - resyncElements: function() { - var me = this; - var meta = me.getMeta(); - var data = me.getDataset().data; - var numMeta = meta.data.length; - var numData = data.length; - - if (numData < numMeta) { - meta.data.splice(numData, numMeta - numData); - } else if (numData > numMeta) { - me.insertElements(numMeta, numData - numMeta); - } - }, - - /** - * @private - */ - insertElements: function(start, count) { - for (var i = 0; i < count; ++i) { - this.addElementAndReset(start + i); - } - }, - - /** - * @private - */ - onDataPush: function() { - this.insertElements(this.getDataset().data.length - 1, arguments.length); - }, - - /** - * @private - */ - onDataPop: function() { - this.getMeta().data.pop(); - }, - - /** - * @private - */ - onDataShift: function() { - this.getMeta().data.shift(); - }, - - /** - * @private - */ - onDataSplice: function(start, count) { - this.getMeta().data.splice(start, count); - this.insertElements(start, arguments.length - 2); - }, - - /** - * @private - */ - onDataUnshift: function() { - this.insertElements(0, arguments.length); + if (meta.dataset) { + meta.dataset.draw(); } - }); - Chart.DatasetController.extend = helpers.inherits; -}; + for (; i < ilen; ++i) { + elements[i].draw(); + } + }, + + removeHoverStyle: function(element) { + helpers.merge(element._model, element.$previousStyle || {}); + delete element.$previousStyle; + }, + + setHoverStyle: function(element) { + var dataset = this.chart.data.datasets[element._datasetIndex]; + var index = element._index; + var custom = element.custom || {}; + var valueOrDefault = helpers.valueAtIndexOrDefault; + var getHoverColor = helpers.getHoverColor; + var model = element._model; + + element.$previousStyle = { + backgroundColor: model.backgroundColor, + borderColor: model.borderColor, + borderWidth: model.borderWidth + }; + + model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : valueOrDefault(dataset.hoverBackgroundColor, index, getHoverColor(model.backgroundColor)); + model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : valueOrDefault(dataset.hoverBorderColor, index, getHoverColor(model.borderColor)); + model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : valueOrDefault(dataset.hoverBorderWidth, index, model.borderWidth); + }, + + /** + * @private + */ + resyncElements: function() { + var me = this; + var meta = me.getMeta(); + var data = me.getDataset().data; + var numMeta = meta.data.length; + var numData = data.length; + + if (numData < numMeta) { + meta.data.splice(numData, numMeta - numData); + } else if (numData > numMeta) { + me.insertElements(numMeta, numData - numMeta); + } + }, + + /** + * @private + */ + insertElements: function(start, count) { + for (var i = 0; i < count; ++i) { + this.addElementAndReset(start + i); + } + }, + + /** + * @private + */ + onDataPush: function() { + this.insertElements(this.getDataset().data.length - 1, arguments.length); + }, + + /** + * @private + */ + onDataPop: function() { + this.getMeta().data.pop(); + }, + + /** + * @private + */ + onDataShift: function() { + this.getMeta().data.shift(); + }, + + /** + * @private + */ + onDataSplice: function(start, count) { + this.getMeta().data.splice(start, count); + this.insertElements(start, arguments.length - 2); + }, + + /** + * @private + */ + onDataUnshift: function() { + this.insertElements(0, arguments.length); + } +}); + +DatasetController.extend = helpers.inherits;
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
test/specs/controller.bar.tests.js
@@ -1,6 +1,11 @@ describe('Chart.controllers.bar', function() { describe('auto', jasmine.fixture.specs('controller.bar')); + it('should be registered as dataset controller', function() { + expect(typeof Chart.controllers.bar).toBe('function'); + expect(typeof Chart.controllers.horizontalBar).toBe('function'); + }); + it('should be constructed', function() { var chart = window.acquireChart({ type: 'bar',
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
test/specs/controller.bubble.tests.js
@@ -1,6 +1,10 @@ describe('Chart.controllers.bubble', function() { describe('auto', jasmine.fixture.specs('controller.bubble')); + it('should be registered as dataset controller', function() { + expect(typeof Chart.controllers.bubble).toBe('function'); + }); + it('should be constructed', function() { var chart = window.acquireChart({ type: 'bubble',
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
test/specs/controller.doughnut.tests.js
@@ -1,4 +1,9 @@ describe('Chart.controllers.doughnut', function() { + it('should be registered as dataset controller', function() { + expect(typeof Chart.controllers.doughnut).toBe('function'); + expect(Chart.controllers.doughnut).toBe(Chart.controllers.pie); + }); + it('should be constructed', function() { var chart = window.acquireChart({ type: 'doughnut',
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
test/specs/controller.line.tests.js
@@ -1,6 +1,10 @@ describe('Chart.controllers.line', function() { describe('auto', jasmine.fixture.specs('controller.line')); + it('should be registered as dataset controller', function() { + expect(typeof Chart.controllers.line).toBe('function'); + }); + it('should be constructed', function() { var chart = window.acquireChart({ type: 'line',
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
test/specs/controller.polarArea.tests.js
@@ -1,6 +1,10 @@ -describe('auto', jasmine.fixture.specs('controller.polarArea')); - describe('Chart.controllers.polarArea', function() { + describe('auto', jasmine.fixture.specs('controller.polarArea')); + + it('should be registered as dataset controller', function() { + expect(typeof Chart.controllers.polarArea).toBe('function'); + }); + it('should be constructed', function() { var chart = window.acquireChart({ type: 'polarArea',
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
test/specs/controller.radar.tests.js
@@ -1,6 +1,10 @@ describe('Chart.controllers.radar', function() { describe('auto', jasmine.fixture.specs('controller.radar')); + it('should be registered as dataset controller', function() { + expect(typeof Chart.controllers.radar).toBe('function'); + }); + it('Should be constructed', function() { var chart = window.acquireChart({ type: 'radar',
true
Other
chartjs
Chart.js
be8d78a900b560a1dbd465a29736063e4e8fa4ef.json
Make Chart.controllers.* importable (#5871) `controllers.*.js` and `core.datasetController.js` are now importable (no more function export), that's why there is so many changes mainly due to one indentation level removed. Split code for `bar/horizontalBar` and `doughnut/pie` in separate files, added a global controllers import (`src/controllers/index.js`) and add tests to check that all dataset controllers are correctly registered under `chart.controllers.{type}`.
test/specs/controller.scatter.test.js
@@ -1,4 +1,8 @@ describe('Chart.controllers.scatter', function() { + it('should be registered as dataset controller', function() { + expect(typeof Chart.controllers.scatter).toBe('function'); + }); + describe('showLines option', function() { it('should not draw a line if undefined', function() { var chart = window.acquireChart({
true
Other
chartjs
Chart.js
f6d9a39cb8e8661e1d6a733d4b77fb3f3238935a.json
Fix axis line width when option is an array (#5751) When the axis lineWidth setting is set to an array, use the first item when determining the size of the axis area.
src/core/core.scale.js
@@ -708,7 +708,7 @@ module.exports = Element.extend({ var itemsToDraw = []; - var axisWidth = me.options.gridLines.lineWidth; + var axisWidth = helpers.valueAtIndexOrDefault(me.options.gridLines.lineWidth, 0); var xTickStart = options.position === 'right' ? me.left : me.right - axisWidth - tl; var xTickEnd = options.position === 'right' ? me.left + tl : me.right; var yTickStart = options.position === 'bottom' ? me.top + axisWidth : me.bottom - tl - axisWidth;
false
Other
chartjs
Chart.js
75aa44eef677b790768262638df0de223fd01a56.json
Upgrade dev dependencies to reduce vulnerabilities (#5840)
gulpfile.js
@@ -49,19 +49,19 @@ gulp.task('bower', bowerTask); gulp.task('build', buildTask); gulp.task('package', packageTask); gulp.task('watch', watchTask); -gulp.task('lint', ['lint-html', 'lint-js']); gulp.task('lint-html', lintHtmlTask); gulp.task('lint-js', lintJsTask); +gulp.task('lint', gulp.parallel('lint-html', 'lint-js')); gulp.task('docs', docsTask); -gulp.task('test', ['lint', 'unittest']); -gulp.task('size', ['library-size', 'module-sizes']); gulp.task('server', serverTask); gulp.task('unittest', unittestTask); +gulp.task('test', gulp.parallel('lint', 'unittest')); gulp.task('library-size', librarySizeTask); gulp.task('module-sizes', moduleSizesTask); +gulp.task('size', gulp.parallel('library-size', 'module-sizes')); gulp.task('_open', _openTask); -gulp.task('dev', ['server', 'default']); -gulp.task('default', ['build', 'watch']); +gulp.task('default', gulp.parallel('build', 'watch')); +gulp.task('dev', gulp.parallel('server', 'default')); /** * Generates the bower.json manifest file which will be pushed along release tags. @@ -233,7 +233,7 @@ function moduleSizesTask() { } function watchTask() { - return gulp.watch('./src/**', ['build']); + return gulp.watch('./src/**', gulp.parallel('build')); } function serverTask() {
true
Other
chartjs
Chart.js
75aa44eef677b790768262638df0de223fd01a56.json
Upgrade dev dependencies to reduce vulnerabilities (#5840)
package.json
@@ -10,42 +10,42 @@ "url": "https://github.com/chartjs/Chart.js.git" }, "devDependencies": { - "browserify": "^14.5.0", + "browserify": "^16.2.3", "browserify-istanbul": "^3.0.1", "bundle-collapser": "^1.3.0", "child-process-promise": "^2.2.1", "coveralls": "^3.0.0", - "eslint": "^4.9.0", + "eslint": "^5.9.0", "eslint-config-chartjs": "^0.1.0", - "eslint-plugin-html": "^4.0.2", + "eslint-plugin-html": "^5.0.0", "gitbook-cli": "^2.3.2", - "gulp": "3.9.x", - "gulp-concat": "~2.6.x", - "gulp-connect": "~5.0.0", - "gulp-eslint": "^4.0.0", - "gulp-file": "^0.3.0", - "gulp-htmllint": "^0.0.15", - "gulp-insert": "~0.5.0", - "gulp-replace": "^0.6.1", - "gulp-size": "~2.1.0", + "gulp": "^4.0.0", + "gulp-concat": "^2.6.0", + "gulp-connect": "^5.6.1", + "gulp-eslint": "^5.0.0", + "gulp-file": "^0.4.0", + "gulp-htmllint": "^0.0.16", + "gulp-insert": "^0.5.0", + "gulp-replace": "^1.0.0", + "gulp-size": "^3.0.0", "gulp-streamify": "^1.0.2", - "gulp-uglify": "~3.0.x", - "gulp-util": "~3.0.x", - "gulp-zip": "~4.0.0", - "jasmine": "^2.8.0", - "jasmine-core": "^2.8.0", - "karma": "^1.7.1", + "gulp-uglify": "^3.0.0", + "gulp-util": "^3.0.0", + "gulp-zip": "^4.2.0", + "jasmine": "^3.3.0", + "jasmine-core": "^3.3.0", + "karma": "^3.1.1", "karma-browserify": "^5.1.1", "karma-chrome-launcher": "^2.2.0", "karma-coverage": "^1.1.1", "karma-firefox-launcher": "^1.0.1", - "karma-jasmine": "^1.1.0", - "karma-jasmine-html-reporter": "^0.2.2", + "karma-jasmine": "^2.0.0", + "karma-jasmine-html-reporter": "^1.4.0", "merge-stream": "^1.0.1", "pixelmatch": "^4.0.2", - "vinyl-source-stream": "^1.1.0", + "vinyl-source-stream": "^2.0.0", "watchify": "^3.9.0", - "yargs": "^9.0.1" + "yargs": "^12.0.2" }, "spm": { "main": "Chart.js"
true
Other
chartjs
Chart.js
75aa44eef677b790768262638df0de223fd01a56.json
Upgrade dev dependencies to reduce vulnerabilities (#5840)
src/platforms/platform.dom.js
@@ -108,6 +108,7 @@ var supportsEventListenerOptions = (function() { var supports = false; try { var options = Object.defineProperty({}, 'passive', { + // eslint-disable-next-line getter-return get: function() { supports = true; } @@ -391,6 +392,7 @@ module.exports = { // we can't use save() and restore() to restore the initial state. So make sure that at // least the canvas context is reset to the default state by setting the canvas width. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html + // eslint-disable-next-line no-self-assign canvas.width = canvas.width; delete canvas[EXPANDO_KEY];
true
Other
chartjs
Chart.js
75aa44eef677b790768262638df0de223fd01a56.json
Upgrade dev dependencies to reduce vulnerabilities (#5840)
test/specs/core.controller.tests.js
@@ -949,25 +949,13 @@ describe('Chart', function() { var meta = chart.getDatasetMeta(0); var point = meta.data[1]; - var node = chart.canvas; - var rect = node.getBoundingClientRect(); - - var evt = new MouseEvent('mousemove', { - view: window, - bubbles: true, - cancelable: true, - clientX: rect.left + point._model.x, - clientY: 0 - }); - - // Manually trigger rather than having an async test - node.dispatchEvent(evt); + jasmine.triggerMouseEvent(chart, 'mousemove', point); // Check and see if tooltip was displayed var tooltip = chart.tooltip; expect(chart.lastActive).toEqual([point]); - expect(tooltip._lastActive).toEqual([]); + expect(tooltip._lastActive).toEqual([point]); // Update and confirm tooltip is reset chart.update();
true
Other
chartjs
Chart.js
75aa44eef677b790768262638df0de223fd01a56.json
Upgrade dev dependencies to reduce vulnerabilities (#5840)
test/specs/core.plugin.tests.js
@@ -323,6 +323,8 @@ describe('Chart.plugins', function() { expect(plugin.hook).toHaveBeenCalled(); expect(plugin.hook.calls.first().args[1]).toEqual({a: 42}); + + delete Chart.defaults.global.plugins.a; });
true
Other
chartjs
Chart.js
3ea93a09f2047b727891f9e13dbd3fb7ebe44adf.json
Add regression test for legend layout issue (#5776)
test/specs/plugin.legend.tests.js
@@ -525,6 +525,43 @@ describe('Legend block tests', function() { }); }); + it('should not draw legend items outside of the chart bounds', function() { + var chart = window.acquireChart( + { + type: 'line', + data: { + datasets: [1, 2, 3].map(function(n) { + return { + label: 'dataset' + n, + data: [] + }; + }), + labels: [] + }, + options: { + legend: { + position: 'right' + } + } + }, + { + canvas: { + width: 512, + height: 105 + } + } + ); + + // Check some basic assertions about the test setup + expect(chart.width).toBe(512); + expect(chart.legend.legendHitBoxes.length).toBe(3); + + // Check whether any legend items reach outside the established bounds + chart.legend.legendHitBoxes.forEach(function(item) { + expect(item.left + item.width).toBeLessThanOrEqual(chart.width); + }); + }); + describe('config update', function() { it ('should update the options', function() { var chart = acquireChart({
false
Other
chartjs
Chart.js
637c2176ecad70b674ffe8802bde070136785a45.json
Support decimal stepSize (#5786)
src/core/core.helpers.js
@@ -174,6 +174,26 @@ module.exports = function() { helpers.toDegrees = function(radians) { return radians * (180 / Math.PI); }; + + /** + * Returns the number of decimal places + * i.e. the number of digits after the decimal point, of the value of this Number. + * @param {Number} x - A number. + * @returns {Number} The number of decimal places. + */ + helpers.decimalPlaces = function(x) { + if (!helpers.isFinite(x)) { + return; + } + var e = 1; + var p = 0; + while (Math.round(x * e) / e !== x) { + e *= 10; + p++; + } + return p; + }; + // Gets the angle from vertical upright to the point about a centre. helpers.getAngleFromPoint = function(centrePoint, anglePoint) { var distanceFromXCenter = anglePoint.x - centrePoint.x;
true
Other
chartjs
Chart.js
637c2176ecad70b674ffe8802bde070136785a45.json
Support decimal stepSize (#5786)
src/scales/scale.linearbase.js
@@ -15,54 +15,55 @@ function generateTicks(generationOptions, dataRange) { // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks // for details. - var factor; - var precision; - var spacing; + var stepSize = generationOptions.stepSize; + var min = generationOptions.min; + var max = generationOptions.max; + var spacing, precision, factor, niceRange, niceMin, niceMax, numSpaces; - if (generationOptions.stepSize && generationOptions.stepSize > 0) { - spacing = generationOptions.stepSize; + if (stepSize && stepSize > 0) { + spacing = stepSize; } else { - var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false); + niceRange = helpers.niceNum(dataRange.max - dataRange.min, false); spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true); precision = generationOptions.precision; - if (precision !== undefined) { + if (!helpers.isNullOrUndef(precision)) { // If the user specified a precision, round to that number of decimal places factor = Math.pow(10, precision); spacing = Math.ceil(spacing * factor) / factor; } } - var niceMin = Math.floor(dataRange.min / spacing) * spacing; - var niceMax = Math.ceil(dataRange.max / spacing) * spacing; + // If a precision is not specified, calculate factor based on spacing + if (!factor) { + factor = Math.pow(10, helpers.decimalPlaces(spacing)); + } + niceMin = Math.floor(dataRange.min / spacing) * spacing; + niceMax = Math.ceil(dataRange.max / spacing) * spacing; // If min, max and stepSize is set and they make an evenly spaced scale use it. - if (!helpers.isNullOrUndef(generationOptions.min) && !helpers.isNullOrUndef(generationOptions.max) && generationOptions.stepSize) { + if (!helpers.isNullOrUndef(min) && !helpers.isNullOrUndef(max) && stepSize) { // If very close to our whole number, use it. - if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) { - niceMin = generationOptions.min; - niceMax = generationOptions.max; + if (helpers.almostWhole((max - min) / stepSize, spacing / 1000)) { + niceMin = min; + niceMax = max; } } - var numSpaces = (niceMax - niceMin) / spacing; + numSpaces = (niceMax - niceMin) / spacing; // If very close to our rounded value, use it. if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { numSpaces = Math.round(numSpaces); } else { numSpaces = Math.ceil(numSpaces); } - precision = 1; - if (spacing < 1) { - precision = Math.pow(10, 1 - Math.floor(helpers.log10(spacing))); - niceMin = Math.round(niceMin * precision) / precision; - niceMax = Math.round(niceMax * precision) / precision; - } - ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin); + niceMin = Math.round(niceMin * factor) / factor; + niceMax = Math.round(niceMax * factor) / factor; + ticks.push(helpers.isNullOrUndef(min) ? niceMin : min); for (var j = 1; j < numSpaces; ++j) { - ticks.push(Math.round((niceMin + j * spacing) * precision) / precision); + ticks.push(Math.round((niceMin + j * spacing) * factor) / factor); } - ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax); + ticks.push(helpers.isNullOrUndef(max) ? niceMax : max); return ticks; }
true
Other
chartjs
Chart.js
637c2176ecad70b674ffe8802bde070136785a45.json
Support decimal stepSize (#5786)
test/specs/core.helpers.tests.js
@@ -238,6 +238,17 @@ describe('Core helper tests', function() { expect(helpers.toDegrees(Math.PI * 3 / 2)).toBe(270); }); + it('should get the correct number of decimal places', function() { + expect(helpers.decimalPlaces(100)).toBe(0); + expect(helpers.decimalPlaces(1)).toBe(0); + expect(helpers.decimalPlaces(0)).toBe(0); + expect(helpers.decimalPlaces(0.01)).toBe(2); + expect(helpers.decimalPlaces(-0.01)).toBe(2); + expect(helpers.decimalPlaces('1')).toBe(undefined); + expect(helpers.decimalPlaces('')).toBe(undefined); + expect(helpers.decimalPlaces(undefined)).toBe(undefined); + }); + it('should get an angle from a point', function() { var center = { x: 0,
true
Other
chartjs
Chart.js
637c2176ecad70b674ffe8802bde070136785a45.json
Support decimal stepSize (#5786)
test/specs/scale.linear.tests.js
@@ -573,6 +573,35 @@ describe('Linear Scale', function() { expect(chart.scales.yScale0.ticks).toEqual(['11', '9', '7', '5', '3', '1']); }); + it('Should create decimal steps if stepSize is a decimal number', function() { + var chart = window.acquireChart({ + type: 'bar', + data: { + datasets: [{ + yAxisID: 'yScale0', + data: [10, 3, 6, 8, 3, 1] + }], + labels: ['a', 'b', 'c', 'd', 'e', 'f'] + }, + options: { + scales: { + yAxes: [{ + id: 'yScale0', + type: 'linear', + ticks: { + stepSize: 2.5 + } + }] + } + } + }); + + expect(chart.scales.yScale0).not.toEqual(undefined); // must construct + expect(chart.scales.yScale0.min).toBe(0); + expect(chart.scales.yScale0.max).toBe(10); + expect(chart.scales.yScale0.ticks).toEqual(['10', '7.5', '5', '2.5', '0']); + }); + describe('precision', function() { it('Should create integer steps if precision is 0', function() { var chart = window.acquireChart({
true
Other
chartjs
Chart.js
7e62913cfc2f97b33545cb5ffca4845aa8cd6d55.json
Change .editorconfig to include final newlines (#5827)
.editorconfig
@@ -7,7 +7,7 @@ indent_size = 4 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true -insert_final_newline = false +insert_final_newline = true [gulpfile.js] indent_style = space
false
Other
chartjs
Chart.js
1ba06a26fddde17285072f3a446679e9388b382f.json
Add aspectRatio property to responsive doc (#5756)
docs/general/responsive.md
@@ -16,6 +16,7 @@ Chart.js provides a [few options](#configuration-options) to enable responsivene | `responsive` | `Boolean` | `true` | Resizes the chart canvas when its container does ([important note...](#important-note)). | `responsiveAnimationDuration` | `Number` | `0` | Duration in milliseconds it takes to animate to new size after a resize event. | `maintainAspectRatio` | `Boolean` | `true` | Maintain the original canvas aspect ratio `(width / height)` when resizing. +| `aspectRatio` | `Number` | `2` | Canvas aspect ratio (i.e. `width / height`, a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style. | `onResize` | `Function` | `null` | Called when a resize occurs. Gets passed two arguments: the chart instance and the new size. ## Important Note
false
Other
chartjs
Chart.js
9293c30d4f5727c4f64967d709f37f44d43b716f.json
Add scatter link in charts documentation (#5736)
docs/charts/README.md
@@ -4,9 +4,10 @@ Chart.js comes with built-in chart types: * [line](./line.md) * [bar](./bar.md) * [radar](./radar.md) -* [polar area](./polar.md) * [doughnut and pie](./doughnut.md) +* [polar area](./polar.md) * [bubble](./bubble.md) +* [scatter](./scatter.md) [Area charts](area.md) can be built from a line or radar chart using the dataset `fill` option.
false
Other
chartjs
Chart.js
a9c4e377a7f529a82fc1dbcef32ab23d40c9b158.json
Add color to financial time series sample (#5661)
samples/scales/time/financial.html
@@ -56,12 +56,16 @@ var ctx = document.getElementById('chart1').getContext('2d'); ctx.canvas.width = 1000; ctx.canvas.height = 300; + + var color = Chart.helpers.color; var cfg = { type: 'bar', data: { labels: labels, datasets: [{ label: 'CHRT - Chart.js Corporation', + backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(), + borderColor: window.chartColors.red, data: data, type: 'line', pointRadius: 0,
false
Other
chartjs
Chart.js
9a295816b3ed406ff34d078746d8afd94d0b13a2.json
Replace ES6 by Webpack in the integration docs (#5555)
docs/getting-started/integration.md
@@ -2,13 +2,6 @@ Chart.js can be integrated with plain JavaScript or with different module loaders. The examples below show how to load Chart.js in different systems. -## ES6 Modules - -```javascript -import Chart from 'chart.js'; -var myChart = new Chart(ctx, {...}); -``` - ## Script Tag ```html @@ -18,6 +11,13 @@ var myChart = new Chart(ctx, {...}); </script> ``` +## Webpack + +```javascript +import Chart from 'chart.js'; +var myChart = new Chart(ctx, {...}); +``` + ## Common JS ```javascript
false
Other
chartjs
Chart.js
246b9a1a40b72e57ba256d679ca6e44f1cd82411.json
Add circular option documentation for grid lines (#5637)
docs/axes/styling.md
@@ -9,6 +9,7 @@ The grid line configuration is nested under the scale configuration in the `grid | Name | Type | Default | Description | -----| ---- | --------| ----------- | `display` | `Boolean` | `true` | If false, do not display grid lines for this axis. +| `circular` | `Boolean` | `false` | If true, gridlines are circular (on radar chart only) | `color` | `Color/Color[]` | `'rgba(0, 0, 0, 0.1)'` | The color of the grid lines. If specified as an array, the first color applies to the first grid line, the second to the second grid line and so on. | `borderDash` | `Number[]` | `[]` | Length and spacing of dashes on grid lines. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash) | `borderDashOffset` | `Number` | `0` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset)
false
Other
chartjs
Chart.js
6dbb7e74462d5b7dedf2124a622a3e678964dd83.json
Move config handling to a dedicated script (#7939) * Split core.config.js out of core.controller.js * Remove side effects from config.js * Turn config into a class * Refactor config merging as includeDefaults
src/core/core.config.js
@@ -0,0 +1,181 @@ +/* eslint-disable import/no-namespace, import/namespace */ +import defaults from './core.defaults'; +import {mergeIf, merge, _merger} from '../helpers/helpers.core'; + +export function getIndexAxis(type, options) { + const typeDefaults = defaults[type] || {}; + const datasetDefaults = typeDefaults.datasets || {}; + const typeOptions = options[type] || {}; + const datasetOptions = typeOptions.datasets || {}; + return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x'; +} + +function getAxisFromDefaultScaleID(id, indexAxis) { + let axis = id; + if (id === '_index_') { + axis = indexAxis; + } else if (id === '_value_') { + axis = indexAxis === 'x' ? 'y' : 'x'; + } + return axis; +} + +function getDefaultScaleIDFromAxis(axis, indexAxis) { + return axis === indexAxis ? '_index_' : '_value_'; +} + +function axisFromPosition(position) { + if (position === 'top' || position === 'bottom') { + return 'x'; + } + if (position === 'left' || position === 'right') { + return 'y'; + } +} + +export function determineAxis(id, scaleOptions) { + if (id === 'x' || id === 'y' || id === 'r') { + return id; + } + return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id.charAt(0).toLowerCase(); +} + +function mergeScaleConfig(config, options) { + options = options || {}; + const chartDefaults = defaults[config.type] || {scales: {}}; + const configScales = options.scales || {}; + const chartIndexAxis = getIndexAxis(config.type, options); + const firstIDs = Object.create(null); + const scales = Object.create(null); + + // First figure out first scale id's per axis. + Object.keys(configScales).forEach(id => { + const scaleConf = configScales[id]; + const axis = determineAxis(id, scaleConf); + const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis); + firstIDs[axis] = firstIDs[axis] || id; + scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, chartDefaults.scales[axis], chartDefaults.scales[defaultId]]); + }); + + // Backward compatibility + if (options.scale) { + scales[options.scale.id || 'r'] = mergeIf(Object.create(null), [{axis: 'r'}, options.scale, chartDefaults.scales.r]); + firstIDs.r = firstIDs.r || options.scale.id || 'r'; + } + + // Then merge dataset defaults to scale configs + config.data.datasets.forEach(dataset => { + const type = dataset.type || config.type; + const indexAxis = dataset.indexAxis || getIndexAxis(type, options); + const datasetDefaults = defaults[type] || {}; + const defaultScaleOptions = datasetDefaults.scales || {}; + Object.keys(defaultScaleOptions).forEach(defaultID => { + const axis = getAxisFromDefaultScaleID(defaultID, indexAxis); + const id = dataset[axis + 'AxisID'] || firstIDs[axis] || axis; + scales[id] = scales[id] || Object.create(null); + mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]); + }); + }); + + // apply scale defaults, if not overridden by dataset defaults + Object.keys(scales).forEach(key => { + const scale = scales[key]; + mergeIf(scale, [defaults.scales[scale.type], defaults.scale]); + }); + + return scales; +} + +/** + * Recursively merge the given config objects as the root options by handling + * default scale options for the `scales` and `scale` properties, then returns + * a deep copy of the result, thus doesn't alter inputs. + */ +function mergeConfig(...args/* config objects ... */) { + return merge(Object.create(null), args, { + merger(key, target, source, options) { + if (key !== 'scales' && key !== 'scale') { + _merger(key, target, source, options); + } + } + }); +} + +function includeDefaults(options, type) { + return mergeConfig( + defaults, + defaults[type], + options || {}); +} + +function initConfig(config) { + config = config || {}; + + // Do NOT use mergeConfig for the data object because this method merges arrays + // and so would change references to labels and datasets, preventing data updates. + const data = config.data = config.data || {datasets: [], labels: []}; + data.datasets = data.datasets || []; + data.labels = data.labels || []; + + const scaleConfig = mergeScaleConfig(config, config.options); + + const options = config.options = includeDefaults(config.options, config.type); + + options.hover = merge(Object.create(null), [ + defaults.interaction, + defaults.hover, + options.interaction, + options.hover + ]); + + options.scales = scaleConfig; + + options.title = (options.title !== false) && merge(Object.create(null), [ + defaults.plugins.title, + options.title + ]); + options.tooltips = (options.tooltips !== false) && merge(Object.create(null), [ + defaults.interaction, + defaults.plugins.tooltip, + options.interaction, + options.tooltips + ]); + + return config; +} + +export default class Config { + constructor(config) { + this._config = initConfig(config); + } + + get type() { + return this._config.type; + } + + get data() { + return this._config.data; + } + + set data(data) { + this._config.data = data; + } + + get options() { + return this._config.options; + } + + get plugins() { + return this._config.plugins; + } + + update(options) { + const config = this._config; + const scaleConfig = mergeScaleConfig(config, options); + + options = includeDefaults(options, config.type); + + options.scales = scaleConfig; + config.options = options; + } +}
true
Other
chartjs
Chart.js
6dbb7e74462d5b7dedf2124a622a3e678964dd83.json
Move config handling to a dedicated script (#7939) * Split core.config.js out of core.controller.js * Remove side effects from config.js * Turn config into a class * Refactor config merging as includeDefaults
src/core/core.controller.js
@@ -6,8 +6,9 @@ import layouts from './core.layouts'; import {BasicPlatform, DomPlatform} from '../platform'; import PluginService from './core.plugins'; import registry from './core.registry'; +import Config, {determineAxis, getIndexAxis} from './core.config'; import {retinaScale} from '../helpers/helpers.dom'; -import {mergeIf, merge, _merger, each, callback as callCallback, uid, valueOrDefault, _elementsEqual} from '../helpers/helpers.core'; +import {each, callback as callCallback, uid, valueOrDefault, _elementsEqual} from '../helpers/helpers.core'; import {clear as canvasClear, clipArea, unclipArea, _isPointInArea} from '../helpers/helpers.canvas'; // @ts-ignore import {version} from '../../package.json'; @@ -16,174 +17,11 @@ import {version} from '../../package.json'; * @typedef { import("../platform/platform.base").IEvent } IEvent */ - -function getIndexAxis(type, options) { - const typeDefaults = defaults[type] || {}; - const datasetDefaults = typeDefaults.datasets || {}; - const typeOptions = options[type] || {}; - const datasetOptions = typeOptions.datasets || {}; - return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x'; -} - -function getAxisFromDefaultScaleID(id, indexAxis) { - let axis = id; - if (id === '_index_') { - axis = indexAxis; - } else if (id === '_value_') { - axis = indexAxis === 'x' ? 'y' : 'x'; - } - return axis; -} - -function getDefaultScaleIDFromAxis(axis, indexAxis) { - return axis === indexAxis ? '_index_' : '_value_'; -} - -function mergeScaleConfig(config, options) { - options = options || {}; - const chartDefaults = defaults[config.type] || {scales: {}}; - const configScales = options.scales || {}; - const chartIndexAxis = getIndexAxis(config.type, options); - const firstIDs = Object.create(null); - const scales = Object.create(null); - - // First figure out first scale id's per axis. - Object.keys(configScales).forEach(id => { - const scaleConf = configScales[id]; - const axis = determineAxis(id, scaleConf); - const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis); - firstIDs[axis] = firstIDs[axis] || id; - scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, chartDefaults.scales[axis], chartDefaults.scales[defaultId]]); - }); - - // Backward compatibility - if (options.scale) { - scales[options.scale.id || 'r'] = mergeIf(Object.create(null), [{axis: 'r'}, options.scale, chartDefaults.scales.r]); - firstIDs.r = firstIDs.r || options.scale.id || 'r'; - } - - // Then merge dataset defaults to scale configs - config.data.datasets.forEach(dataset => { - const type = dataset.type || config.type; - const indexAxis = dataset.indexAxis || getIndexAxis(type, options); - const datasetDefaults = defaults[type] || {}; - const defaultScaleOptions = datasetDefaults.scales || {}; - Object.keys(defaultScaleOptions).forEach(defaultID => { - const axis = getAxisFromDefaultScaleID(defaultID, indexAxis); - const id = dataset[axis + 'AxisID'] || firstIDs[axis] || axis; - scales[id] = scales[id] || Object.create(null); - mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]); - }); - }); - - // apply scale defaults, if not overridden by dataset defaults - Object.keys(scales).forEach(key => { - const scale = scales[key]; - mergeIf(scale, [defaults.scales[scale.type], defaults.scale]); - }); - - return scales; -} - -/** - * Recursively merge the given config objects as the root options by handling - * default scale options for the `scales` and `scale` properties, then returns - * a deep copy of the result, thus doesn't alter inputs. - */ -function mergeConfig(...args/* config objects ... */) { - return merge(Object.create(null), args, { - merger(key, target, source, options) { - if (key !== 'scales' && key !== 'scale') { - _merger(key, target, source, options); - } - } - }); -} - -function initConfig(config) { - config = config || {}; - - // Do NOT use mergeConfig for the data object because this method merges arrays - // and so would change references to labels and datasets, preventing data updates. - const data = config.data = config.data || {datasets: [], labels: []}; - data.datasets = data.datasets || []; - data.labels = data.labels || []; - - const scaleConfig = mergeScaleConfig(config, config.options); - - const options = config.options = mergeConfig( - defaults, - defaults[config.type], - config.options || {}); - - options.hover = merge(Object.create(null), [ - defaults.interaction, - defaults.hover, - options.interaction, - options.hover - ]); - - options.scales = scaleConfig; - - options.title = (options.title !== false) && merge(Object.create(null), [ - defaults.plugins.title, - options.title - ]); - options.tooltips = (options.tooltips !== false) && merge(Object.create(null), [ - defaults.interaction, - defaults.plugins.tooltip, - options.interaction, - options.tooltips - ]); - - return config; -} - -function isAnimationDisabled(config) { - return !config.animation; -} - -function updateConfig(chart) { - let newOptions = chart.options; - - each(chart.scales, (scale) => { - layouts.removeBox(chart, scale); - }); - - const scaleConfig = mergeScaleConfig(chart.config, newOptions); - - newOptions = mergeConfig( - defaults, - defaults[chart.config.type], - newOptions); - - chart.options = chart.config.options = newOptions; - chart.options.scales = scaleConfig; - - chart._animationsDisabled = isAnimationDisabled(newOptions); -} - const KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea']; function positionIsHorizontal(position, axis) { return position === 'top' || position === 'bottom' || (KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x'); } -function axisFromPosition(position) { - if (position === 'top' || position === 'bottom') { - return 'x'; - } - if (position === 'left' || position === 'right') { - return 'y'; - } -} - -function determineAxis(id, scaleOptions) { - if (id === 'x' || id === 'y' || id === 'r') { - return id; - } - return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id.charAt(0).toLowerCase(); -} - function compare2Level(l1, l2) { return function(a, b) { return a[l1] === b[l1] @@ -235,7 +73,7 @@ class Chart { constructor(item, config) { const me = this; - config = initConfig(config); + this.config = config = new Config(config); const initialCanvas = getCanvas(item); const existingChart = Chart.getChart(initialCanvas); if (existingChart) { @@ -255,7 +93,6 @@ class Chart { this.id = uid(); this.ctx = context; this.canvas = canvas; - this.config = config; this.width = width; this.height = height; this.aspectRatio = height ? width / height : null; @@ -266,7 +103,6 @@ class Chart { this.boxes = []; this.currentDevicePixelRatio = undefined; this.chartArea = undefined; - this.data = undefined; this._active = []; this._lastEvent = undefined; /** @type {{attach?: function, detach?: function, resize?: function}} */ @@ -279,20 +115,11 @@ class Chart { this.$proxies = {}; this._hiddenIndices = {}; this.attached = false; + this._animationsDisabled = undefined; // Add the chart instance to the global namespace Chart.instances[me.id] = me; - // Define alias to the config data: `chart.data === chart.config.data` - Object.defineProperty(me, 'data', { - get() { - return me.config.data; - }, - set(value) { - me.config.data = value; - } - }); - if (!context || !canvas) { // The given item is not a compatible context2d element, let's return before finalizing // the chart initialization but after setting basic chart / controller properties that @@ -311,6 +138,14 @@ class Chart { } } + get data() { + return this.config.data; + } + + set data(data) { + this.config.data = data; + } + /** * @private */ @@ -592,7 +427,13 @@ class Chart { me._updating = true; - updateConfig(me); + each(me.scales, (scale) => { + layouts.removeBox(me, scale); + }); + + me.config.update(me.options); + me.options = me.config.options; + me._animationsDisabled = !me.options.animation; me.ensureScalesHaveIDs(); me.buildOrUpdateScales();
true
Other
chartjs
Chart.js
6dbb7e74462d5b7dedf2124a622a3e678964dd83.json
Move config handling to a dedicated script (#7939) * Split core.config.js out of core.controller.js * Remove side effects from config.js * Turn config into a class * Refactor config merging as includeDefaults
src/core/core.plugins.js
@@ -50,7 +50,7 @@ export default class PluginService { return this._cache; } - const config = (chart && chart.config) || {}; + const config = chart && chart.config; const options = (config.options && config.options.plugins) || {}; const plugins = allPlugins(config); const descriptors = createDescriptors(plugins, options); @@ -61,6 +61,9 @@ export default class PluginService { } } +/** + * @param {import("./core.config").default} config + */ function allPlugins(config) { const plugins = []; const keys = Object.keys(registry.plugins.items);
true
Other
chartjs
Chart.js
58d1911d059239b52be8f309f8249f7b4e6dbb95.json
Add args.mode to before/after update plugin hooks (#7949)
docs/docs/getting-started/v3-migration.md
@@ -487,3 +487,8 @@ All helpers are now exposed in a flat hierarchy, e.g., `Chart.helpers.canvas.cli * `Chart.platforms` is an object that contains two usable platform classes, `BasicPlatform` and `DomPlatform`. It also contains `BasePlatform`, a class that all platforms must extend from. * If the canvas passed in is an instance of `OffscreenCanvas`, the `BasicPlatform` is automatically used. * `isAttached` method was added to platform. + +#### IPlugin interface + +* `afterDatasetsUpdate`, `afterUpdate`, `beforeDatasetsUpdate`, and `beforeUpdate` now receive `args` object as second argument. `options` argument is always the last and thus was moved from 2nd to 3rd place. +* `afterEvent` and `beforeEvent` now receive a wrapped `event` as the second argument. The native event is available via `event.native`.
true
Other
chartjs
Chart.js
58d1911d059239b52be8f309f8249f7b4e6dbb95.json
Add args.mode to before/after update plugin hooks (#7949)
src/core/core.controller.js
@@ -587,6 +587,7 @@ class Chart { update(mode) { const me = this; + const args = {mode}; let i, ilen; me._updating = true; @@ -600,7 +601,7 @@ class Chart { // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167 me._plugins.invalidate(); - if (me._plugins.notify(me, 'beforeUpdate') === false) { + if (me._plugins.notify(me, 'beforeUpdate', [args]) === false) { return; } @@ -622,7 +623,7 @@ class Chart { me._updateDatasets(mode); // Do this before render so that any plugins that need final scale updates can use it - me._plugins.notify(me, 'afterUpdate'); + me._plugins.notify(me, 'afterUpdate', [args]); me._layers.sort(compare2Level('z', '_idx')); @@ -675,16 +676,17 @@ class Chart { _updateDatasets(mode) { const me = this; const isFunction = typeof mode === 'function'; + const args = {mode}; - if (me._plugins.notify(me, 'beforeDatasetsUpdate') === false) { + if (me._plugins.notify(me, 'beforeDatasetsUpdate', [args]) === false) { return; } for (let i = 0, ilen = me.data.datasets.length; i < ilen; ++i) { me._updateDataset(i, isFunction ? mode({datasetIndex: i}) : mode); } - me._plugins.notify(me, 'afterDatasetsUpdate'); + me._plugins.notify(me, 'afterDatasetsUpdate', [args]); } /**
true
Other
chartjs
Chart.js
58d1911d059239b52be8f309f8249f7b4e6dbb95.json
Add args.mode to before/after update plugin hooks (#7949)
src/core/core.plugins.js
@@ -126,6 +126,8 @@ function createDescriptors(plugins, options) { * @desc Called before updating `chart`. If any plugin returns `false`, the update * is cancelled (and thus subsequent render(s)) until another `update` is triggered. * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {string} args.mode - The update mode * @param {object} options - The plugin options. * @returns {boolean} `false` to cancel the chart update. */ @@ -134,6 +136,8 @@ function createDescriptors(plugins, options) { * @desc Called after `chart` has been updated and before rendering. Note that this * hook will not be called if the chart update has been previously cancelled. * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {string} args.mode - The update mode * @param {object} options - The plugin options. */ /** @@ -148,6 +152,8 @@ function createDescriptors(plugins, options) { * @desc Called before updating the `chart` datasets. If any plugin returns `false`, * the datasets update is cancelled until another `update` is triggered. * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {string} args.mode - The update mode * @param {object} options - The plugin options. * @returns {boolean} false to cancel the datasets update. * @since version 2.1.5 @@ -157,6 +163,8 @@ function createDescriptors(plugins, options) { * @desc Called after the `chart` datasets have been updated. Note that this hook * will not be called if the datasets update has been previously cancelled. * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {string} args.mode - The update mode * @param {object} options - The plugin options. * @since version 2.1.5 */ @@ -168,6 +176,7 @@ function createDescriptors(plugins, options) { * @param {object} args - The call arguments. * @param {number} args.index - The dataset index. * @param {object} args.meta - The dataset metadata. + * @param {string} args.mode - The update mode * @param {object} options - The plugin options. * @returns {boolean} `false` to cancel the chart datasets drawing. */ @@ -179,6 +188,7 @@ function createDescriptors(plugins, options) { * @param {object} args - The call arguments. * @param {number} args.index - The dataset index. * @param {object} args.meta - The dataset metadata. + * @param {string} args.mode - The update mode * @param {object} options - The plugin options. */ /**
true
Other
chartjs
Chart.js
58d1911d059239b52be8f309f8249f7b4e6dbb95.json
Add args.mode to before/after update plugin hooks (#7949)
src/plugins/plugin.filler.js
@@ -525,7 +525,7 @@ function doFill(ctx, cfg) { export default { id: 'filler', - afterDatasetsUpdate(chart, options) { + afterDatasetsUpdate(chart, _args, options) { const count = (chart.data.datasets || []).length; const propagate = options.propagate; const sources = [];
true
Other
chartjs
Chart.js
58d1911d059239b52be8f309f8249f7b4e6dbb95.json
Add args.mode to before/after update plugin hooks (#7949)
types/core/index.d.ts
@@ -1,853 +1,859 @@ import { BasePlatform } from '../platform'; import { - Color, - EasingFunction, - IChartArea, - IChartComponent, - IFontSpec, - IPoint, - Scriptable, - TimeUnit, - IEvent, + Color, + EasingFunction, + IChartArea, + IChartComponent, + IFontSpec, + IPoint, + Scriptable, + TimeUnit, + IEvent, } from './interfaces'; import { - DefaultDataPoint, - IChartConfiguration, - IChartData, - IChartDataset, - IChartOptions, - IChartType, - IScaleOptions + DefaultDataPoint, + IChartConfiguration, + IChartData, + IChartDataset, + IChartOptions, + IChartType, + IScaleOptions } from '../interfaces'; export interface IDateAdapter { - /** - * Returns a map of time formats for the supported formatting units defined - * in Unit as well as 'datetime' representing a detailed date/time string. - * @returns {{string: string}} - */ - formats(): { [key: string]: string }; - /** - * Parses the given `value` and return the associated timestamp. - * @param {any} value - the value to parse (usually comes from the data) - * @param {string} [format] - the expected data format - */ - parse(value: any, format?: TimeUnit): number | null; - /** - * Returns the formatted date in the specified `format` for a given `timestamp`. - * @param {number} timestamp - the timestamp to format - * @param {string} format - the date/time token - * @return {string} - */ - format(timestamp: number, format: TimeUnit): string; - /** - * Adds the specified `amount` of `unit` to the given `timestamp`. - * @param {number} timestamp - the input timestamp - * @param {number} amount - the amount to add - * @param {Unit} unit - the unit as string - * @return {number} - */ - add(timestamp: number, amount: number, unit: TimeUnit): number; - /** - * Returns the number of `unit` between the given timestamps. - * @param {number} a - the input timestamp (reference) - * @param {number} b - the timestamp to subtract - * @param {Unit} unit - the unit as string - * @return {number} - */ - diff(a: number, b: number, unit: TimeUnit): number; - /** - * Returns start of `unit` for the given `timestamp`. - * @param {number} timestamp - the input timestamp - * @param {Unit|'isoWeek'} unit - the unit as string - * @param {number} [weekday] - the ISO day of the week with 1 being Monday - * and 7 being Sunday (only needed if param *unit* is `isoWeek`). - * @return {number} - */ - startOf(timestamp: number, unit: TimeUnit | 'isoWeek', weekday?: number): number; - /** - * Returns end of `unit` for the given `timestamp`. - * @param {number} timestamp - the input timestamp - * @param {Unit|'isoWeek'} unit - the unit as string - * @return {number} - */ - endOf(timestamp: number, unit: TimeUnit | 'isoWeek'): number; + /** + * Returns a map of time formats for the supported formatting units defined + * in Unit as well as 'datetime' representing a detailed date/time string. + * @returns {{string: string}} + */ + formats(): { [key: string]: string }; + /** + * Parses the given `value` and return the associated timestamp. + * @param {any} value - the value to parse (usually comes from the data) + * @param {string} [format] - the expected data format + */ + parse(value: any, format?: TimeUnit): number | null; + /** + * Returns the formatted date in the specified `format` for a given `timestamp`. + * @param {number} timestamp - the timestamp to format + * @param {string} format - the date/time token + * @return {string} + */ + format(timestamp: number, format: TimeUnit): string; + /** + * Adds the specified `amount` of `unit` to the given `timestamp`. + * @param {number} timestamp - the input timestamp + * @param {number} amount - the amount to add + * @param {Unit} unit - the unit as string + * @return {number} + */ + add(timestamp: number, amount: number, unit: TimeUnit): number; + /** + * Returns the number of `unit` between the given timestamps. + * @param {number} a - the input timestamp (reference) + * @param {number} b - the timestamp to subtract + * @param {Unit} unit - the unit as string + * @return {number} + */ + diff(a: number, b: number, unit: TimeUnit): number; + /** + * Returns start of `unit` for the given `timestamp`. + * @param {number} timestamp - the input timestamp + * @param {Unit|'isoWeek'} unit - the unit as string + * @param {number} [weekday] - the ISO day of the week with 1 being Monday + * and 7 being Sunday (only needed if param *unit* is `isoWeek`). + * @return {number} + */ + startOf(timestamp: number, unit: TimeUnit | 'isoWeek', weekday?: number): number; + /** + * Returns end of `unit` for the given `timestamp`. + * @param {number} timestamp - the input timestamp + * @param {Unit|'isoWeek'} unit - the unit as string + * @return {number} + */ + endOf(timestamp: number, unit: TimeUnit | 'isoWeek'): number; } export interface DateAdapter extends IDateAdapter { - readonly options: any; + readonly options: any; } export const DateAdapter: { - prototype: DateAdapter; - new (options: any): DateAdapter; - override(members: Partial<IDateAdapter>): void; + prototype: DateAdapter; + new(options: any): DateAdapter; + override(members: Partial<IDateAdapter>): void; }; export const _adapters: { - _date: DateAdapter; + _date: DateAdapter; }; export class Animation { - constructor(cfg: any, target: any, prop: string, to?: any); - active(): boolean; - update(cfg: any, to: any, date: number): void; - cancel(): void; - tick(date: number): void; + constructor(cfg: any, target: any, prop: string, to?: any); + active(): boolean; + update(cfg: any, to: any, date: number): void; + cancel(): void; + tick(date: number): void; } export interface IAnimationEvent { - chart: Chart; - numSteps: number; - currentState: number; + chart: Chart; + numSteps: number; + currentState: number; } export class Animator { - listen(chart: Chart, event: 'complete' | 'progress', cb: (event: IAnimationEvent) => void): void; - add(chart: Chart, items: readonly Animation[]): void; - has(chart: Chart): boolean; - start(chart: Chart): void; - running(chart: Chart): boolean; - stop(chart: Chart): void; - remove(chart: Chart): boolean; + listen(chart: Chart, event: 'complete' | 'progress', cb: (event: IAnimationEvent) => void): void; + add(chart: Chart, items: readonly Animation[]): void; + has(chart: Chart): boolean; + start(chart: Chart): void; + running(chart: Chart): boolean; + stop(chart: Chart): void; + remove(chart: Chart): boolean; } export class Animations { - constructor(chart: Chart, animations: {}); - configure(animations: {}): void; - update(target: any, values: any): undefined | boolean; + constructor(chart: Chart, animations: {}); + configure(animations: {}): void; + update(target: any, values: any): undefined | boolean; } export interface IAnimationCommonSpec { - /** - * The number of milliseconds an animation takes. - * @default 1000 - */ - duration: number; - /** - * Easing function to use - * @default 'easeOutQuart' - */ - easing: EasingFunction; - - /** - * Running animation count + FPS display in upper left corner of the chart. - * @default false - */ - debug: boolean; - - /** - * Delay before starting the animations. - * @default 0 - */ - delay: number; - - /** - * If set to true, the animations loop endlessly. - * @default false - */ - loop: boolean; + /** + * The number of milliseconds an animation takes. + * @default 1000 + */ + duration: number; + /** + * Easing function to use + * @default 'easeOutQuart' + */ + easing: EasingFunction; + + /** + * Running animation count + FPS display in upper left corner of the chart. + * @default false + */ + debug: boolean; + + /** + * Delay before starting the animations. + * @default 0 + */ + delay: number; + + /** + * If set to true, the animations loop endlessly. + * @default false + */ + loop: boolean; } export interface IAnimationPropertySpec extends IAnimationCommonSpec { - properties: string[]; - - /** - * Type of property, determines the interpolator used. Possible values: 'number', 'color' and 'boolean'. Only really needed for 'color', because typeof does not get that right. - */ - type: 'color' | 'number' | 'boolean'; - - fn: <T>(from: T, to: T, factor: number) => T; - - /** - * Start value for the animation. Current value is used when undefined - */ - from: Color | number | boolean; - /** - * - */ - to: Color | number | boolean; + properties: string[]; + + /** + * Type of property, determines the interpolator used. Possible values: 'number', 'color' and 'boolean'. Only really needed for 'color', because typeof does not get that right. + */ + type: 'color' | 'number' | 'boolean'; + + fn: <T>(from: T, to: T, factor: number) => T; + + /** + * Start value for the animation. Current value is used when undefined + */ + from: Color | number | boolean; + /** + * + */ + to: Color | number | boolean; } export type IAnimationSpecContainer = IAnimationCommonSpec & { - [prop: string]: IAnimationPropertySpec; + [prop: string]: IAnimationPropertySpec; }; export type IAnimationOptions = IAnimationSpecContainer & { - /** - * Callback called on each step of an animation. - */ - onProgress: (this: Chart, event: IAnimationEvent) => void; - /** - *Callback called when all animations are completed. - */ - onComplete: (this: Chart, event: IAnimationEvent) => void; - - active: IAnimationSpecContainer; - hide: IAnimationSpecContainer; - reset: IAnimationSpecContainer; - resize: IAnimationSpecContainer; - show: IAnimationSpecContainer; + /** + * Callback called on each step of an animation. + */ + onProgress: (this: Chart, event: IAnimationEvent) => void; + /** + *Callback called when all animations are completed. + */ + onComplete: (this: Chart, event: IAnimationEvent) => void; + + active: IAnimationSpecContainer; + hide: IAnimationSpecContainer; + reset: IAnimationSpecContainer; + resize: IAnimationSpecContainer; + show: IAnimationSpecContainer; }; export interface IChartAnimationOptions { - animation: Scriptable<IAnimationOptions>; - datasets: { - animation: Scriptable<IAnimationOptions>; - }; + animation: Scriptable<IAnimationOptions>; + datasets: { + animation: Scriptable<IAnimationOptions>; + }; } export interface IChartMeta<E extends Element = Element, DSE extends Element = Element> { - type: string; - controller: DatasetController; - order: number; + type: string; + controller: DatasetController; + order: number; - label: string; - index: number; - visible: boolean; + label: string; + index: number; + visible: boolean; - stack: number; + stack: number; - indexAxis: 'x' | 'y'; + indexAxis: 'x' | 'y'; - data: E[]; - dataset?: DSE; + data: E[]; + dataset?: DSE; - hidden: boolean; + hidden: boolean; - xAxisID?: string; - yAxisID?: string; - rAxisID?: string; - iAxisID: string; - vAxisID: string; + xAxisID?: string; + yAxisID?: string; + rAxisID?: string; + iAxisID: string; + vAxisID: string; - xScale?: Scale; - yScale?: Scale; - rScale?: Scale; - iScale?: Scale; - vScale?: Scale; + xScale?: Scale; + yScale?: Scale; + rScale?: Scale; + iScale?: Scale; + vScale?: Scale; - _sorted: boolean; - _stacked: boolean; - _parsed: any[]; + _sorted: boolean; + _stacked: boolean; + _parsed: any[]; } export interface IParsingOptions { - parsing: - | { - [key: string]: string; - } - | false; + parsing: + | { + [key: string]: string; + } + | false; } export interface ActiveDataPoint { - datasetIndex: number; - index: number; + datasetIndex: number; + index: number; } export interface ActiveElement extends ActiveDataPoint { - element: Element; + element: Element; } export declare class Chart< - TYPE extends IChartType = IChartType, - DATA extends unknown[] = DefaultDataPoint<TYPE>, - LABEL = string -> { - readonly platform: BasePlatform; - readonly id: string; - readonly canvas: HTMLCanvasElement; - readonly ctx: CanvasRenderingContext2D; - readonly config: IChartConfiguration<TYPE, DATA, LABEL> - readonly width: number; - readonly height: number; - readonly aspectRatio: number; - readonly boxes: ILayoutItem[]; - readonly currentDevicePixelRatio: number; - readonly chartArea: IChartArea; - readonly scales: { [key: string]: Scale }; - readonly scale: Scale | undefined; - readonly attached: boolean; - - data: IChartData<TYPE, DATA, LABEL>; - options: IChartOptions<TYPE>; - - constructor(item: ChartItem, config: IChartConfiguration<TYPE, DATA, LABEL>); - - clear(): this; - stop(): this; - - resize(silent: boolean, width: number, height: number): void; - ensureScalesHaveIDs(): void; - buildOrUpdateScales(): void; - buildOrUpdateControllers(): void; - reset(): void; - update(mode?: UpdateMode): void; - render(): void; - draw(): void; - - getElementsAtEventForMode(e: Event, mode: string, options: IInteractionOptions, useFinalPosition: boolean): InteractionItem[]; - - getSortedVisibleDatasetMetas(): IChartMeta[]; - getDatasetMeta(datasetIndex: number): IChartMeta; - getVisibleDatasetCount(): number; - isDatasetVisible(datasetIndex: number): boolean; - setDatasetVisibility(datasetIndex: number, visible: boolean): void; - toggleDataVisibility(index: number): void; - getDataVisibility(index: number): boolean; - hide(datasetIndex: number): void; - show(datasetIndex: number): void; - - getActiveElements(): ActiveElement[]; - setActiveElements(active: ActiveDataPoint[]); - - destroy(): void; - toBase64Image(type?: string, quality?: any): string; - bindEvents(): void; - unbindEvents(): void; - updateHoverStyle(items: Element, mode: 'dataset', enabled: boolean): void; - - static readonly version: string; - static readonly instances: { [key: string]: Chart }; - static readonly registry: Registry; - static getChart(key: string | CanvasRenderingContext2D | HTMLCanvasElement) : Chart | undefined; - static register(...items: IChartComponentLike[]): void; - static unregister(...items: IChartComponentLike[]): void; + TYPE extends IChartType = IChartType, + DATA extends unknown[] = DefaultDataPoint<TYPE>, + LABEL = string + > { + readonly platform: BasePlatform; + readonly id: string; + readonly canvas: HTMLCanvasElement; + readonly ctx: CanvasRenderingContext2D; + readonly config: IChartConfiguration<TYPE, DATA, LABEL> + readonly width: number; + readonly height: number; + readonly aspectRatio: number; + readonly boxes: ILayoutItem[]; + readonly currentDevicePixelRatio: number; + readonly chartArea: IChartArea; + readonly scales: { [key: string]: Scale }; + readonly scale: Scale | undefined; + readonly attached: boolean; + + data: IChartData<TYPE, DATA, LABEL>; + options: IChartOptions<TYPE>; + + constructor(item: ChartItem, config: IChartConfiguration<TYPE, DATA, LABEL>); + + clear(): this; + stop(): this; + + resize(silent: boolean, width: number, height: number): void; + ensureScalesHaveIDs(): void; + buildOrUpdateScales(): void; + buildOrUpdateControllers(): void; + reset(): void; + update(mode?: UpdateMode): void; + render(): void; + draw(): void; + + getElementsAtEventForMode(e: Event, mode: string, options: IInteractionOptions, useFinalPosition: boolean): InteractionItem[]; + + getSortedVisibleDatasetMetas(): IChartMeta[]; + getDatasetMeta(datasetIndex: number): IChartMeta; + getVisibleDatasetCount(): number; + isDatasetVisible(datasetIndex: number): boolean; + setDatasetVisibility(datasetIndex: number, visible: boolean): void; + toggleDataVisibility(index: number): void; + getDataVisibility(index: number): boolean; + hide(datasetIndex: number): void; + show(datasetIndex: number): void; + + getActiveElements(): ActiveElement[]; + setActiveElements(active: ActiveDataPoint[]); + + destroy(): void; + toBase64Image(type?: string, quality?: any): string; + bindEvents(): void; + unbindEvents(): void; + updateHoverStyle(items: Element, mode: 'dataset', enabled: boolean): void; + + static readonly version: string; + static readonly instances: { [key: string]: Chart }; + static readonly registry: Registry; + static getChart(key: string | CanvasRenderingContext2D | HTMLCanvasElement): Chart | undefined; + static register(...items: IChartComponentLike[]): void; + static unregister(...items: IChartComponentLike[]): void; } export declare type ChartItem = - | string - | CanvasRenderingContext2D - | OffscreenCanvasRenderingContext2D - | HTMLCanvasElement - | OffscreenCanvas - | { canvas: HTMLCanvasElement | OffscreenCanvas } - | ArrayLike<CanvasRenderingContext2D | HTMLCanvasElement | OffscreenCanvas>; + | string + | CanvasRenderingContext2D + | OffscreenCanvasRenderingContext2D + | HTMLCanvasElement + | OffscreenCanvas + | { canvas: HTMLCanvasElement | OffscreenCanvas } + | ArrayLike<CanvasRenderingContext2D | HTMLCanvasElement | OffscreenCanvas>; export declare enum UpdateModeEnum { - resize = 'resize', - reset = 'reset', - none = 'none', - hide = 'hide', - show = 'show', - normal = 'normal', - active = 'active' + resize = 'resize', + reset = 'reset', + none = 'none', + hide = 'hide', + show = 'show', + normal = 'normal', + active = 'active' } export type UpdateMode = keyof typeof UpdateModeEnum; export class DatasetController<E extends Element = Element, DSE extends Element = Element> { - constructor(chart: Chart, datasetIndex: number); - - readonly chart: Chart; - readonly index: number; - readonly _cachedMeta: IChartMeta<E, DSE>; - enableOptionSharing: boolean; - - linkScales(): void; - getAllParsedValues(scale: Scale): number[]; - protected getLabelAndValue(index: number): { label: string; value: string }; - updateElements(elements: E[], start: number, count: number, mode: UpdateMode): void; - update(mode: UpdateMode): void; - updateIndex(datasetIndex: number): void; - protected getMaxOverflow(): boolean | number; - draw(): void; - reset(): void; - getDataset(): IChartDataset; - getMeta(): IChartMeta<E, DSE>; - getScaleForId(scaleID: string): Scale | undefined; - configure(): void; - initialize(): void; - addElements(): void; - buildOrUpdateElements(): void; - - getStyle(index: number, active: boolean): any; - protected resolveDatasetElementOptions(active: boolean): any; - protected resolveDataElementOptions(index: number, mode: UpdateMode): any; - /** - * Utility for checking if the options are shared and should be animated separately. - * @protected - */ - protected getSharedOptions(options: any): undefined | any; - /** - * Utility for determining if `options` should be included in the updated properties - * @protected - */ - protected includeOptions(mode: UpdateMode, sharedOptions: any): boolean; - /** - * Utility for updating an element with new properties, using animations when appropriate. - * @protected - */ - - protected updateElement(element: E | DSE, index: number | undefined, properties: any, mode: UpdateMode): void; - /** - * Utility to animate the shared options, that are potentially affecting multiple elements. - * @protected - */ - - protected updateSharedOptions(sharedOptions: any, mode: UpdateMode, newOptions: any): void; - removeHoverStyle(element: E, datasetIndex: number, index: number): void; - setHoverStyle(element: E, datasetIndex: number, index: number): void; - - parse(start: number, count: number): void; - protected parsePrimitiveData(meta: IChartMeta<E, DSE>, data: any[], start: number, count: number): any[]; - protected parseArrayData(meta: IChartMeta<E, DSE>, data: any[], start: number, count: number): any[]; - protected parseObjectData(meta: IChartMeta<E, DSE>, data: any[], start: number, count: number): any[]; - protected getParsed(index: number): any; - protected applyStack(scale: Scale, parsed: any[]): number; - protected updateRangeFromParsed( - range: { min: number; max: number }, - scale: Scale, - parsed: any[], - stack: boolean - ): void; - protected getMinMax(scale: Scale, canStack?: boolean): { min: number; max: number }; + constructor(chart: Chart, datasetIndex: number); + + readonly chart: Chart; + readonly index: number; + readonly _cachedMeta: IChartMeta<E, DSE>; + enableOptionSharing: boolean; + + linkScales(): void; + getAllParsedValues(scale: Scale): number[]; + protected getLabelAndValue(index: number): { label: string; value: string }; + updateElements(elements: E[], start: number, count: number, mode: UpdateMode): void; + update(mode: UpdateMode): void; + updateIndex(datasetIndex: number): void; + protected getMaxOverflow(): boolean | number; + draw(): void; + reset(): void; + getDataset(): IChartDataset; + getMeta(): IChartMeta<E, DSE>; + getScaleForId(scaleID: string): Scale | undefined; + configure(): void; + initialize(): void; + addElements(): void; + buildOrUpdateElements(): void; + + getStyle(index: number, active: boolean): any; + protected resolveDatasetElementOptions(active: boolean): any; + protected resolveDataElementOptions(index: number, mode: UpdateMode): any; + /** + * Utility for checking if the options are shared and should be animated separately. + * @protected + */ + protected getSharedOptions(options: any): undefined | any; + /** + * Utility for determining if `options` should be included in the updated properties + * @protected + */ + protected includeOptions(mode: UpdateMode, sharedOptions: any): boolean; + /** + * Utility for updating an element with new properties, using animations when appropriate. + * @protected + */ + + protected updateElement(element: E | DSE, index: number | undefined, properties: any, mode: UpdateMode): void; + /** + * Utility to animate the shared options, that are potentially affecting multiple elements. + * @protected + */ + + protected updateSharedOptions(sharedOptions: any, mode: UpdateMode, newOptions: any): void; + removeHoverStyle(element: E, datasetIndex: number, index: number): void; + setHoverStyle(element: E, datasetIndex: number, index: number): void; + + parse(start: number, count: number): void; + protected parsePrimitiveData(meta: IChartMeta<E, DSE>, data: any[], start: number, count: number): any[]; + protected parseArrayData(meta: IChartMeta<E, DSE>, data: any[], start: number, count: number): any[]; + protected parseObjectData(meta: IChartMeta<E, DSE>, data: any[], start: number, count: number): any[]; + protected getParsed(index: number): any; + protected applyStack(scale: Scale, parsed: any[]): number; + protected updateRangeFromParsed( + range: { min: number; max: number }, + scale: Scale, + parsed: any[], + stack: boolean + ): void; + protected getMinMax(scale: Scale, canStack?: boolean): { min: number; max: number }; } export interface IDatasetControllerChartComponent extends IChartComponent { - defaults: { - datasetElementType?: string | null | false; - dataElementType?: string | null | false; - dataElementOptions?: string[]; - datasetElementOptions?: string[] | { [key: string]: string }; - }; + defaults: { + datasetElementType?: string | null | false; + dataElementType?: string | null | false; + dataElementOptions?: string[]; + datasetElementOptions?: string[] | { [key: string]: string }; + }; } export interface Defaults { - readonly color: string; - readonly events: ('mousemove' | 'mouseout' | 'click' | 'touchstart' | 'touchmove')[]; - readonly font: IFontSpec; - readonly interaction: { - mode: InteractionMode | string; - intersect: boolean; - }; - readonly hover: { - onHover?: () => void; - mode?: InteractionMode | string; - intersect?: boolean; - }; - readonly maintainAspectRatio: boolean; - readonly onClick?: () => void; - readonly onHover?: () => void; - readonly responsive: boolean; - - readonly plugins: { [key: string]: any }; - readonly scale?: IScaleOptions; - readonly doughnut: any; - readonly scales: { [key: string]: IScaleOptions }; - readonly controllers: { [key: string]: any }; - - set(scope: string, values: any): any; - get(scope: string): any; - /** - * Routes the named defaults to fallback to another scope/name. - * This routing is useful when those target values, like defaults.color, are changed runtime. - * If the values would be copied, the runtime change would not take effect. By routing, the - * fallback is evaluated at each access, so its always up to date. - * - * Example: - * - * defaults.route('elements.arc', 'backgroundColor', '', 'color') - * - reads the backgroundColor from defaults.color when undefined locally - * - * @param scope Scope this route applies to. - * @param name Property name that should be routed to different namespace when not defined here. - * @param targetScope The namespace where those properties should be routed to. - * Empty string ('') is the root of defaults. - * @param targetName The target name in the target scope the property should be routed to. - */ - route(scope: string, name: string, targetScope: string, targetName: string): void; + readonly color: string; + readonly events: ('mousemove' | 'mouseout' | 'click' | 'touchstart' | 'touchmove')[]; + readonly font: IFontSpec; + readonly interaction: { + mode: InteractionMode | string; + intersect: boolean; + }; + readonly hover: { + onHover?: () => void; + mode?: InteractionMode | string; + intersect?: boolean; + }; + readonly maintainAspectRatio: boolean; + readonly onClick?: () => void; + readonly onHover?: () => void; + readonly responsive: boolean; + + readonly plugins: { [key: string]: any }; + readonly scale?: IScaleOptions; + readonly doughnut: any; + readonly scales: { [key: string]: IScaleOptions }; + readonly controllers: { [key: string]: any }; + + set(scope: string, values: any): any; + get(scope: string): any; + /** + * Routes the named defaults to fallback to another scope/name. + * This routing is useful when those target values, like defaults.color, are changed runtime. + * If the values would be copied, the runtime change would not take effect. By routing, the + * fallback is evaluated at each access, so its always up to date. + * + * Example: + * + * defaults.route('elements.arc', 'backgroundColor', '', 'color') + * - reads the backgroundColor from defaults.color when undefined locally + * + * @param scope Scope this route applies to. + * @param name Property name that should be routed to different namespace when not defined here. + * @param targetScope The namespace where those properties should be routed to. + * Empty string ('') is the root of defaults. + * @param targetName The target name in the target scope the property should be routed to. + */ + route(scope: string, name: string, targetScope: string, targetName: string): void; } export const defaults: Defaults; export interface Element<T = {}, O = {}> { - readonly x: number; - readonly y: number; - readonly active: boolean; - readonly options: O; - - tooltipPosition(useFinalPosition?: boolean): IPoint; - hasValue(): boolean; - getProps<P extends keyof T>(props: [P], final?: boolean): Pick<T, P>; - getProps<P extends keyof T, P2 extends keyof T>(props: [P, P2], final?: boolean): Pick<T, P | P2>; - getProps<P extends keyof T, P2 extends keyof T, P3 extends keyof T>( - props: [P, P2, P3], - final?: boolean - ): Pick<T, P | P2 | P3>; - getProps<P extends keyof T, P2 extends keyof T, P3 extends keyof T, P4 extends keyof T>( - props: [P, P2, P3, P4], - final?: boolean - ): Pick<T, P | P2 | P3 | P4>; - getProps<P extends keyof T, P2 extends keyof T, P3 extends keyof T, P4 extends keyof T, P5 extends keyof T>( - props: [P, P2, P3, P4, P5], - final?: boolean - ): Pick<T, P | P2 | P3 | P4 | P5>; - getProps(props: (keyof T)[], final?: boolean): T; + readonly x: number; + readonly y: number; + readonly active: boolean; + readonly options: O; + + tooltipPosition(useFinalPosition?: boolean): IPoint; + hasValue(): boolean; + getProps<P extends keyof T>(props: [P], final?: boolean): Pick<T, P>; + getProps<P extends keyof T, P2 extends keyof T>(props: [P, P2], final?: boolean): Pick<T, P | P2>; + getProps<P extends keyof T, P2 extends keyof T, P3 extends keyof T>( + props: [P, P2, P3], + final?: boolean + ): Pick<T, P | P2 | P3>; + getProps<P extends keyof T, P2 extends keyof T, P3 extends keyof T, P4 extends keyof T>( + props: [P, P2, P3, P4], + final?: boolean + ): Pick<T, P | P2 | P3 | P4>; + getProps<P extends keyof T, P2 extends keyof T, P3 extends keyof T, P4 extends keyof T, P5 extends keyof T>( + props: [P, P2, P3, P4, P5], + final?: boolean + ): Pick<T, P | P2 | P3 | P4 | P5>; + getProps(props: (keyof T)[], final?: boolean): T; } export const Element: { - prototype: Element; - new <T = {}, O = {}>(): Element<T, O>; + prototype: Element; + new <T = {}, O = {}>(): Element<T, O>; }; export interface IInteractionOptions { - axis?: string; - intersect?: boolean; + axis?: string; + intersect?: boolean; } export interface InteractionItem { - element: Element; - datasetIndex: number; - index: number; + element: Element; + datasetIndex: number; + index: number; } export type InteractionModeFunction = ( - chart: Chart, - e: IEvent, - options: IInteractionOptions, - useFinalPosition?: boolean + chart: Chart, + e: IEvent, + options: IInteractionOptions, + useFinalPosition?: boolean ) => InteractionItem[]; export interface IInteractionMode { - /** - * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something - * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item - */ - index: InteractionModeFunction; - - /** - * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something - * If the options.intersect is false, we find the nearest item and return the items in that dataset - */ - dataset: InteractionModeFunction; - /** - * Point mode returns all elements that hit test based on the event position - * of the event - */ - point: InteractionModeFunction; - /** - * nearest mode returns the element closest to the point - */ - nearest: InteractionModeFunction; - /** - * x mode returns the elements that hit-test at the current x coordinate - */ - x: InteractionModeFunction; - /** - * y mode returns the elements that hit-test at the current y coordinate - */ - y: InteractionModeFunction; + /** + * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something + * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item + */ + index: InteractionModeFunction; + + /** + * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something + * If the options.intersect is false, we find the nearest item and return the items in that dataset + */ + dataset: InteractionModeFunction; + /** + * Point mode returns all elements that hit test based on the event position + * of the event + */ + point: InteractionModeFunction; + /** + * nearest mode returns the element closest to the point + */ + nearest: InteractionModeFunction; + /** + * x mode returns the elements that hit-test at the current x coordinate + */ + x: InteractionModeFunction; + /** + * y mode returns the elements that hit-test at the current y coordinate + */ + y: InteractionModeFunction; } export type InteractionMode = keyof IInteractionMode; export const Interaction: { - modes: IInteractionMode; + modes: IInteractionMode; }; export type LayoutPosition = 'left' | 'top' | 'right' | 'chartArea'; export interface ILayoutItem { - /** - * The position of the item in the chart layout. Possible values are - */ - position: LayoutPosition; - /** - * The weight used to sort the item. Higher weights are further away from the chart area - */ - weight: number; - /** - * if true, and the item is horizontal, then push vertical boxes down - */ - fullWidth: boolean; - /** - * returns true if the layout item is horizontal (ie. top or bottom) - */ - isHorizontal(): boolean; - /** - * Takes two parameters: width and height. Returns size of item - * @param width - * @param height - */ - update(width: number, height: number): number; - - /** - * Draws the element - */ - draw(): void; - - /** - * Returns an object with padding on the edges - */ - getPadding?(): IChartArea; - - /** - * Width of item. Must be valid after update() - */ - width: number; - /** - * Height of item. Must be valid after update() - */ - height: number; - /** - * Left edge of the item. Set by layout system and cannot be used in update - */ - left: number; - /** - * Top edge of the item. Set by layout system and cannot be used in update - */ - top: number; - /** - * Right edge of the item. Set by layout system and cannot be used in update - */ - right: number; - /** - * Bottom edge of the item. Set by layout system and cannot be used in update - */ - bottom: number; + /** + * The position of the item in the chart layout. Possible values are + */ + position: LayoutPosition; + /** + * The weight used to sort the item. Higher weights are further away from the chart area + */ + weight: number; + /** + * if true, and the item is horizontal, then push vertical boxes down + */ + fullWidth: boolean; + /** + * returns true if the layout item is horizontal (ie. top or bottom) + */ + isHorizontal(): boolean; + /** + * Takes two parameters: width and height. Returns size of item + * @param width + * @param height + */ + update(width: number, height: number): number; + + /** + * Draws the element + */ + draw(): void; + + /** + * Returns an object with padding on the edges + */ + getPadding?(): IChartArea; + + /** + * Width of item. Must be valid after update() + */ + width: number; + /** + * Height of item. Must be valid after update() + */ + height: number; + /** + * Left edge of the item. Set by layout system and cannot be used in update + */ + left: number; + /** + * Top edge of the item. Set by layout system and cannot be used in update + */ + top: number; + /** + * Right edge of the item. Set by layout system and cannot be used in update + */ + right: number; + /** + * Bottom edge of the item. Set by layout system and cannot be used in update + */ + bottom: number; } export const layouts: { - /** - * Register a box to a chart. - * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title. - * @param {Chart} chart - the chart to use - * @param {ILayoutItem} item - the item to add to be laid out - */ - addBox(chart: Chart, item: ILayoutItem): void; - - /** - * Remove a layoutItem from a chart - * @param {Chart} chart - the chart to remove the box from - * @param {ILayoutItem} layoutItem - the item to remove from the layout - */ - removeBox(chart: Chart, layoutItem: ILayoutItem): void; - - /** - * Sets (or updates) options on the given `item`. - * @param {Chart} chart - the chart in which the item lives (or will be added to) - * @param {ILayoutItem} item - the item to configure with the given options - * @param options - the new item options. - */ - configure( - chart: Chart, - item: ILayoutItem, - options: { fullWidth?: number; position?: LayoutPosition; weight?: number } - ): void; - - /** - * Fits boxes of the given chart into the given size by having each box measure itself - * then running a fitting algorithm - * @param {Chart} chart - the chart - * @param {number} width - the width to fit into - * @param {number} height - the height to fit into - */ - update(chart: Chart, width: number, height: number): void; + /** + * Register a box to a chart. + * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title. + * @param {Chart} chart - the chart to use + * @param {ILayoutItem} item - the item to add to be laid out + */ + addBox(chart: Chart, item: ILayoutItem): void; + + /** + * Remove a layoutItem from a chart + * @param {Chart} chart - the chart to remove the box from + * @param {ILayoutItem} layoutItem - the item to remove from the layout + */ + removeBox(chart: Chart, layoutItem: ILayoutItem): void; + + /** + * Sets (or updates) options on the given `item`. + * @param {Chart} chart - the chart in which the item lives (or will be added to) + * @param {ILayoutItem} item - the item to configure with the given options + * @param options - the new item options. + */ + configure( + chart: Chart, + item: ILayoutItem, + options: { fullWidth?: number; position?: LayoutPosition; weight?: number } + ): void; + + /** + * Fits boxes of the given chart into the given size by having each box measure itself + * then running a fitting algorithm + * @param {Chart} chart - the chart + * @param {number} width - the width to fit into + * @param {number} height - the height to fit into + */ + update(chart: Chart, width: number, height: number): void; }; export interface PluginService { - /** - * Calls enabled plugins for `chart` on the specified hook and with the given args. - * This method immediately returns as soon as a plugin explicitly returns false. The - * returned value can be used, for instance, to interrupt the current action. - * @param {Chart} chart - The chart instance for which plugins should be called. - * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate'). - * @param {Array} [args] - Extra arguments to apply to the hook call. - * @returns {boolean} false if any of the plugins return false, else returns true. - */ - notify(chart: Chart, hook: string, args: any[]): boolean; - invalidate(): void; + /** + * Calls enabled plugins for `chart` on the specified hook and with the given args. + * This method immediately returns as soon as a plugin explicitly returns false. The + * returned value can be used, for instance, to interrupt the current action. + * @param {Chart} chart - The chart instance for which plugins should be called. + * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate'). + * @param {Array} [args] - Extra arguments to apply to the hook call. + * @returns {boolean} false if any of the plugins return false, else returns true. + */ + notify(chart: Chart, hook: string, args: any[]): boolean; + invalidate(): void; } export interface IPlugin<O = {}> { - id: string; - - /** - * @desc Called before initializing `chart`. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - */ - beforeInit?(chart: Chart, options: O): void; - /** - * @desc Called after `chart` has been initialized and before the first update. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - */ - afterInit?(chart: Chart, options: O): void; - /** - * @desc Called before updating `chart`. If any plugin returns `false`, the update - * is cancelled (and thus subsequent render(s)) until another `update` is triggered. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart update. - */ - beforeUpdate?(chart: Chart, options: O): boolean | void; - /** - * @desc Called after `chart` has been updated and before rendering. Note that this - * hook will not be called if the chart update has been previously cancelled. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - */ - afterUpdate?(chart: Chart, options: O): void; - /** - * @desc Called during chart reset - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - * @since version 3.0.0 - */ - reset?(chart: Chart, options: O): void; - /** - * @desc Called before updating the `chart` datasets. If any plugin returns `false`, - * the datasets update is cancelled until another `update` is triggered. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - * @returns {boolean} false to cancel the datasets update. - * @since version 2.1.5 - */ - beforeDatasetsUpdate?(chart: Chart, options: O): boolean | void; - /** - * @desc Called after the `chart` datasets have been updated. Note that this hook - * will not be called if the datasets update has been previously cancelled. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - * @since version 2.1.5 - */ - afterDatasetsUpdate?(chart: Chart, options: O): void; - /** - * @desc Called before updating the `chart` dataset at the given `args.index`. If any plugin - * returns `false`, the datasets update is cancelled until another `update` is triggered. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {number} args.index - The dataset index. - * @param {object} args.meta - The dataset metadata. - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart datasets drawing. - */ - beforeDatasetUpdate?(chart: Chart, args: { index: number; meta: IChartMeta }, options: O): boolean | void; - /** - * @desc Called after the `chart` datasets at the given `args.index` has been updated. Note - * that this hook will not be called if the datasets update has been previously cancelled. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {number} args.index - The dataset index. - * @param {object} args.meta - The dataset metadata. - * @param {object} options - The plugin options. - */ - afterDatasetUpdate?(chart: Chart, args: { index: number; meta: IChartMeta }, options: O): void; - /** - * @desc Called before laying out `chart`. If any plugin returns `false`, - * the layout update is cancelled until another `update` is triggered. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart layout. - */ - beforeLayout?(chart: Chart, options: O): boolean | void; - /** - * @desc Called after the `chart` has been laid out. Note that this hook will not - * be called if the layout update has been previously cancelled. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - */ - afterLayout?(chart: Chart, options: O): void; - /** - * @desc Called before rendering `chart`. If any plugin returns `false`, - * the rendering is cancelled until another `render` is triggered. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart rendering. - */ - beforeRender?(chart: Chart, options: O): boolean | void; - /** - * @desc Called after the `chart` has been fully rendered (and animation completed). Note - * that this hook will not be called if the rendering has been previously cancelled. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - */ - afterRender?(chart: Chart, options: O): void; - /** - * @desc Called before drawing `chart` at every animation frame. If any plugin returns `false`, - * the frame drawing is cancelled untilanother `render` is triggered. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart drawing. - */ - beforeDraw?(chart: Chart, options: O): boolean | void; - /** - * @desc Called after the `chart` has been drawn. Note that this hook will not be called - * if the drawing has been previously cancelled. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - */ - afterDraw?(chart: Chart, options: O): void; - /** - * @desc Called before drawing the `chart` datasets. If any plugin returns `false`, - * the datasets drawing is cancelled until another `render` is triggered. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart datasets drawing. - */ - beforeDatasetsDraw?(chart: Chart, options: O): boolean | void; - /** - * @desc Called after the `chart` datasets have been drawn. Note that this hook - * will not be called if the datasets drawing has been previously cancelled. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - */ - afterDatasetsDraw?(chart: Chart, options: O): void; - /** - * @desc Called before drawing the `chart` dataset at the given `args.index` (datasets - * are drawn in the reverse order). If any plugin returns `false`, the datasets drawing - * is cancelled until another `render` is triggered. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {number} args.index - The dataset index. - * @param {object} args.meta - The dataset metadata. - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart datasets drawing. - */ - beforeDatasetDraw?(chart: Chart, args: { index: number; meta: IChartMeta }, options: O): boolean | void; - /** - * @desc Called after the `chart` datasets at the given `args.index` have been drawn - * (datasets are drawn in the reverse order). Note that this hook will not be called - * if the datasets drawing has been previously cancelled. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {number} args.index - The dataset index. - * @param {object} args.meta - The dataset metadata. - * @param {object} options - The plugin options. - */ - afterDatasetDraw?(chart: Chart, args: { index: number; meta: IChartMeta }, options: O): void; - /** - * @desc Called before processing the specified `event`. If any plugin returns `false`, - * the event will be discarded. - * @param {Chart} chart - The chart instance. - * @param {IEvent} event - The event object. - * @param {object} options - The plugin options. - * @param {boolean} replay - True if this event is replayed from `Chart.update` - */ - beforeEvent?(chart: Chart, event: IEvent, options: O, replay: boolean): void; - /** - * @desc Called after the `event` has been consumed. Note that this hook - * will not be called if the `event` has been previously discarded. - * @param {Chart} chart - The chart instance. - * @param {IEvent} event - The event object. - * @param {object} options - The plugin options. - * @param {boolean} replay - True if this event is replayed from `Chart.update` - */ - afterEvent?(chart: Chart, event: IEvent, options: O, replay: boolean): void; - /** - * @desc Called after the chart as been resized. - * @param {Chart} chart - The chart instance. - * @param {number} size - The new canvas display size (eq. canvas.style width & height). - * @param {object} options - The plugin options. - */ - resize?(chart: Chart, size: number, options: O): void; - /** - * Called after the chart as been destroyed. - * @param {Chart} chart - The chart instance. - * @param {object} options - The plugin options. - */ - destroy?(chart: Chart, options: O): void; + id: string; + + /** + * @desc Called before initializing `chart`. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + */ + beforeInit?(chart: Chart, options: O): void; + /** + * @desc Called after `chart` has been initialized and before the first update. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + */ + afterInit?(chart: Chart, options: O): void; + /** + * @desc Called before updating `chart`. If any plugin returns `false`, the update + * is cancelled (and thus subsequent render(s)) until another `update` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart update. + */ + beforeUpdate?(chart: Chart, args: { mode: UpdateMode }, options: O): boolean | void; + /** + * @desc Called after `chart` has been updated and before rendering. Note that this + * hook will not be called if the chart update has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + */ + afterUpdate?(chart: Chart, args: { mode: UpdateMode }, options: O): void; + /** + * @desc Called during chart reset + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + * @since version 3.0.0 + */ + reset?(chart: Chart, options: O): void; + /** + * @desc Called before updating the `chart` datasets. If any plugin returns `false`, + * the datasets update is cancelled until another `update` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {UpdateMode} args.mode - The update mode. + * @param {object} options - The plugin options. + * @returns {boolean} false to cancel the datasets update. + * @since version 2.1.5 + */ + beforeDatasetsUpdate?(chart: Chart, args: { mode: UpdateMode }, options: O): boolean | void; + /** + * @desc Called after the `chart` datasets have been updated. Note that this hook + * will not be called if the datasets update has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {UpdateMode} args.mode - The update mode. + * @param {object} options - The plugin options. + * @since version 2.1.5 + */ + afterDatasetsUpdate?(chart: Chart, args: { mode: UpdateMode }, options: O): void; + /** + * @desc Called before updating the `chart` dataset at the given `args.index`. If any plugin + * returns `false`, the datasets update is cancelled until another `update` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {number} args.index - The dataset index. + * @param {object} args.meta - The dataset metadata. + * @param {UpdateMode} args.mode - The update mode. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart datasets drawing. + */ + beforeDatasetUpdate?(chart: Chart, args: { index: number; meta: IChartMeta, mode: UpdateMode }, options: O): boolean | void; + /** + * @desc Called after the `chart` datasets at the given `args.index` has been updated. Note + * that this hook will not be called if the datasets update has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {number} args.index - The dataset index. + * @param {object} args.meta - The dataset metadata. + * @param {UpdateMode} args.mode - The update mode. + * @param {object} options - The plugin options. + */ + afterDatasetUpdate?(chart: Chart, args: { index: number; meta: IChartMeta, mode: UpdateMode }, options: O): void; + /** + * @desc Called before laying out `chart`. If any plugin returns `false`, + * the layout update is cancelled until another `update` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart layout. + */ + beforeLayout?(chart: Chart, options: O): boolean | void; + /** + * @desc Called after the `chart` has been laid out. Note that this hook will not + * be called if the layout update has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + */ + afterLayout?(chart: Chart, options: O): void; + /** + * @desc Called before rendering `chart`. If any plugin returns `false`, + * the rendering is cancelled until another `render` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart rendering. + */ + beforeRender?(chart: Chart, options: O): boolean | void; + /** + * @desc Called after the `chart` has been fully rendered (and animation completed). Note + * that this hook will not be called if the rendering has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + */ + afterRender?(chart: Chart, options: O): void; + /** + * @desc Called before drawing `chart` at every animation frame. If any plugin returns `false`, + * the frame drawing is cancelled untilanother `render` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart drawing. + */ + beforeDraw?(chart: Chart, options: O): boolean | void; + /** + * @desc Called after the `chart` has been drawn. Note that this hook will not be called + * if the drawing has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + */ + afterDraw?(chart: Chart, options: O): void; + /** + * @desc Called before drawing the `chart` datasets. If any plugin returns `false`, + * the datasets drawing is cancelled until another `render` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart datasets drawing. + */ + beforeDatasetsDraw?(chart: Chart, options: O): boolean | void; + /** + * @desc Called after the `chart` datasets have been drawn. Note that this hook + * will not be called if the datasets drawing has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + */ + afterDatasetsDraw?(chart: Chart, options: O): void; + /** + * @desc Called before drawing the `chart` dataset at the given `args.index` (datasets + * are drawn in the reverse order). If any plugin returns `false`, the datasets drawing + * is cancelled until another `render` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {number} args.index - The dataset index. + * @param {object} args.meta - The dataset metadata. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart datasets drawing. + */ + beforeDatasetDraw?(chart: Chart, args: { index: number; meta: IChartMeta }, options: O): boolean | void; + /** + * @desc Called after the `chart` datasets at the given `args.index` have been drawn + * (datasets are drawn in the reverse order). Note that this hook will not be called + * if the datasets drawing has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {number} args.index - The dataset index. + * @param {object} args.meta - The dataset metadata. + * @param {object} options - The plugin options. + */ + afterDatasetDraw?(chart: Chart, args: { index: number; meta: IChartMeta }, options: O): void; + /** + * @desc Called before processing the specified `event`. If any plugin returns `false`, + * the event will be discarded. + * @param {Chart} chart - The chart instance. + * @param {IEvent} event - The event object. + * @param {object} options - The plugin options. + * @param {boolean} replay - True if this event is replayed from `Chart.update` + */ + beforeEvent?(chart: Chart, event: IEvent, options: O, replay: boolean): void; + /** + * @desc Called after the `event` has been consumed. Note that this hook + * will not be called if the `event` has been previously discarded. + * @param {Chart} chart - The chart instance. + * @param {IEvent} event - The event object. + * @param {object} options - The plugin options. + * @param {boolean} replay - True if this event is replayed from `Chart.update` + */ + afterEvent?(chart: Chart, event: IEvent, options: O, replay: boolean): void; + /** + * @desc Called after the chart as been resized. + * @param {Chart} chart - The chart instance. + * @param {number} size - The new canvas display size (eq. canvas.style width & height). + * @param {object} options - The plugin options. + */ + resize?(chart: Chart, size: number, options: O): void; + /** + * Called after the chart as been destroyed. + * @param {Chart} chart - The chart instance. + * @param {object} options - The plugin options. + */ + destroy?(chart: Chart, options: O): void; } export declare type IChartComponentLike = IChartComponent | IChartComponent[] | { [key: string]: IChartComponent }; @@ -857,267 +863,267 @@ export declare type IChartComponentLike = IChartComponent | IChartComponent[] | * Note: class is exported for typedoc */ export interface Registry { - readonly controllers: TypedRegistry<DatasetController>; - readonly elements: TypedRegistry<Element>; - readonly plugins: TypedRegistry<IPlugin>; - readonly scales: TypedRegistry<Scale>; - - add(...args: IChartComponentLike[]): void; - remove(...args: IChartComponentLike[]): void; - - addControllers(...args: IChartComponentLike[]): void; - addElements(...args: IChartComponentLike[]): void; - addPlugins(...args: IChartComponentLike[]): void; - addScales(...args: IChartComponentLike[]): void; - - getController(id: string): DatasetController | undefined; - getElement(id: string): Element | undefined; - getPlugin(id: string): IPlugin | undefined; - getScale(id: string): Scale | undefined; + readonly controllers: TypedRegistry<DatasetController>; + readonly elements: TypedRegistry<Element>; + readonly plugins: TypedRegistry<IPlugin>; + readonly scales: TypedRegistry<Scale>; + + add(...args: IChartComponentLike[]): void; + remove(...args: IChartComponentLike[]): void; + + addControllers(...args: IChartComponentLike[]): void; + addElements(...args: IChartComponentLike[]): void; + addPlugins(...args: IChartComponentLike[]): void; + addScales(...args: IChartComponentLike[]): void; + + getController(id: string): DatasetController | undefined; + getElement(id: string): Element | undefined; + getPlugin(id: string): IPlugin | undefined; + getScale(id: string): Scale | undefined; } export const registry: Registry; export interface ITick { - value: number; - label?: string; - major?: boolean; + value: number; + label?: string; + major?: boolean; } export interface ICoreScaleOptions { - /** - * Controls the axis global visibility (visible when true, hidden when false). When display: 'auto', the axis is visible only if at least one associated dataset is visible. - * @default true - */ - display: boolean | 'auto'; - /** - * Reverse the scale. - * @default false - */ - reverse: boolean; - /** - * The weight used to sort the axis. Higher weights are further away from the chart area. - * @default true - */ - weight: number; - /** - * Callback called before the update process starts. - */ - beforeUpdate(axis: Scale): void; - /** - * Callback that runs before dimensions are set. - */ - beforeSetDimensions(axis: Scale): void; - /** - * Callback that runs after dimensions are set. - */ - afterSetDimensions(axis: Scale): void; - /** - * Callback that runs before data limits are determined. - */ - beforeDataLimits(axis: Scale): void; - /** - * Callback that runs after data limits are determined. - */ - afterDataLimits(axis: Scale): void; - /** - * Callback that runs before ticks are created. - */ - beforeBuildTicks(axis: Scale): void; - /** - * Callback that runs after ticks are created. Useful for filtering ticks. - */ - afterBuildTicks(axis: Scale): void; - /** - * Callback that runs before ticks are converted into strings. - */ - beforeTickToLabelConversion(axis: Scale): void; - /** - * Callback that runs after ticks are converted into strings. - */ - afterTickToLabelConversion(axis: Scale): void; - /** - * Callback that runs before tick rotation is determined. - */ - beforeCalculateTickRotation(axis: Scale): void; - /** - * Callback that runs after tick rotation is determined. - */ - afterCalculateTickRotation(axis: Scale): void; - /** - * Callback that runs before the scale fits to the canvas. - */ - beforeFit(axis: Scale): void; - /** - * Callback that runs after the scale fits to the canvas. - */ - afterFit(axis: Scale): void; - /** - * Callback that runs at the end of the update process. - */ - afterUpdate(axis: Scale): void; + /** + * Controls the axis global visibility (visible when true, hidden when false). When display: 'auto', the axis is visible only if at least one associated dataset is visible. + * @default true + */ + display: boolean | 'auto'; + /** + * Reverse the scale. + * @default false + */ + reverse: boolean; + /** + * The weight used to sort the axis. Higher weights are further away from the chart area. + * @default true + */ + weight: number; + /** + * Callback called before the update process starts. + */ + beforeUpdate(axis: Scale): void; + /** + * Callback that runs before dimensions are set. + */ + beforeSetDimensions(axis: Scale): void; + /** + * Callback that runs after dimensions are set. + */ + afterSetDimensions(axis: Scale): void; + /** + * Callback that runs before data limits are determined. + */ + beforeDataLimits(axis: Scale): void; + /** + * Callback that runs after data limits are determined. + */ + afterDataLimits(axis: Scale): void; + /** + * Callback that runs before ticks are created. + */ + beforeBuildTicks(axis: Scale): void; + /** + * Callback that runs after ticks are created. Useful for filtering ticks. + */ + afterBuildTicks(axis: Scale): void; + /** + * Callback that runs before ticks are converted into strings. + */ + beforeTickToLabelConversion(axis: Scale): void; + /** + * Callback that runs after ticks are converted into strings. + */ + afterTickToLabelConversion(axis: Scale): void; + /** + * Callback that runs before tick rotation is determined. + */ + beforeCalculateTickRotation(axis: Scale): void; + /** + * Callback that runs after tick rotation is determined. + */ + afterCalculateTickRotation(axis: Scale): void; + /** + * Callback that runs before the scale fits to the canvas. + */ + beforeFit(axis: Scale): void; + /** + * Callback that runs after the scale fits to the canvas. + */ + afterFit(axis: Scale): void; + /** + * Callback that runs at the end of the update process. + */ + afterUpdate(axis: Scale): void; } export interface Scale<O extends ICoreScaleOptions = ICoreScaleOptions> extends Element<{}, O>, IChartArea { - readonly id: string; - readonly type: string; - readonly ctx: CanvasRenderingContext2D; - readonly chart: Chart; - - width: number; - height: number; - - maxWidth: number; - maxHeight: number; - - paddingTop: number; - paddingBottom: number; - paddingLeft: number; - paddingRight: number; - - axis: string; - labelRotation: number; - min: number; - max: number; - ticks: ITick[]; - getMatchingVisibleMetas(type?: string): IChartMeta[]; - - draw(chartArea: IChartArea): void; - drawTitle(chartArea: IChartArea): void; - drawLabels(chartArea: IChartArea): void; - drawGrid(chartArea: IChartArea): void; - - /** - * @param {number} pixel - * @return {number} - */ - getDecimalForPixel(pixel: number): number; - /** - * Utility for getting the pixel location of a percentage of scale - * The coordinate (0, 0) is at the upper-left corner of the canvas - * @param {number} decimal - * @return {number} - */ - getPixelForDecimal(decimal: number): number; - /** - * Returns the location of the tick at the given index - * The coordinate (0, 0) is at the upper-left corner of the canvas - * @param {number} index - * @return {number} - */ - getPixelForTick(index: number): number; - /** - * Used to get the label to display in the tooltip for the given value - * @param {*} value - * @return {string} - */ - getLabelForValue(value: number): string; - /** - * Returns the location of the given data point. Value can either be an index or a numerical value - * The coordinate (0, 0) is at the upper-left corner of the canvas - * @param {*} value - * @param {number} [index] - * @return {number} - */ - getPixelForValue(value: number, index: number): number; - - /** - * Used to get the data value from a given pixel. This is the inverse of getPixelForValue - * The coordinate (0, 0) is at the upper-left corner of the canvas - * @param {number} pixel - * @return {*} - */ - getValueForPixel(pixel: number): number | undefined; - - getBaseValue(): number; - /** - * Returns the pixel for the minimum chart value - * The coordinate (0, 0) is at the upper-left corner of the canvas - * @return {number} - */ - getBasePixel(): number; - - init(options: O): void; - parse(raw: any, index: number): any; - getUserBounds(): { min: number; max: number; minDefined: boolean; maxDefined: boolean }; - getMinMax(canStack: boolean): { min: number; max: number }; - invalidateCaches(): void; - getPadding(): IChartArea; - getTicks(): ITick[]; - getLabels(): string[]; - beforeUpdate(): void; - update(maxWidth: number, maxHeight: number, margins: any): void; - configure(): void; - afterUpdate(): void; - beforeSetDimensions(): void; - setDimensions(): void; - afterSetDimensions(): void; - beforeDataLimits(): void; - determineDataLimits(): void; - afterDataLimits(): void; - beforeBuildTicks(): void; - buildTicks(): ITick[]; - afterBuildTicks(): void; - beforeTickToLabelConversion(): void; - generateTickLabels(ticks: ITick[]): void; - afterTickToLabelConversion(): void; - beforeCalculateLabelRotation(): void; - calculateLabelRotation(): void; - afterCalculateLabelRotation(): void; - beforeFit(): void; - fit(): void; - afterFit(): void; - - isHorizontal(): boolean; - isFullWidth(): boolean; + readonly id: string; + readonly type: string; + readonly ctx: CanvasRenderingContext2D; + readonly chart: Chart; + + width: number; + height: number; + + maxWidth: number; + maxHeight: number; + + paddingTop: number; + paddingBottom: number; + paddingLeft: number; + paddingRight: number; + + axis: string; + labelRotation: number; + min: number; + max: number; + ticks: ITick[]; + getMatchingVisibleMetas(type?: string): IChartMeta[]; + + draw(chartArea: IChartArea): void; + drawTitle(chartArea: IChartArea): void; + drawLabels(chartArea: IChartArea): void; + drawGrid(chartArea: IChartArea): void; + + /** + * @param {number} pixel + * @return {number} + */ + getDecimalForPixel(pixel: number): number; + /** + * Utility for getting the pixel location of a percentage of scale + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param {number} decimal + * @return {number} + */ + getPixelForDecimal(decimal: number): number; + /** + * Returns the location of the tick at the given index + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param {number} index + * @return {number} + */ + getPixelForTick(index: number): number; + /** + * Used to get the label to display in the tooltip for the given value + * @param {*} value + * @return {string} + */ + getLabelForValue(value: number): string; + /** + * Returns the location of the given data point. Value can either be an index or a numerical value + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param {*} value + * @param {number} [index] + * @return {number} + */ + getPixelForValue(value: number, index: number): number; + + /** + * Used to get the data value from a given pixel. This is the inverse of getPixelForValue + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param {number} pixel + * @return {*} + */ + getValueForPixel(pixel: number): number | undefined; + + getBaseValue(): number; + /** + * Returns the pixel for the minimum chart value + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @return {number} + */ + getBasePixel(): number; + + init(options: O): void; + parse(raw: any, index: number): any; + getUserBounds(): { min: number; max: number; minDefined: boolean; maxDefined: boolean }; + getMinMax(canStack: boolean): { min: number; max: number }; + invalidateCaches(): void; + getPadding(): IChartArea; + getTicks(): ITick[]; + getLabels(): string[]; + beforeUpdate(): void; + update(maxWidth: number, maxHeight: number, margins: any): void; + configure(): void; + afterUpdate(): void; + beforeSetDimensions(): void; + setDimensions(): void; + afterSetDimensions(): void; + beforeDataLimits(): void; + determineDataLimits(): void; + afterDataLimits(): void; + beforeBuildTicks(): void; + buildTicks(): ITick[]; + afterBuildTicks(): void; + beforeTickToLabelConversion(): void; + generateTickLabels(ticks: ITick[]): void; + afterTickToLabelConversion(): void; + beforeCalculateLabelRotation(): void; + calculateLabelRotation(): void; + afterCalculateLabelRotation(): void; + beforeFit(): void; + fit(): void; + afterFit(): void; + + isHorizontal(): boolean; + isFullWidth(): boolean; } export const Scale: { - prototype: Scale; - new <O extends ICoreScaleOptions = ICoreScaleOptions>(cfg: any): Scale<O>; + prototype: Scale; + new <O extends ICoreScaleOptions = ICoreScaleOptions>(cfg: any): Scale<O>; }; export interface IScriptAbleScaleContext { - chart: Chart; - scale: Scale; - index: number; - tick: ITick; + chart: Chart; + scale: Scale; + index: number; + tick: ITick; } export type ScriptAbleScale<T> = T | ((ctx: IScriptAbleScaleContext) => T); export const Ticks: { - formatters: { - /** - * Formatter for value labels - * @param value the value to display - * @return {string|string[]} the label to display - */ - values(value: any): string | string[]; - /** - * Formatter for numeric ticks - * @param tickValue the value to be formatted - * @param index the position of the tickValue parameter in the ticks array - * @param ticks the list of ticks being converted - * @return string representation of the tickValue parameter - */ - numeric(tickValue: number, index: number, ticks: { value: number }[]): string; - /** - * Formatter for logarithmic ticks - * @param tickValue the value to be formatted - * @param index the position of the tickValue parameter in the ticks array - * @param ticks the list of ticks being converted - * @return string representation of the tickValue parameter - */ - logarithmic(tickValue: number, index: number, ticks: { value: number }[]): string; - }; + formatters: { + /** + * Formatter for value labels + * @param value the value to display + * @return {string|string[]} the label to display + */ + values(value: any): string | string[]; + /** + * Formatter for numeric ticks + * @param tickValue the value to be formatted + * @param index the position of the tickValue parameter in the ticks array + * @param ticks the list of ticks being converted + * @return string representation of the tickValue parameter + */ + numeric(tickValue: number, index: number, ticks: { value: number }[]): string; + /** + * Formatter for logarithmic ticks + * @param tickValue the value to be formatted + * @param index the position of the tickValue parameter in the ticks array + * @param ticks the list of ticks being converted + * @return string representation of the tickValue parameter + */ + logarithmic(tickValue: number, index: number, ticks: { value: number }[]): string; + }; }; export interface TypedRegistry<T> { - /** - * @param {IChartComponent} item - * @returns {string} The scope where items defaults were registered to. - */ - register(item: IChartComponent): string; - get(id: string): T | undefined; - unregister(item: IChartComponent): void; + /** + * @param {IChartComponent} item + * @returns {string} The scope where items defaults were registered to. + */ + register(item: IChartComponent): string; + get(id: string): T | undefined; + unregister(item: IChartComponent): void; }
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
docs/docs/configuration/tooltip.md
@@ -10,8 +10,8 @@ The tooltip configuration is passed into the `options.tooltips` namespace. The g | ---- | ---- | ------- | ----------- | `enabled` | `boolean` | `true` | Are on-canvas tooltips enabled? | `custom` | `function` | `null` | See [custom tooltip](#external-custom-tooltips) section. -| `mode` | `string` | `'nearest'` | Sets which elements appear in the tooltip. [more...](../general/interactions/modes.md#interaction-modes). -| `intersect` | `boolean` | `true` | If true, the tooltip mode applies only when the mouse position intersects with an element. If false, the mode will be applied at all times. +| `mode` | `string` | | Sets which elements appear in the tooltip. [more...](../general/interactions/modes.md#interaction-modes). +| `intersect` | `boolean` | | If true, the tooltip mode applies only when the mouse position intersects with an element. If false, the mode will be applied at all times. | `position` | `string` | `'average'` | The mode for positioning the tooltip. [more...](#position-modes) | `callbacks` | `object` | | See the [callbacks section](#tooltip-callbacks). | `itemSort` | `function` | | Sort tooltip items. [more...](#sort-callback)
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
docs/docs/general/interactions/index.md
@@ -2,7 +2,7 @@ title: Interactions --- -The hover configuration is passed into the `options.hover` namespace. The global hover configuration is at `Chart.defaults.hover`. To configure which events trigger chart interactions, see [events](./events.md#events). +The interaction configuration is passed into the `options.interaction` namespace. The global interaction configuration is at `Chart.defaults.interaction`. To configure which events trigger chart interactions, see [events](./events.md#events). | Name | Type | Default | Description | ---- | ---- | ------- | -----------
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
docs/docs/general/interactions/modes.md
@@ -4,6 +4,8 @@ title: Interaction Modes When configuring interaction with the graph via hover or tooltips, a number of different modes are available. +`options.hover` and `options.tooltips` extend from `options.interaction`. So if `mode`, `intersect` or any other common settings are configured only in `options.interaction`, both hover and tooltips obey that. + The modes are detailed below and how they behave in conjunction with the `intersect` setting. ## point @@ -15,7 +17,7 @@ var chart = new Chart(ctx, { type: 'line', data: data, options: { - tooltips: { + interaction: { mode: 'point' } } @@ -31,7 +33,7 @@ var chart = new Chart(ctx, { type: 'line', data: data, options: { - tooltips: { + interaction: { mode: 'nearest' } } @@ -47,7 +49,7 @@ var chart = new Chart(ctx, { type: 'line', data: data, options: { - tooltips: { + interaction: { mode: 'index' } } @@ -61,7 +63,7 @@ var chart = new Chart(ctx, { type: 'bar', data: data, options: { - tooltips: { + interaction: { mode: 'index', axis: 'y' } @@ -77,7 +79,7 @@ var chart = new Chart(ctx, { type: 'line', data: data, options: { - tooltips: { + interaction: { mode: 'dataset' } } @@ -92,7 +94,7 @@ var chart = new Chart(ctx, { type: 'line', data: data, options: { - tooltips: { + interaction: { mode: 'x' } } @@ -107,7 +109,7 @@ var chart = new Chart(ctx, { type: 'line', data: data, options: { - tooltips: { + interaction: { mode: 'y' } }
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
docs/docs/getting-started/v3-migration.md
@@ -202,6 +202,7 @@ Animation system was completely rewritten in Chart.js v3. Each property can now #### Interactions +* To allow DRY configuration, a root options scope for common interaction options was added. `options.hover` and `options.tooltips` now both extend from `options.interaction`. Defaults are defined at `defaults.interaction` level, so by default hover and tooltip interactions share the same mode etc. * `interactions` are now limited to the chart area * `{mode: 'label'}` was replaced with `{mode: 'index'}` * `{mode: 'single'}` was replaced with `{mode: 'nearest', intersect: true}`
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
samples/charts/line/multi-axis.html
@@ -62,7 +62,9 @@ data: lineChartData, options: { responsive: true, - hoverMode: 'index', + interaction: { + mode: 'index' + }, stacked: false, title: { display: true,
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
samples/charts/scatter/multi-axis.html
@@ -88,8 +88,10 @@ data: scatterChartData, options: { responsive: true, - hoverMode: 'nearest', - intersect: true, + interaction: { + intersect: true, + mode: 'nearest' + }, title: { display: true, text: 'Chart.js Scatter Chart - Multi Axis'
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
src/controllers/controller.bar.js
@@ -528,10 +528,12 @@ BarController.defaults = { 'maxBarThickness', 'minBarLength', ], - hover: { + interaction: { mode: 'index' }, + hover: {}, + datasets: { categoryPercentage: 0.8, barPercentage: 0.9,
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
src/controllers/controller.line.js
@@ -164,10 +164,12 @@ LineController.defaults = { showLines: true, spanGaps: false, - hover: { + interaction: { mode: 'index' }, + hover: {}, + scales: { _index_: { type: 'category',
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
src/core/core.controller.js
@@ -116,10 +116,25 @@ function initConfig(config) { defaults[config.type], config.options || {}); + options.hover = merge(Object.create(null), [ + defaults.interaction, + defaults.hover, + options.interaction, + options.hover + ]); + options.scales = scaleConfig; - options.title = (options.title !== false) && merge(Object.create(null), [defaults.plugins.title, options.title]); - options.tooltips = (options.tooltips !== false) && merge(Object.create(null), [defaults.plugins.tooltip, options.tooltips]); + options.title = (options.title !== false) && merge(Object.create(null), [ + defaults.plugins.title, + options.title + ]); + options.tooltips = (options.tooltips !== false) && merge(Object.create(null), [ + defaults.interaction, + defaults.plugins.tooltip, + options.interaction, + options.tooltips + ]); return config; }
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
src/core/core.defaults.js
@@ -42,12 +42,15 @@ export class Defaults { lineWidth: 0, strokeStyle: undefined }; - this.hover = { - onHover: null, + this.interaction = { mode: 'nearest', intersect: true }; + this.hover = { + onHover: null + }; this.maintainAspectRatio = true; + this.onHover = null; this.onClick = null; this.responsive = true; this.showLines = true;
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
src/plugins/plugin.tooltip.js
@@ -1066,9 +1066,7 @@ export default { defaults: { enabled: true, custom: null, - mode: 'nearest', position: 'average', - intersect: true, backgroundColor: 'rgba(0,0,0,0.8)', titleFont: { style: 'bold',
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
test/specs/core.controller.tests.js
@@ -89,13 +89,38 @@ describe('Chart', function() { expect(chart.data.datasets[0].data).toEqual([10, 11, 12]); }); - it('should initialize config with default options', function() { + it('should initialize config with default interaction options', function() { var callback = function() {}; var defaults = Chart.defaults; + var defaultMode = defaults.line.interaction.mode; defaults.hover.onHover = callback; defaults.line.spanGaps = true; - defaults.line.hover.mode = 'x-axis'; + defaults.line.interaction.mode = 'test'; + + var chart = acquireChart({ + type: 'line' + }); + + var options = chart.options; + expect(options.font.size).toBe(defaults.font.size); + expect(options.showLines).toBe(defaults.line.showLines); + expect(options.spanGaps).toBe(true); + expect(options.hover.onHover).toBe(callback); + expect(options.hover.mode).toBe('test'); + + defaults.hover.onHover = null; + defaults.line.spanGaps = false; + defaults.line.interaction.mode = defaultMode; + }); + + it('should initialize config with default hover options', function() { + var callback = function() {}; + var defaults = Chart.defaults; + + defaults.hover.onHover = callback; + defaults.line.spanGaps = true; + defaults.line.hover.mode = 'test'; var chart = acquireChart({ type: 'line' @@ -106,11 +131,11 @@ describe('Chart', function() { expect(options.showLines).toBe(defaults.line.showLines); expect(options.spanGaps).toBe(true); expect(options.hover.onHover).toBe(callback); - expect(options.hover.mode).toBe('x-axis'); + expect(options.hover.mode).toBe('test'); defaults.hover.onHover = null; defaults.line.spanGaps = false; - defaults.line.hover.mode = 'index'; + delete defaults.line.hover.mode; }); it('should override default options', function() { @@ -141,7 +166,7 @@ describe('Chart', function() { expect(options.title.position).toBe('bottom'); defaults.hover.onHover = null; - defaults.line.hover.mode = 'index'; + delete defaults.line.hover.mode; defaults.line.spanGaps = false; });
true
Other
chartjs
Chart.js
f5c4f97504b6ae96f8f0592bcc15cebb2dfba8a6.json
Add interaction options (#7922) * Add interaction options * Add migration note
types/core/index.d.ts
@@ -417,13 +417,18 @@ export interface Defaults { readonly color: string; readonly events: ('mousemove' | 'mouseout' | 'click' | 'touchstart' | 'touchmove')[]; readonly font: IFontSpec; - readonly hover: { - onHover?: () => void; + readonly interaction: { mode: InteractionMode | string; intersect: boolean; }; + readonly hover: { + onHover?: () => void; + mode?: InteractionMode | string; + intersect?: boolean; + }; readonly maintainAspectRatio: boolean; readonly onClick?: () => void; + readonly onHover?: () => void; readonly responsive: boolean; readonly plugins: { [key: string]: any };
true
Other
chartjs
Chart.js
41eb16a6506ce1caa699ee5ca6e1d85f01c27b63.json
Add example of event to data values (#7925)
docs/docs/general/interactions/events.md
@@ -22,3 +22,23 @@ var chart = new Chart(ctx, { } }); ``` + +## Converting Events to Data Values + +A common occurrence is taking an event, such as a click, and finding the data coordinates on the chart where the event occurred. Chart.js provides helpers that make this a straightforward process. + +```javascript +const chart = new Chart(ctx, { + type: 'line', + data: data, + options: { + onClick: (e) => { + const canvasPosition = Chart.helpers.getRelativePosition(e); + + // Substitute the appropriate scale IDs + const dataX = chart.scales.x.getValueForPixel(canvasPosition.x); + const dataY = chart.scales.y.getValueForPixel(canvasPosition.y); + } + } +}); +``` \ No newline at end of file
false
Other
chartjs
Chart.js
c688c2f5430de350f27fda0081c6f1d83c0055b8.json
Fix broken urls in docs (#7912)
docs/docs/axes/radial/linear.md
@@ -133,7 +133,7 @@ The following options are used to configure the point labels that are shown on t | ---- | ---- | ------- | ------- | ----------- | `display` | `boolean` | | `true` | if true, point labels are shown. | `callback` | `function` | | | Callback function to transform data labels to point labels. The default implementation simply returns the current string. -| `font` | `Font` | Yes | `defaults.font` | See [Fonts](../general/fonts.md) +| `font` | `Font` | Yes | `defaults.font` | See [Fonts](./general/fonts.md) The scriptable context is the same as for the [Angle Line Options](#angle-line-options).
true
Other
chartjs
Chart.js
c688c2f5430de350f27fda0081c6f1d83c0055b8.json
Fix broken urls in docs (#7912)
docs/docs/developers/updates.md
@@ -95,7 +95,7 @@ function updateScale(chart) { } ``` -Code sample for updating options can be found in [toggle-scale-type.html](../../samples/scales/toggle-scale-type.html). +Code sample for updating options can be found in [toggle-scale-type.html](./../../samples/latest/scales/toggle-scale-type.html). ## Preventing Animations
true
Other
chartjs
Chart.js
c688c2f5430de350f27fda0081c6f1d83c0055b8.json
Fix broken urls in docs (#7912)
docs/docs/general/performance.md
@@ -26,11 +26,11 @@ Line charts are able to do [automatic data decimation during draw](#automatic-da ### Rotation -[Specify a rotation value](../axes/cartesian/index.md#tick-configuration) by setting `minRotation` and `maxRotation` to the same value, which avoids the chart from having to automatically determine a value to use. +[Specify a rotation value](./axes/cartesian/index.mdx#tick-configuration) by setting `minRotation` and `maxRotation` to the same value, which avoids the chart from having to automatically determine a value to use. ### Sampling -Set the [`ticks.sampleSize`](../axes/cartesian/index.md#tick-configuration) option. This will determine how large your labels are by looking at only a subset of them in order to render axes more quickly. This works best if there is not a large variance in the size of your labels. +Set the [`ticks.sampleSize`](./axes/cartesian/index.mdx#tick-configuration) option. This will determine how large your labels are by looking at only a subset of them in order to render axes more quickly. This works best if there is not a large variance in the size of your labels. ## Disable Animations
true
Other
chartjs
Chart.js
c688c2f5430de350f27fda0081c6f1d83c0055b8.json
Fix broken urls in docs (#7912)
docs/docs/getting-started/v3-migration.md
@@ -51,7 +51,7 @@ const chart = new Chart(ctx, { ### Chart types -* `horizontalBar` chart type was removed. Horizontal bar charts can be configured using the new [`indexAxis`](../charts/bar.md#general) option +* `horizontalBar` chart type was removed. Horizontal bar charts can be configured using the new [`indexAxis`](./charts/bar.mdx#general) option ### Options
true
Other
chartjs
Chart.js
de963091d9505ca8c4b8009a97780a2db4dce670.json
Remove area inclusion check when rendering points (#7910)
src/elements/element.point.js
@@ -1,5 +1,5 @@ import Element from '../core/core.element'; -import {_isPointInArea, drawPoint} from '../helpers/helpers.canvas'; +import {drawPoint} from '../helpers/helpers.canvas'; export default class Point extends Element { @@ -46,21 +46,18 @@ export default class Point extends Element { return (radius + borderWidth) * 2; } - draw(ctx, chartArea) { + draw(ctx) { const me = this; const options = me.options; if (me.skip || options.radius <= 0) { return; } - // Clipping for Points. - if (chartArea === undefined || _isPointInArea(me, chartArea)) { - ctx.strokeStyle = options.borderColor; - ctx.lineWidth = options.borderWidth; - ctx.fillStyle = options.backgroundColor; - drawPoint(ctx, options, me.x, me.y); - } + ctx.strokeStyle = options.borderColor; + ctx.lineWidth = options.borderWidth; + ctx.fillStyle = options.backgroundColor; + drawPoint(ctx, options, me.x, me.y); } getRange() {
false
Other
chartjs
Chart.js
7ce9710f336c2ad2359466dc9357979c4d562446.json
fix some typos (#7914)
docs/docs/configuration/legend.md
@@ -57,7 +57,7 @@ The legend label configuration is nested below the legend configuration using th | `generateLabels` | `function` | | Generates legend items for each thing in the legend. Default implementation returns the text + styling for the color box. See [Legend Item](#legend-item-interface) for details. | `filter` | `function` | `null` | Filters legend items out of the legend. Receives 2 parameters, a [Legend Item](#legend-item-interface) and the chart data. | `sort` | `function` | `null` | Sorts legend items. Receives 3 parameters, two [Legend Items](#legend-item-interface) and the chart data. -| `usePointStyle` | `boolean` | `false` | Label style will match corresponding point style (size is based on the mimimum value between boxWidth and font.size). +| `usePointStyle` | `boolean` | `false` | Label style will match corresponding point style (size is based on the minimum value between boxWidth and font.size). ## Legend Title Configuration
true
Other
chartjs
Chart.js
7ce9710f336c2ad2359466dc9357979c4d562446.json
fix some typos (#7914)
docs/docs/general/performance.md
@@ -75,7 +75,7 @@ new Chart(ctx, { ## Parallel rendering with web workers (Chrome only) -Chome (in version 69) added the ability to [transfer rendering control of a canvas](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/transferControlToOffscreen) to a web worker. Web workers can use the [OffscreenCanvas API](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) to render from a web worker onto canvases in the DOM. Chart.js is a canvas-based library and supports rendering in a web worker - just pass an OffscreenCanvas into the Chart constructor instead of a Canvas element. Note that as of today, this API is only supported in Chrome. +Chrome (in version 69) added the ability to [transfer rendering control of a canvas](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/transferControlToOffscreen) to a web worker. Web workers can use the [OffscreenCanvas API](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) to render from a web worker onto canvases in the DOM. Chart.js is a canvas-based library and supports rendering in a web worker - just pass an OffscreenCanvas into the Chart constructor instead of a Canvas element. Note that as of today, this API is only supported in Chrome. By moving all Chart.js calculations onto a separate thread, the main thread can be freed up for other uses. Some tips and tricks when using Chart.js in a web worker: * Transferring data between threads can be expensive, so ensure that your config and data objects are as small as possible. Try generating them on the worker side if you can (workers can make HTTP requests!) or passing them to your worker as ArrayBuffers, which can be transferred quickly from one thread to another. @@ -222,7 +222,7 @@ new Chart(ctx, { }); ``` -## When transpiling with Babel, cosider using `loose` mode +## When transpiling with Babel, consider using `loose` mode Babel 7.9 changed the way classes are constructed. It is slow, unless used with `loose` mode. [More information](https://github.com/babel/babel/issues/11356)
true
Other
chartjs
Chart.js
7ce9710f336c2ad2359466dc9357979c4d562446.json
fix some typos (#7914)
docs/docs/general/responsive.md
@@ -39,7 +39,7 @@ chart.canvas.parentNode.style.width = '128px'; Note that in order for the above code to correctly resize the chart height, the [`maintainAspectRatio`](#configuration-options) option must also be set to `false`. -## Printing Resizeable Charts +## Printing Resizable Charts CSS media queries allow changing styles when printing a page. The CSS applied from these media queries may cause charts to need to resize. However, the resize won't happen automatically. To support resizing charts when printing, one needs to hook the [onbeforeprint](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeprint) event and manually trigger resizing of each chart.
true
Other
chartjs
Chart.js
7ce9710f336c2ad2359466dc9357979c4d562446.json
fix some typos (#7914)
src/core/core.animations.js
@@ -127,7 +127,7 @@ export default class Animations { const animations = this._createAnimations(options, newOptions); if (newOptions.$shared && !options.$shared) { // Going from distinct options to shared options: - // After all animations are done, assing the shared options object to the element + // After all animations are done, assign the shared options object to the element // So any new updates to the shared options are observed awaitAll(target.options.$animations, newOptions).then(() => { target.options = newOptions;
true
Other
chartjs
Chart.js
7ce9710f336c2ad2359466dc9357979c4d562446.json
fix some typos (#7914)
src/core/core.plugins.js
@@ -214,7 +214,7 @@ function createDescriptors(plugins, options) { /** * @method IPlugin#beforeDraw * @desc Called before drawing `chart` at every animation frame. If any plugin returns `false`, - * the frame drawing is cancelled untilanother `render` is triggered. + * the frame drawing is cancelled until another `render` is triggered. * @param {Chart} chart - The chart instance. * @param {object} options - The plugin options. * @returns {boolean} `false` to cancel the chart drawing.
true
Other
chartjs
Chart.js
7ce9710f336c2ad2359466dc9357979c4d562446.json
fix some typos (#7914)
src/scales/scale.category.js
@@ -83,7 +83,7 @@ export default class CategoryScale extends Scale { return me.getPixelForDecimal((value - me._startValue) / me._valueRange); } - // Must override base implementation becuase it calls getPixelForValue + // Must override base implementation because it calls getPixelForValue // and category scale can have duplicate values getPixelForTick(index) { const me = this;
true
Other
chartjs
Chart.js
8e640f4c710fde95d4542abc75cb779d6bd1c737.json
Fix version numbers in Developers section of docs (#7909)
docs/docs/developers/index.md
@@ -38,9 +38,9 @@ Thanks to [BrowserStack](https://browserstack.com) for allowing our team to test ## Previous versions -To migrate from version 3 to version 2, please see [the v3 migration guide](../getting-started/v3-migration). +To migrate from version 2 to version 3, please see [the v3 migration guide](../getting-started/v3-migration). -Version 2 has a completely different API than earlier versions. +Version 3 has a largely different API than earlier versions. Most earlier version options have current equivalents or are the same.
false
Other
chartjs
Chart.js
11dc2aad0e05b80bdf9134a84bb6dd908b1f11ea.json
Fix broken url in docs
docs/docs/charts/scatter.md
@@ -35,7 +35,7 @@ var scatterChart = new Chart(ctx, { ## Dataset Properties -The scatter chart supports all of the same properties as the [line chart](./charts/line#dataset-properties). +The scatter chart supports all of the same properties as the [line chart](./charts/line.mdx#dataset-properties). ## Data Structure
false
Other
chartjs
Chart.js
2e986852b577f4f6211d86b7a3aa291c69497412.json
Fix broken url in docs
docs/docs/charts/area.md
@@ -2,7 +2,7 @@ title: Area Chart --- -Both [line](line.md) and [radar](radar.md) charts support a `fill` option on the dataset object which can be used to create space between two datasets or a dataset and a boundary, i.e. the scale `origin`, `start,` or `end` (see [filling modes](#filling-modes)). +Both [line](./line.mdx) and [radar](./radar.mdx) charts support a `fill` option on the dataset object which can be used to create space between two datasets or a dataset and a boundary, i.e. the scale `origin`, `start,` or `end` (see [filling modes](#filling-modes)). > **Note:** this feature is implemented by the [`filler` plugin](https://github.com/chartjs/Chart.js/blob/master/src/plugins/plugin.filler.js).
true
Other
chartjs
Chart.js
2e986852b577f4f6211d86b7a3aa291c69497412.json
Fix broken url in docs
docs/docs/charts/scatter.md
@@ -35,7 +35,7 @@ var scatterChart = new Chart(ctx, { ## Dataset Properties -The scatter chart supports all of the same properties as the [line chart](./line.md#dataset-properties). +The scatter chart supports all of the same properties as the [line chart](./charts/line#dataset-properties). ## Data Structure
true
Other
chartjs
Chart.js
2e986852b577f4f6211d86b7a3aa291c69497412.json
Fix broken url in docs
docs/docs/configuration/elements.md
@@ -64,7 +64,7 @@ Global line options: `Chart.defaults.elements.line`. | `borderDashOffset` | `number` | `0.0` | Line dash offset. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset). | `borderJoinStyle` | `string` | `'miter'` | Line join style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin). | `capBezierPoints` | `boolean` | `true` | `true` to keep Bézier control inside the chart, `false` for no restriction. -| `cubicInterpolationMode` | `string` | `'default'` | Interpolation mode to apply. [See more...](../charts/line.md#cubicinterpolationmode) +| `cubicInterpolationMode` | `string` | `'default'` | Interpolation mode to apply. [See more...](./charts/line.mdx/#cubicinterpolationmode) | `fill` | `boolean`\|`string` | `true` | How to fill the area under the line. See [area charts](../charts/area.md#filling-modes). | `stepped` | `boolean` | `false` | `true` to show the line as a stepped line (`tension` will be ignored).
true
Other
chartjs
Chart.js
2e986852b577f4f6211d86b7a3aa291c69497412.json
Fix broken url in docs
docs/docs/index.md
@@ -57,7 +57,7 @@ var myChart = new Chart(ctx, { ## Contributing -Before submitting an issue or a pull request to the project, please take a moment to look over the [contributing guidelines](./developers/contributing.md) first. +Before submitting an issue or a pull request to the project, please take a moment to look over the [contributing guidelines](./docs/developers/contributing.md) first. For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](https://stackoverflow.com/questions/tagged/chartjs).
true
Other
chartjs
Chart.js
b6c22d269a16097bc8c55d7cc01d37b7369391d4.json
Remove circular dependencies from helpers (#7898)
src/helpers/helpers.canvas.js
@@ -1,7 +1,5 @@ -import { - isArray, isNullOrUndef, PI, TAU, HALF_PI, QUARTER_PI, - TWO_THIRDS_PI, RAD_PER_DEG -} from './index'; +import {isArray, isNullOrUndef} from './helpers.core'; +import {PI, TAU, HALF_PI, QUARTER_PI, TWO_THIRDS_PI, RAD_PER_DEG} from './helpers.math'; /** * @typedef { import("../core/core.controller").default } Chart
true
Other
chartjs
Chart.js
b6c22d269a16097bc8c55d7cc01d37b7369391d4.json
Remove circular dependencies from helpers (#7898)
src/helpers/helpers.dom.js
@@ -1,4 +1,4 @@ -import {INFINITY} from './index'; +import {INFINITY} from './helpers.math'; /** * @private
true