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
23bf7c0c89bd3e5ed4cbc2709a08eac63ad1c67d.json
Preserve scriptable context (#7981) * Preserve scriptable context * CC, utilize `index` in tests * Update example to utilize context
test/fixtures/controller.radar/borderColor/scriptable.js
@@ -8,7 +8,7 @@ module.exports = { // option in dataset data: [0, 5, 10, null, -10, -5], borderColor: function(ctx) { - var index = (ctx.dataIndex === undefined ? ctx.datasetIndex : ctx.dataIndex); + var index = ctx.index; return index === 0 ? '#ff0000' : index === 1 ? '#00ff00' : '#0000ff'; @@ -26,7 +26,7 @@ module.exports = { elements: { line: { borderColor: function(ctx) { - var index = (ctx.dataIndex === undefined ? ctx.datasetIndex : ctx.dataIndex); + var index = ctx.index; return index === 0 ? '#ff0000' : index === 1 ? '#00ff00' : '#0000ff';
true
Other
chartjs
Chart.js
23bf7c0c89bd3e5ed4cbc2709a08eac63ad1c67d.json
Preserve scriptable context (#7981) * Preserve scriptable context * CC, utilize `index` in tests * Update example to utilize context
test/fixtures/controller.radar/borderWidth/scriptable.js
@@ -9,7 +9,7 @@ module.exports = { data: [0, 5, 10, null, -10, -5], borderColor: '#0000ff', borderWidth: function(ctx) { - var index = (ctx.dataIndex === undefined ? ctx.datasetIndex : ctx.dataIndex); + var index = ctx.index; return index % 2 ? 10 : 20; }, pointBorderColor: '#00ff00' @@ -27,7 +27,7 @@ module.exports = { line: { borderColor: '#ff0000', borderWidth: function(ctx) { - var index = (ctx.dataIndex === undefined ? ctx.datasetIndex : ctx.dataIndex); + var index = ctx.index; return index % 2 ? 10 : 20; }, fill: false
true
Other
chartjs
Chart.js
72dc37581c13362ee7bee60610cf42ae9e0fad4d.json
Fix typo in test options (#7987)
test/specs/controller.bar.tests.js
@@ -1219,7 +1219,7 @@ describe('Chart.controllers.bar', function() { }, options: { elements: { - bars: { + bar: { backgroundColor: 'rgb(255, 0, 0)', borderColor: 'rgb(0, 0, 255)', borderWidth: 2,
false
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
docs/docs/charts/bar.mdx
@@ -79,7 +79,7 @@ the color of the bars is generally set this way. | Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default | ---- | ---- | :----: | :----: | ---- | [`backgroundColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'` -| [`base`](#general) | `number` | Yes | Yes | +| [`base`](#general) | `number` | Yes | Yes | | [`borderColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'` | [`borderSkipped`](#borderskipped) | `string` | Yes | Yes | `'start'` | [`borderWidth`](#borderwidth) | <code>number&#124;object</code> | Yes | Yes | `0` @@ -234,7 +234,7 @@ If true, the bars for a particular data point fall between the grid lines. The g ## Default Options -It is common to want to apply a configuration setting to all created bar charts. The global bar chart settings are stored in `Chart.defaults.bar`. Changing the global options only affects charts created after the change. Existing charts are not changed. +It is common to want to apply a configuration setting to all created bar charts. The global bar chart settings are stored in `Chart.defaults.controllers.bar`. Changing the global options only affects charts created after the change. Existing charts are not changed. ## barPercentage vs categoryPercentage
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
docs/docs/charts/doughnut.mdx
@@ -169,7 +169,7 @@ These are the customisation options specific to Pie & Doughnut charts. These opt ## Default Options -We can also change these default values for each Doughnut type that is created, this object is available at `Chart.defaults.doughnut`. Pie charts also have a clone of these defaults available to change at `Chart.defaults.pie`, with the only difference being `cutoutPercentage` being set to 0. +We can also change these default values for each Doughnut type that is created, this object is available at `Chart.defaults.controllers.doughnut`. Pie charts also have a clone of these defaults available to change at `Chart.defaults.controllers.pie`, with the only difference being `cutoutPercentage` being set to 0. ## Data Structure
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
docs/docs/charts/line.mdx
@@ -184,12 +184,12 @@ The line chart defines the following configuration options. These options are me ## Default Options -It is common to want to apply a configuration setting to all created line charts. The global line chart settings are stored in `Chart.defaults.line`. Changing the global options only affects charts created after the change. Existing charts are not changed. +It is common to want to apply a configuration setting to all created line charts. The global line chart settings are stored in `Chart.defaults.controllers.line`. Changing the global options only affects charts created after the change. Existing charts are not changed. For example, to configure all line charts with `spanGaps = true` you would do: ```javascript -Chart.defaults.line.spanGaps = true; +Chart.defaults.controllers.line.spanGaps = true; ``` ## Data Structure
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
docs/docs/charts/polar.mdx
@@ -119,12 +119,12 @@ The polar area chart uses the [radialLinear](../axes/radial/linear.md) scale. Ad ## Default Options -We can also change these default values for each PolarArea type that is created, this object is available at `Chart.defaults.polarArea`. Changing the global options only affects charts created after the change. Existing charts are not changed. +We can also change these default values for each PolarArea type that is created, this object is available at `Chart.defaults.controllers.polarArea`. Changing the global options only affects charts created after the change. Existing charts are not changed. For example, to configure all new polar area charts with `animateScale = false` you would do: ```javascript -Chart.defaults.polarArea.animation.animateScale = false; +Chart.defaults.controllers.polarArea.animation.animateScale = false; ``` ## Data Structure
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
docs/docs/charts/radar.mdx
@@ -191,7 +191,7 @@ options = { ## Default Options -It is common to want to apply a configuration setting to all created radar charts. The global radar chart settings are stored in `Chart.defaults.radar`. Changing the global options only affects charts created after the change. Existing charts are not changed. +It is common to want to apply a configuration setting to all created radar charts. The global radar chart settings are stored in `Chart.defaults.controllers.radar`. Changing the global options only affects charts created after the change. Existing charts are not changed. ## Data Structure
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
docs/docs/configuration/index.md
@@ -40,7 +40,7 @@ Options may be configured directly on the dataset. The dataset options can be ch - per dataset: dataset.* - per chart: options[type].datasets.* -- or globally: Chart.defaults[type].datasets.* +- or globally: Chart.defaults.controllers[type].datasets.* where type corresponds to the dataset type.
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
docs/docs/getting-started/v3-migration.md
@@ -100,6 +100,7 @@ A number of changes were made to the configuration options passed to the `Chart` #### Defaults * `global` namespace was removed from `defaults`. So `Chart.defaults.global` is now `Chart.defaults` +* Dataset controller defaults were relocate to `controllers`. For example `Chart.defaults.line` is now `Chart.defaults.controllers.line` * `default` prefix was removed from defaults. For example `Chart.defaults.global.defaultColor` is now `Chart.defaults.color` * `defaultColor` was renamed to `color` * `defaultFontColor` was renamed to `font.color`
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
samples/charts/multi-series-pie.html
@@ -47,7 +47,7 @@ labels: { generateLabels: function(chart) { // Get the default label list - var original = Chart.defaults.pie.legend.labels.generateLabels; + var original = Chart.defaults.controllers.pie.legend.labels.generateLabels; var labels = original.call(this, chart); // Build an array of colors used in the datasets of the chart @@ -92,4 +92,4 @@ </script> </body> -</html> \ No newline at end of file +</html>
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
src/core/core.config.js
@@ -3,7 +3,7 @@ import defaults from './core.defaults'; import {mergeIf, merge, _merger} from '../helpers/helpers.core'; export function getIndexAxis(type, options) { - const typeDefaults = defaults[type] || {}; + const typeDefaults = defaults.controllers[type] || {}; const datasetDefaults = typeDefaults.datasets || {}; const typeOptions = options[type] || {}; const datasetOptions = typeOptions.datasets || {}; @@ -42,7 +42,7 @@ export function determineAxis(id, scaleOptions) { function mergeScaleConfig(config, options) { options = options || {}; - const chartDefaults = defaults[config.type] || {scales: {}}; + const chartDefaults = defaults.controllers[config.type] || {scales: {}}; const configScales = options.scales || {}; const chartIndexAxis = getIndexAxis(config.type, options); const firstIDs = Object.create(null); @@ -67,7 +67,7 @@ function mergeScaleConfig(config, options) { config.data.datasets.forEach(dataset => { const type = dataset.type || config.type; const indexAxis = dataset.indexAxis || getIndexAxis(type, options); - const datasetDefaults = defaults[type] || {}; + const datasetDefaults = defaults.controllers[type] || {}; const defaultScaleOptions = datasetDefaults.scales || {}; Object.keys(defaultScaleOptions).forEach(defaultID => { const axis = getAxisFromDefaultScaleID(defaultID, indexAxis); @@ -94,7 +94,7 @@ function mergeScaleConfig(config, options) { function mergeConfig(...args/* config objects ... */) { return merge(Object.create(null), args, { merger(key, target, source, options) { - if (key !== 'scales' && key !== 'scale') { + if (key !== 'scales' && key !== 'scale' && key !== 'controllers') { _merger(key, target, source, options); } } @@ -104,7 +104,7 @@ function mergeConfig(...args/* config objects ... */) { function includeDefaults(options, type) { return mergeConfig( defaults, - defaults[type], + defaults.controllers[type], options || {}); }
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
src/core/core.controller.js
@@ -384,7 +384,7 @@ class Chart { meta.controller.updateIndex(i); meta.controller.linkScales(); } else { - const controllerDefaults = defaults[type]; + const controllerDefaults = defaults.controllers[type]; const ControllerClass = registry.getController(type); Object.assign(ControllerClass.prototype, { dataElementType: registry.getElement(controllerDefaults.dataElementType),
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
src/core/core.datasetController.js
@@ -1,4 +1,5 @@ import Animations from './core.animations'; +import defaults from './core.defaults'; import {isObject, merge, _merger, isArray, valueOrDefault, mergeIf, resolveObjectKey, _capitalize} from '../helpers/helpers.core'; import {listenArrayEvents, unlistenArrayEvents} from '../helpers/helpers.collection'; import {resolve} from '../helpers/helpers.options'; @@ -335,7 +336,8 @@ export default class DatasetController { configure() { const me = this; me._config = merge(Object.create(null), [ - me.chart.options[me._type].datasets, + defaults.controllers[me._type].datasets, + me.chart.options[me._type]?.datasets, me.getDataset(), ], { merger(key, target, source) {
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
src/core/core.registry.js
@@ -10,7 +10,7 @@ import {each, callback as call, _capitalize} from '../helpers/helpers.core'; */ export class Registry { constructor() { - this.controllers = new TypedRegistry(DatasetController, ''); + this.controllers = new TypedRegistry(DatasetController, 'controllers'); this.elements = new TypedRegistry(Element, 'elements'); this.plugins = new TypedRegistry(Object, 'plugins'); this.scales = new TypedRegistry(Scale, 'scales');
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
test/specs/controller.bar.tests.js
@@ -1286,7 +1286,7 @@ describe('Chart.controllers.bar', function() { var chart = window.acquireChart(this.config); var meta = chart.getDatasetMeta(0); var xScale = chart.scales[meta.xAxisID]; - var options = Chart.defaults.bar.datasets; + var options = Chart.defaults.controllers.bar.datasets; var categoryPercentage = options.categoryPercentage; var barPercentage = options.barPercentage; @@ -1462,7 +1462,7 @@ describe('Chart.controllers.bar', function() { expected = barThickness; } else { var scale = chart.scales.x; - var options = Chart.defaults.bar.datasets; + var options = Chart.defaults.controllers.bar.datasets; var categoryPercentage = options.categoryPercentage; var barPercentage = options.barPercentage; var tickInterval = scale.getPixelForTick(1) - scale.getPixelForTick(0);
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
test/specs/controller.line.tests.js
@@ -499,18 +499,18 @@ describe('Chart.controllers.line', function() { describe('dataset global defaults', function() { beforeEach(function() { - this._defaults = Chart.helpers.clone(Chart.defaults.line.datasets); + this._defaults = Chart.helpers.clone(Chart.defaults.controllers.line.datasets); }); afterEach(function() { - Chart.defaults.line.datasets = this._defaults; + Chart.defaults.controllers.line.datasets = this._defaults; delete this._defaults; }); it('should utilize the dataset global default options', function() { - Chart.defaults.line.datasets = Chart.defaults.line.datasets || {}; + Chart.defaults.controllers.line.datasets = Chart.defaults.controllers.line.datasets || {}; - Chart.helpers.merge(Chart.defaults.line.datasets, { + Chart.helpers.merge(Chart.defaults.controllers.line.datasets, { spanGaps: true, lineTension: 0.231, backgroundColor: '#add', @@ -551,9 +551,9 @@ describe('Chart.controllers.line', function() { }); it('should be overriden by user-supplied values', function() { - Chart.defaults.line.datasets = Chart.defaults.line.datasets || {}; + Chart.defaults.controllers.line.datasets = Chart.defaults.controllers.line.datasets || {}; - Chart.helpers.merge(Chart.defaults.line.datasets, { + Chart.helpers.merge(Chart.defaults.controllers.line.datasets, { spanGaps: true, lineTension: 0.231 });
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
test/specs/core.controller.tests.js
@@ -92,59 +92,59 @@ describe('Chart', function() { it('should initialize config with default interaction options', function() { var callback = function() {}; var defaults = Chart.defaults; - var defaultMode = defaults.line.interaction.mode; + var defaultMode = defaults.controllers.line.interaction.mode; defaults.hover.onHover = callback; - defaults.line.spanGaps = true; - defaults.line.interaction.mode = 'test'; + defaults.controllers.line.spanGaps = true; + defaults.controllers.line.interaction.mode = 'test'; var chart = acquireChart({ type: 'line' }); var options = chart.options; expect(options.font.size).toBe(defaults.font.size); - expect(options.showLine).toBe(defaults.line.showLine); + expect(options.showLine).toBe(defaults.controllers.line.showLine); 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; + defaults.controllers.line.spanGaps = false; + defaults.controllers.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'; + defaults.controllers.line.spanGaps = true; + defaults.controllers.line.hover.mode = 'test'; var chart = acquireChart({ type: 'line' }); var options = chart.options; expect(options.font.size).toBe(defaults.font.size); - expect(options.showLine).toBe(defaults.line.showLine); + expect(options.showLine).toBe(defaults.controllers.line.showLine); 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; - delete defaults.line.hover.mode; + defaults.controllers.line.spanGaps = false; + delete defaults.controllers.line.hover.mode; }); it('should override default options', function() { var callback = function() {}; var defaults = Chart.defaults; defaults.hover.onHover = callback; - defaults.line.hover.mode = 'x-axis'; - defaults.line.spanGaps = true; + defaults.controllers.line.hover.mode = 'x-axis'; + defaults.controllers.line.spanGaps = true; var chart = acquireChart({ type: 'line', @@ -166,8 +166,8 @@ describe('Chart', function() { expect(options.title.position).toBe('bottom'); defaults.hover.onHover = null; - delete defaults.line.hover.mode; - defaults.line.spanGaps = false; + delete defaults.controllers.line.hover.mode; + defaults.controllers.line.spanGaps = false; }); it('should override axis positions that are incorrect', function() { @@ -348,7 +348,7 @@ describe('Chart', function() { expect(chart.scales.x.options._jasmineCheck).toBeDefined(); expect(chart.scales.y.options._jasmineCheck).toBeDefined(); - expect(Chart.defaults.line._jasmineCheck).not.toBeDefined(); + expect(Chart.defaults.controllers.line._jasmineCheck).not.toBeDefined(); expect(Chart.defaults._jasmineCheck).not.toBeDefined(); expect(Chart.defaults.scales.linear._jasmineCheck).not.toBeDefined(); expect(Chart.defaults.scales.category._jasmineCheck).not.toBeDefined();
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
test/specs/core.registry.tests.js
@@ -6,12 +6,12 @@ describe('Chart.registry', function() { CustomController.prototype = Object.create(Chart.controllers.line.prototype); CustomController.prototype.constructor = CustomController; CustomController.id = 'myline'; - CustomController.defaults = Chart.defaults.line; + CustomController.defaults = Chart.defaults.controllers.line; Chart.register(CustomController); expect(Chart.registry.getController('myline')).toEqual(CustomController); - expect(Chart.defaults.myline).toEqual(CustomController.defaults); + expect(Chart.defaults.controllers.myline).toEqual(CustomController.defaults); Chart.unregister(CustomController); }); @@ -94,14 +94,14 @@ describe('Chart.registry', function() { Chart.register(CustomController); expect(Chart.registry.getController('custom')).toEqual(CustomController); - expect(Chart.defaults.custom).toEqual(CustomController.defaults); + expect(Chart.defaults.controllers.custom).toEqual(CustomController.defaults); Chart.unregister(CustomController); expect(function() { Chart.registry.getController('custom'); }).toThrow(new Error('"custom" is not a registered controller.')); - expect(Chart.defaults.custom).not.toBeDefined(); + expect(Chart.defaults.controllers.custom).not.toBeDefined(); }); it('should handle an ES6 scale extension', function() { @@ -120,7 +120,7 @@ describe('Chart.registry', function() { expect(function() { Chart.registry.getScale('es6Scale'); }).toThrow(new Error('"es6Scale" is not a registered scale.')); - expect(Chart.defaults.custom).not.toBeDefined(); + expect(Chart.defaults.controllers.custom).not.toBeDefined(); }); it('should handle an ES6 element extension', function() { @@ -190,14 +190,14 @@ describe('Chart.registry', function() { Chart.registry.addControllers(customExtension); expect(Chart.registry.getController('custom')).toEqual(customExtension); - expect(Chart.defaults.custom).toEqual(customExtension.defaults); + expect(Chart.defaults.controllers.custom).toEqual(customExtension.defaults); Chart.registry.removeControllers(customExtension); expect(function() { Chart.registry.getController('custom'); }).toThrow(new Error('"custom" is not a registered controller.')); - expect(Chart.defaults.custom).not.toBeDefined(); + expect(Chart.defaults.controllers.custom).not.toBeDefined(); }); it('as scale', function() { @@ -285,11 +285,13 @@ describe('Chart.registry', function() { }); it('should not register anything that would collide with existing defaults', function() { + Chart.defaults.controllers.test = {test: true}; class testController extends Chart.DatasetController {} - testController.id = 'events'; + testController.id = 'test'; expect(function() { Chart.register(testController); - }).toThrow(new Error('Can not register "events", because "defaults.events" would collide with existing defaults')); + }).toThrow(new Error('Can not register "test", because "defaults.controllers.test" would collide with existing defaults')); + delete Chart.defaults.controllers.test; }); describe('should handle multiple items', function() {
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
test/specs/global.defaults.tests.js
@@ -33,7 +33,7 @@ describe('Default Configs', function() { describe('Doughnut Chart', function() { it('should return correct tooltip strings', function() { - var config = Chart.defaults.doughnut; + var config = Chart.defaults.controllers.doughnut; var chart = window.acquireChart({ type: 'doughnut', data: { @@ -59,7 +59,7 @@ describe('Default Configs', function() { }); it('should return correct tooltip string for a multiline label', function() { - var config = Chart.defaults.doughnut; + var config = Chart.defaults.controllers.doughnut; var chart = window.acquireChart({ type: 'doughnut', data: { @@ -89,7 +89,7 @@ describe('Default Configs', function() { }); it('should return correct legend label objects', function() { - var config = Chart.defaults.doughnut; + var config = Chart.defaults.controllers.doughnut; var chart = window.acquireChart({ type: 'doughnut', data: { @@ -130,7 +130,7 @@ describe('Default Configs', function() { }); it('should hide the correct arc when a legend item is clicked', function() { - var config = Chart.defaults.doughnut; + var config = Chart.defaults.controllers.doughnut; var chart = window.acquireChart({ type: 'doughnut', data: { @@ -159,7 +159,7 @@ describe('Default Configs', function() { describe('Polar Area Chart', function() { it('should return correct tooltip strings', function() { - var config = Chart.defaults.polarArea; + var config = Chart.defaults.controllers.polarArea; var chart = window.acquireChart({ type: 'polarArea', data: { @@ -185,7 +185,7 @@ describe('Default Configs', function() { }); it('should return correct legend label objects', function() { - var config = Chart.defaults.polarArea; + var config = Chart.defaults.controllers.polarArea; var chart = window.acquireChart({ type: 'polarArea', data: { @@ -226,7 +226,7 @@ describe('Default Configs', function() { }); it('should hide the correct arc when a legend item is clicked', function() { - var config = Chart.defaults.polarArea; + var config = Chart.defaults.controllers.polarArea; var chart = window.acquireChart({ type: 'polarArea', data: {
true
Other
chartjs
Chart.js
4f2511aff345c3f0ce6afb8f2e87fe043f50117b.json
Relocate dataset defaults to defaults.controllers (#7979)
test/specs/platform.dom.tests.js
@@ -119,8 +119,8 @@ describe('Platform.dom', function() { }); it('should use default "chart" aspect ratio for render and display sizes', function() { - var ratio = Chart.defaults.doughnut.aspectRatio; - Chart.defaults.doughnut.aspectRatio = 1; + var ratio = Chart.defaults.controllers.doughnut.aspectRatio; + Chart.defaults.controllers.doughnut.aspectRatio = 1; var chart = acquireChart({ type: 'doughnut', @@ -133,7 +133,7 @@ describe('Platform.dom', function() { } }); - Chart.defaults.doughnut.aspectRatio = ratio; + Chart.defaults.controllers.doughnut.aspectRatio = ratio; expect(chart).toBeChartOfSize({ dw: 425, dh: 425,
true
Other
chartjs
Chart.js
bc59038772b74bff64127098115604520fbf769f.json
Allow 1px margin to getRelativePosition test (#7984)
test/specs/helpers.dom.tests.js
@@ -317,10 +317,9 @@ describe('DOM helpers tests', function() { }; const rect = chart.canvas.getBoundingClientRect(); - expect(helpers.getRelativePosition(event, chart)).toEqual({ - x: Math.round(event.clientX - rect.x), - y: Math.round(event.clientY - rect.y) - }); + const pos = helpers.getRelativePosition(event, chart); + expect(Math.abs(pos.x - Math.round(event.clientX - rect.x))).toBeLessThanOrEqual(1); + expect(Math.abs(pos.y - Math.round(event.clientY - rect.y))).toBeLessThanOrEqual(1); const chart2 = window.acquireChart({}, { canvas: { @@ -330,10 +329,9 @@ describe('DOM helpers tests', function() { } }); const rect2 = chart2.canvas.getBoundingClientRect(); - expect(helpers.getRelativePosition(event, chart2)).toEqual({ - x: Math.round((event.clientX - rect2.x - 10) / 180 * 200), - y: Math.round((event.clientY - rect2.y - 10) / 180 * 200) - }); + const pos2 = helpers.getRelativePosition(event, chart2); + expect(Math.abs(pos2.x - Math.round((event.clientX - rect2.x - 10) / 180 * 200))).toBeLessThanOrEqual(1); + expect(Math.abs(pos2.y - Math.round((event.clientY - rect2.y - 10) / 180 * 200))).toBeLessThanOrEqual(1); const chart3 = window.acquireChart({}, { canvas: { @@ -343,10 +341,9 @@ describe('DOM helpers tests', function() { } }); const rect3 = chart3.canvas.getBoundingClientRect(); - expect(helpers.getRelativePosition(event, chart3)).toEqual({ - x: Math.round((event.clientX - rect3.x - 10) / 360 * 400), - y: Math.round((event.clientY - rect3.y - 10) / 360 * 400) - }); + const pos3 = helpers.getRelativePosition(event, chart3); + expect(Math.abs(pos3.x - Math.round((event.clientX - rect3.x - 10) / 360 * 400))).toBeLessThanOrEqual(1); + expect(Math.abs(pos3.y - Math.round((event.clientY - rect3.y - 10) / 360 * 400))).toBeLessThanOrEqual(1); }); }); });
false
Other
chartjs
Chart.js
68bae7906d93784618bd7d2ef4f760db09a31088.json
fix return type for setActiveElements (#7961)
types/core/index.d.ts
@@ -299,7 +299,7 @@ export declare class Chart< show(datasetIndex: number): void; getActiveElements(): ActiveElement[]; - setActiveElements(active: ActiveDataPoint[]); + setActiveElements(active: ActiveDataPoint[]): void; destroy(): void; toBase64Image(type?: string, quality?: any): string;
true
Other
chartjs
Chart.js
68bae7906d93784618bd7d2ef4f760db09a31088.json
fix return type for setActiveElements (#7961)
types/plugins/index.d.ts
@@ -295,7 +295,7 @@ export const Tooltip: IPlugin & { }; getActiveElements(): ActiveElement[]; - setActiveElements(active: ActiveDataPoint[], eventPosition: { x: number, y: number }); + setActiveElements(active: ActiveDataPoint[], eventPosition: { x: number, y: number }): void; }; export interface ITooltipCallbacks {
true
Other
chartjs
Chart.js
2e43f787de354427a0ec96c505e8934072702ad9.json
Fix small bugs when animations are disabled (#8253) * Fix small bugs when animations are disabled * Update test
src/core/core.controller.js
@@ -1002,13 +1002,13 @@ class Chart { /** * @private */ - _updateHoverStyles(active, lastActive) { + _updateHoverStyles(active, lastActive, replay) { const me = this; const options = me.options || {}; const hoverOptions = options.hover; const diff = (a, b) => a.filter(x => !b.some(y => x.datasetIndex === y.datasetIndex && x.index === y.index)); const deactivated = diff(lastActive, active); - const activated = diff(active, lastActive); + const activated = replay ? active : diff(active, lastActive); if (deactivated.length) { me.updateHoverStyle(deactivated, hoverOptions.mode, false); @@ -1093,7 +1093,7 @@ class Chart { changed = !_elementsEqual(active, lastActive); if (changed || replay) { me._active = active; - me._updateHoverStyles(active, lastActive); + me._updateHoverStyles(active, lastActive, replay); } return changed;
true
Other
chartjs
Chart.js
2e43f787de354427a0ec96c505e8934072702ad9.json
Fix small bugs when animations are disabled (#8253) * Fix small bugs when animations are disabled * Update test
src/core/core.element.js
@@ -37,7 +37,7 @@ export default class Element { } const ret = {}; props.forEach(prop => { - ret[prop] = anims[prop] && anims[prop].active ? anims[prop]._to : me[prop]; + ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : me[prop]; }); return ret; }
true
Other
chartjs
Chart.js
2e43f787de354427a0ec96c505e8934072702ad9.json
Fix small bugs when animations are disabled (#8253) * Fix small bugs when animations are disabled * Update test
src/helpers/helpers.extras.js
@@ -65,5 +65,5 @@ export const _alignStartEnd = (align, start, end) => align === 'start' ? start : */ export function _coordsAnimated(element) { const anims = element && element.$animations; - return anims && ((anims.x && anims.x.active) || (anims.y && anims.y.active)); + return anims && ((anims.x && anims.x.active()) || (anims.y && anims.y.active())); }
true
Other
chartjs
Chart.js
2e43f787de354427a0ec96c505e8934072702ad9.json
Fix small bugs when animations are disabled (#8253) * Fix small bugs when animations are disabled * Update test
test/specs/core.element.tests.js
@@ -8,7 +8,7 @@ describe('Chart.element', function() { expect(elem.getProps(['x', 'y'])).toEqual(jasmine.objectContaining({x: 10, y: 1.5})); expect(elem.getProps(['x', 'y'], true)).toEqual(jasmine.objectContaining({x: 10, y: 1.5})); - elem.$animations = {x: {active: true, _to: 20}}; + elem.$animations = {x: {active: () => true, _to: 20}}; expect(elem.getProps(['x', 'y'])).toEqual(jasmine.objectContaining({x: 10, y: 1.5})); expect(elem.getProps(['x', 'y'], true)).toEqual(jasmine.objectContaining({x: 20, y: 1.5})); });
true
Other
chartjs
Chart.js
59000abd1d96c4e29c6687967f948b47a7db3948.json
Use cached Intl.NumberFormat everywhere (#8244)
src/controllers/controller.doughnut.js
@@ -1,4 +1,5 @@ import DatasetController from '../core/core.datasetController'; +import {formatNumber} from '../core/core.intl'; import {isArray, valueOrDefault} from '../helpers/helpers.core'; import {toRadians, PI, TAU, HALF_PI} from '../helpers/helpers.math'; @@ -235,7 +236,7 @@ export default class DoughnutController extends DatasetController { const meta = me._cachedMeta; const chart = me.chart; const labels = chart.data.labels || []; - const value = new Intl.NumberFormat(chart.options.locale).format(meta._parsed[index]); + const value = formatNumber(meta._parsed[index], chart.options.locale); return { label: labels[index] || '',
true
Other
chartjs
Chart.js
59000abd1d96c4e29c6687967f948b47a7db3948.json
Use cached Intl.NumberFormat everywhere (#8244)
src/core/core.intl.js
@@ -0,0 +1,17 @@ + +const intlCache = new Map(); + +export function getNumberFormat(locale, options) { + options = options || {}; + const cacheKey = locale + JSON.stringify(options); + let formatter = intlCache.get(cacheKey); + if (!formatter) { + formatter = new Intl.NumberFormat(locale, options); + intlCache.set(cacheKey, formatter); + } + return formatter; +} + +export function formatNumber(num, locale, options) { + return getNumberFormat(locale, options).format(num); +}
true
Other
chartjs
Chart.js
59000abd1d96c4e29c6687967f948b47a7db3948.json
Use cached Intl.NumberFormat everywhere (#8244)
src/core/core.ticks.js
@@ -1,7 +1,7 @@ import {isArray} from '../helpers/helpers.core'; import {log10} from '../helpers/helpers.math'; +import {formatNumber} from './core.intl'; -const intlCache = new Map(); /** * Namespace to hold formatters for different types of ticks * @namespace Chart.Ticks.formatters @@ -55,14 +55,7 @@ const formatters = { const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal}; Object.assign(options, this.options.ticks.format); - const cacheKey = locale + JSON.stringify(options); - let formatter = intlCache.get(cacheKey); - if (!formatter) { - formatter = new Intl.NumberFormat(locale, options); - intlCache.set(cacheKey, formatter); - } - - return formatter.format(tickValue); + return formatNumber(tickValue, locale, options); } };
true
Other
chartjs
Chart.js
59000abd1d96c4e29c6687967f948b47a7db3948.json
Use cached Intl.NumberFormat everywhere (#8244)
src/scales/scale.linearbase.js
@@ -1,6 +1,7 @@ import {isNullOrUndef, valueOrDefault} from '../helpers/helpers.core'; import {almostEquals, almostWhole, log10, _decimalPlaces, _setMinAndMaxByKey, sign} from '../helpers/helpers.math'; import Scale from '../core/core.scale'; +import {formatNumber} from '../core/core.intl'; /** * Implementation of the nice number algorithm used in determining where axis labels will go @@ -244,6 +245,6 @@ export default class LinearScaleBase extends Scale { } getLabelForValue(value) { - return new Intl.NumberFormat(this.options.locale).format(value); + return formatNumber(value, this.options.locale); } }
true
Other
chartjs
Chart.js
59000abd1d96c4e29c6687967f948b47a7db3948.json
Use cached Intl.NumberFormat everywhere (#8244)
src/scales/scale.logarithmic.js
@@ -3,6 +3,7 @@ import {_setMinAndMaxByKey, log10} from '../helpers/helpers.math'; import Scale from '../core/core.scale'; import LinearScaleBase from './scale.linearbase'; import Ticks from '../core/core.ticks'; +import {formatNumber} from '../core/core.intl'; function isMajor(tickVal) { const remain = tickVal / (Math.pow(10, Math.floor(log10(tickVal)))); @@ -148,7 +149,7 @@ export default class LogarithmicScale extends Scale { * @return {string} */ getLabelForValue(value) { - return value === undefined ? '0' : new Intl.NumberFormat(this.options.locale).format(value); + return value === undefined ? '0' : formatNumber(value, this.options.locale); } /**
true
Other
chartjs
Chart.js
e530a4d1a0bd264885a559b1bb5213e26d898454.json
Line: Use Path2D as cache (#8239) * Line: Use Path2D as cache * Add comment, move to helpers, first and last point
src/elements/element.line.js
@@ -3,6 +3,7 @@ import {_bezierInterpolation, _pointInLine, _steppedInterpolation} from '../help import {_computeSegments, _boundSegments} from '../helpers/helpers.segment'; import {_steppedLineTo, _bezierCurveTo} from '../helpers/helpers.canvas'; import {_updateBezierControlPoints} from '../helpers/helpers.curve'; +import {_coordsAnimated} from '../helpers/helpers.extras'; /** * @typedef { import("./element.point").default } PointElement @@ -50,7 +51,7 @@ function pathVars(points, segment, params) { /** * Create path from points, grouping by truncated x-coordinate * Points need to be in order by x-coordinate for this to work efficiently - * @param {CanvasRenderingContext2D} ctx - Context + * @param {CanvasRenderingContext2D|Path2D} ctx - Context * @param {LineElement} line * @param {object} segment * @param {number} segment.start - start index of the segment, referring the points array @@ -97,7 +98,7 @@ function pathSegment(ctx, line, segment, params) { /** * Create path from points, grouping by truncated x-coordinate * Points need to be in order by x-coordinate for this to work efficiently - * @param {CanvasRenderingContext2D} ctx - Context + * @param {CanvasRenderingContext2D|Path2D} ctx - Context * @param {LineElement} line * @param {object} segment * @param {number} segment.start - start index of the segment, referring the points array @@ -206,6 +207,7 @@ export default class LineElement extends Element { this.options = undefined; this._loop = undefined; this._fullLoop = undefined; + this._path = undefined; this._points = undefined; this._segments = undefined; this._pointsUpdated = false; @@ -228,6 +230,7 @@ export default class LineElement extends Element { set points(points) { this._points = points; delete this._segments; + delete this._path; } get points() { @@ -317,7 +320,7 @@ export default class LineElement extends Element { /** * Append all segments of this line to current path. - * @param {CanvasRenderingContext2D} ctx + * @param {CanvasRenderingContext2D|Path2D} ctx * @param {number} [start] * @param {number} [count] * @returns {undefined|boolean} - true if line is a full loop (path should be closed) @@ -357,16 +360,25 @@ export default class LineElement extends Element { setStyle(ctx, options); - ctx.beginPath(); - - if (this.path(ctx, start, count)) { - ctx.closePath(); + let path = this._path; + if (!path) { + path = this._path = new Path2D(); + if (this.path(path, start, count)) { + path.closePath(); + } } - ctx.stroke(); + ctx.stroke(path); + ctx.restore(); - this._pointsUpdated = false; + if (_coordsAnimated(points[0]) || _coordsAnimated(points[points.length - 1])) { + // When point coordinates are animating, we need to recalculate the + // path (and control points when beziers are used). Only coordinates + // matter, other animations are ignored. + this._pointsUpdated = false; + this._path = undefined; + } } }
true
Other
chartjs
Chart.js
e530a4d1a0bd264885a559b1bb5213e26d898454.json
Line: Use Path2D as cache (#8239) * Line: Use Path2D as cache * Add comment, move to helpers, first and last point
src/helpers/helpers.extras.js
@@ -1,3 +1,4 @@ + export function fontString(pixelSize, fontStyle, fontFamily) { return fontStyle + ' ' + pixelSize + 'px ' + fontFamily; } @@ -55,3 +56,14 @@ export const _toLeftRightCenter = (align) => align === 'start' ? 'left' : align * @private */ export const _alignStartEnd = (align, start, end) => align === 'start' ? start : align === 'end' ? end : (start + end) / 2; + +/** + * Return true if `x` or `y` property (coordinates) of the element is currently animated. + * @param {object} element + * @returns {boolean} + * @private + */ +export function _coordsAnimated(element) { + const anims = element && element.$animations; + return anims && ((anims.x && anims.x.active) || (anims.y && anims.y.active)); +}
true
Other
chartjs
Chart.js
e6dfc47927508c79aa5495be65e8bda32fffddcf.json
Update spelling of cancellable (#8236)
src/core/core.controller.js
@@ -462,7 +462,7 @@ class Chart { // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167 me._plugins.invalidate(); - if (me.notifyPlugins('beforeUpdate', {mode, cancelable: true}) === false) { + if (me.notifyPlugins('beforeUpdate', {mode, cancellable: true}) === false) { return; } @@ -504,7 +504,7 @@ class Chart { _updateLayout() { const me = this; - if (me.notifyPlugins('beforeLayout', {cancelable: true}) === false) { + if (me.notifyPlugins('beforeLayout', {cancellable: true}) === false) { return; } @@ -544,7 +544,7 @@ class Chart { const me = this; const isFunction = typeof mode === 'function'; - if (me.notifyPlugins('beforeDatasetsUpdate', {mode, cancelable: true}) === false) { + if (me.notifyPlugins('beforeDatasetsUpdate', {mode, cancellable: true}) === false) { return; } @@ -563,21 +563,21 @@ class Chart { _updateDataset(index, mode) { const me = this; const meta = me.getDatasetMeta(index); - const args = {meta, index, mode, cancelable: true}; + const args = {meta, index, mode, cancellable: true}; if (me.notifyPlugins('beforeDatasetUpdate', args) === false) { return; } meta.controller._update(mode); - args.cancelable = false; + args.cancellable = false; me.notifyPlugins('afterDatasetUpdate', args); } render() { const me = this; - if (me.notifyPlugins('beforeRender', {cancelable: true}) === false) { + if (me.notifyPlugins('beforeRender', {cancellable: true}) === false) { return; } @@ -605,7 +605,7 @@ class Chart { return; } - if (me.notifyPlugins('beforeDraw', {cancelable: true}) === false) { + if (me.notifyPlugins('beforeDraw', {cancellable: true}) === false) { return; } @@ -662,7 +662,7 @@ class Chart { _drawDatasets() { const me = this; - if (me.notifyPlugins('beforeDatasetsDraw', {cancelable: true}) === false) { + if (me.notifyPlugins('beforeDatasetsDraw', {cancellable: true}) === false) { return; } @@ -687,7 +687,7 @@ class Chart { const args = { meta, index: meta.index, - cancelable: true + cancellable: true }; if (me.notifyPlugins('beforeDatasetDraw', args) === false) { @@ -705,7 +705,7 @@ class Chart { unclipArea(ctx); - args.cancelable = false; + args.cancellable = false; me.notifyPlugins('afterDatasetDraw', args); } @@ -1020,15 +1020,15 @@ class Chart { */ _eventHandler(e, replay) { const me = this; - const args = {event: e, replay, cancelable: true}; + const args = {event: e, replay, cancellable: true}; if (me.notifyPlugins('beforeEvent', args) === false) { return; } const changed = me._handleEvent(e, replay); - args.cancelable = false; + args.cancellable = false; me.notifyPlugins('afterEvent', args); if (changed) {
true
Other
chartjs
Chart.js
e6dfc47927508c79aa5495be65e8bda32fffddcf.json
Update spelling of cancellable (#8236)
src/core/core.plugins.js
@@ -50,7 +50,7 @@ export default class PluginService { const plugin = descriptor.plugin; const method = plugin[hook]; const params = [chart, args, descriptor.options]; - if (callCallback(method, params, plugin) === false && args.cancelable) { + if (callCallback(method, params, plugin) === false && args.cancellable) { return false; } }
true
Other
chartjs
Chart.js
e6dfc47927508c79aa5495be65e8bda32fffddcf.json
Update spelling of cancellable (#8236)
test/specs/core.plugin.tests.js
@@ -151,7 +151,7 @@ describe('Chart.plugins', function() { spyOn(plugin, 'hook').and.callThrough(); }); - var ret = chart.notifyPlugins('hook', {cancelable: true}); + var ret = chart.notifyPlugins('hook', {cancellable: true}); expect(ret).toBeFalsy(); expect(plugins[0].hook).toHaveBeenCalled(); expect(plugins[1].hook).toHaveBeenCalled();
true
Other
chartjs
Chart.js
78e78256a5e2630b2bba644a8d48ec1674220179.json
Cache the lineheight regex (#8240)
src/helpers/helpers.options.js
@@ -2,6 +2,8 @@ import defaults from '../core/core.defaults'; import {isArray, isObject, valueOrDefault} from './helpers.core'; import {toFontString} from './helpers.canvas'; +const LINE_HEIGHT = new RegExp(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/); + /** * @alias Chart.helpers.options * @namespace @@ -15,7 +17,7 @@ import {toFontString} from './helpers.canvas'; * @since 2.7.0 */ export function toLineHeight(value, size) { - const matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/); + const matches = ('' + value).match(LINE_HEIGHT); if (!matches || matches[1] === 'normal') { return size * 1.2; }
false
Other
chartjs
Chart.js
55dd7ded0e7c6133c615c28aa3d46ab97ea08a82.json
Remove duplicate Scriptable definitions (#8223)
types/index.esm.d.ts
@@ -16,11 +16,31 @@ import { TimeUnit } from "./adapters"; import { AnimationEvent } from './animation'; import { Element }from './element'; import { ChartArea, Point } from './geometric'; +import { + Scriptable, + ScriptableOptions, + ScriptableAndArrayOptions +} from './scriptable'; export { DateAdapterBase, DateAdapter, TimeUnit, _adapters } from './adapters'; export { Animation, Animations, Animator, AnimationEvent } from './animation'; export { Element } from './element'; export { ChartArea, Point } from './geometric'; +export { + Scriptable, + ScriptableOptions, + ScriptableAndArray, + ScriptableAndArrayOptions +} from './scriptable'; + +export interface ScriptableContext { + chart: Chart; + dataPoint: any; + dataIndex: number; + dataset: ChartDataset; + datasetIndex: number; + active: boolean; +} export interface ParsingOptions { /** @@ -60,8 +80,8 @@ export interface ControllerDatasetOptions extends ParsingOptions { export interface BarControllerDatasetOptions extends ControllerDatasetOptions, - ScriptableAndArrayOptions<BarOptions>, - ScriptableAndArrayOptions<CommonHoverOptions> { + ScriptableAndArrayOptions<BarOptions, ScriptableContext>, + ScriptableAndArrayOptions<CommonHoverOptions, ScriptableContext> { /** * The base axis of the dataset. 'x' for vertical bars and 'y' for horizontal bars. * @default 'x' @@ -118,8 +138,8 @@ export const BarController: ChartComponent & { export interface BubbleControllerDatasetOptions extends ControllerDatasetOptions, - ScriptableAndArrayOptions<PointOptions>, - ScriptableAndArrayOptions<PointHoverOptions> {} + ScriptableAndArrayOptions<PointOptions, ScriptableContext>, + ScriptableAndArrayOptions<PointHoverOptions, ScriptableContext> {} export interface BubbleDataPoint { /** @@ -146,10 +166,10 @@ export const BubbleController: ChartComponent & { export interface LineControllerDatasetOptions extends ControllerDatasetOptions, - ScriptableAndArrayOptions<PointPrefixedOptions>, - ScriptableAndArrayOptions<PointPrefixedHoverOptions>, - ScriptableOptions<LineOptions>, - ScriptableOptions<LineHoverOptions> { + ScriptableAndArrayOptions<PointPrefixedOptions, ScriptableContext>, + ScriptableAndArrayOptions<PointPrefixedHoverOptions, ScriptableContext>, + ScriptableOptions<LineOptions, ScriptableContext>, + ScriptableOptions<LineHoverOptions, ScriptableContext> { /** * The ID of the x axis to plot this dataset on. */ @@ -204,8 +224,8 @@ export const ScatterController: ChartComponent & { export interface DoughnutControllerDatasetOptions extends ControllerDatasetOptions, - ScriptableAndArrayOptions<ArcOptions>, - ScriptableAndArrayOptions<ArcHoverOptions> { + ScriptableAndArrayOptions<ArcOptions, ScriptableContext>, + ScriptableAndArrayOptions<ArcHoverOptions, ScriptableContext> { /** * Sweep to allow arcs to cover. @@ -322,10 +342,10 @@ export const PolarAreaController: ChartComponent & { export interface RadarControllerDatasetOptions extends ControllerDatasetOptions, - ScriptableOptions<PointPrefixedOptions>, - ScriptableOptions<PointPrefixedHoverOptions>, - ScriptableOptions<LineOptions>, - ScriptableOptions<LineHoverOptions> { + ScriptableOptions<PointPrefixedOptions, ScriptableContext>, + ScriptableOptions<PointPrefixedHoverOptions, ScriptableContext>, + ScriptableOptions<LineOptions, ScriptableContext>, + ScriptableOptions<LineHoverOptions, ScriptableContext> { /** * The ID of the x axis to plot this dataset on. */ @@ -1268,15 +1288,13 @@ export const Scale: { new <O extends CoreScaleOptions = CoreScaleOptions>(cfg: any): Scale<O>; }; -export interface ScriptAbleScaleContext { +export interface ScriptableScaleContext { chart: Chart; scale: Scale; index: number; tick: Tick; } -export type ScriptAbleScale<T> = T | ((ctx: ScriptAbleScaleContext) => T); - export const Ticks: { formatters: { /** @@ -1345,21 +1363,6 @@ export interface ChartComponent { afterUnregister?(): void; } - -export interface ScriptableContext { - chart: Chart; - dataPoint: any; - dataIndex: number; - dataset: ChartDataset; - datasetIndex: number; - active: boolean; -} - -export type Scriptable<T> = T | ((ctx: ScriptableContext) => T); -export type ScriptableOptions<T> = { [P in keyof T]: Scriptable<T[P]> }; -export type ScriptableAndArray<T> = readonly T[] | Scriptable<T>; -export type ScriptableAndArrayOptions<T> = { [P in keyof T]: ScriptableAndArray<T[P]> }; - export interface CoreInteractionOptions { /** * Sets which elements appear in the tooltip. See Interaction Modes for details. @@ -1386,10 +1389,10 @@ export interface HoverInteractionOptions extends CoreInteractionOptions { } export interface CoreChartOptions extends ParsingOptions { - animation: Scriptable<AnimationOptions | false>; + animation: Scriptable<AnimationOptions | false, ScriptableContext>; datasets: { - animation: Scriptable<AnimationOptions | false>; + animation: Scriptable<AnimationOptions | false, ScriptableContext>; }; /** @@ -1467,7 +1470,7 @@ export interface CoreChartOptions extends ParsingOptions { onClick(event: ChartEvent, elements: ActiveElement[], chart: Chart): void; layout: { - padding: Scriptable<number | ChartArea>; + padding: Scriptable<number | ChartArea, ScriptableContext>; }; plugins: PluginOptions; @@ -2488,7 +2491,7 @@ export interface TooltipOptions extends CoreInteractionOptions { */ textDirection: string; - animation: Scriptable<AnimationSpecContainer>; + animation: Scriptable<AnimationSpecContainer, ScriptableContext>; callbacks: TooltipCallbacks; } @@ -2555,19 +2558,19 @@ export interface GridLineOptions { /** * @default 'rgba(0, 0, 0, 0.1)' */ - color: ScriptAbleScale<Color> | readonly Color[]; + color: Scriptable<Color, ScriptableScaleContext> | readonly Color[]; /** * @default [] */ borderDash: number[]; /** * @default 0 */ - borderDashOffset: ScriptAbleScale<number>; + borderDashOffset: Scriptable<number, ScriptableScaleContext>; /** * @default 1 */ - lineWidth: ScriptAbleScale<number> | readonly number[]; + lineWidth: Scriptable<number, ScriptableScaleContext> | readonly number[]; /** * @default true @@ -2588,11 +2591,11 @@ export interface GridLineOptions { /** * @default 0 */ - tickBorderDashOffset: ScriptAbleScale<number>; + tickBorderDashOffset: Scriptable<number, ScriptableScaleContext>; /** * @default 'rgba(0, 0, 0, 0.1)' */ - tickColor: ScriptAbleScale<Color> | readonly Color[]; + tickColor: Scriptable<Color, ScriptableScaleContext> | readonly Color[]; /** * @default 10 */ @@ -2621,11 +2624,11 @@ export interface TickOptions { * Color of tick * @see Defaults.color */ - color: ScriptAbleScale<Color>; + color: Scriptable<Color, ScriptableScaleContext>; /** * see Fonts */ - font: ScriptAbleScale<FontSpec>; + font: Scriptable<FontSpec, ScriptableScaleContext>; /** * Sets the offset of the tick labels from the axis */ @@ -2954,22 +2957,22 @@ export type RadialLinearScaleOptions = CoreScaleOptions & { * Color of angled lines. * @default 'rgba(0, 0, 0, 0.1)' */ - color: ScriptAbleScale<Color>; + color: Scriptable<Color, ScriptableScaleContext>; /** * Width of angled lines. * @default 1 */ - lineWidth: ScriptAbleScale<number>; + lineWidth: Scriptable<number, ScriptableScaleContext>; /** * Length and spacing of dashes on angled lines. See MDN. * @default [] */ - borderDash: ScriptAbleScale<number[]>; + borderDash: Scriptable<number[], ScriptableScaleContext>; /** * Offset for line dashes. See MDN. * @default 0 */ - borderDashOffset: ScriptAbleScale<number>; + borderDashOffset: Scriptable<number, ScriptableScaleContext>; }; /** @@ -2999,11 +3002,11 @@ export type RadialLinearScaleOptions = CoreScaleOptions & { * Color of label * @see Defaults.color */ - color: ScriptAbleScale<Color>; + color: Scriptable<Color, ScriptableScaleContext>; /** * @see https://www.chartjs.org/docs/next/axes/general/fonts.md */ - font: ScriptAbleScale<FontSpec>; + font: Scriptable<FontSpec, ScriptableScaleContext>; /** * Callback function to transform data labels to point labels. The default implementation simply returns the current string. @@ -3026,7 +3029,7 @@ export type RadialLinearScaleOptions = CoreScaleOptions & { * Color of label backdrops. * @default 'rgba(255, 255, 255, 0.75)' */ - backdropColor: ScriptAbleScale<Color>; + backdropColor: Scriptable<Color, ScriptableScaleContext>; /** * Horizontal padding of label backdrop. * @default 2 @@ -3063,7 +3066,7 @@ export type RadialLinearScaleOptions = CoreScaleOptions & { * If true, draw a background behind the tick labels. * @default true */ - showLabelBackdrop: ScriptAbleScale<boolean>; + showLabelBackdrop: Scriptable<boolean, ScriptableScaleContext>; }; };
true
Other
chartjs
Chart.js
55dd7ded0e7c6133c615c28aa3d46ab97ea08a82.json
Remove duplicate Scriptable definitions (#8223)
types/scriptable.d.ts
@@ -0,0 +1,4 @@ +export type Scriptable<T, TContext> = T | ((ctx: TContext) => T); +export type ScriptableOptions<T, TContext> = { [P in keyof T]: Scriptable<T[P], TContext> }; +export type ScriptableAndArray<T, TContext> = readonly T[] | Scriptable<T, TContext>; +export type ScriptableAndArrayOptions<T, TContext> = { [P in keyof T]: ScriptableAndArray<T[P], TContext> };
true
Other
chartjs
Chart.js
491f871218d94889c9c929a19973c852e5cdc6e5.json
Add note about loading fonts and chart updates (#8214)
docs/docs/general/fonts.md
@@ -37,3 +37,7 @@ let chart = new Chart(ctx, { ## Missing Fonts If a font is specified for a chart that does exist on the system, the browser will not apply the font when it is set. If you notice odd fonts appearing in your charts, check that the font you are applying exists on your system. See [issue 3318](https://github.com/chartjs/Chart.js/issues/3318) for more details. + +## Loading Fonts + +If a font is not cached and needs to be loaded, charts that use the font will need to be updated once the font is loaded. This can be accomplished using the [Font Loading APIs](https://developer.mozilla.org/en-US/docs/Web/API/CSS_Font_Loading_API). See [issue 8020](https://github.com/chartjs/Chart.js/issues/8020) for more details.
false
Other
chartjs
Chart.js
e529775d5ed82c431e60fc8ef5c64b39ff0c69d8.json
Update showLine location in defaults (#8199) Current defaults was wrong. Working example: https://jsfiddle.net/Leelenaleee/vL7d6yp0/5/
docs/docs/configuration/index.md
@@ -50,7 +50,7 @@ The following example would set the `showLine` option to 'false' for all line da ```javascript // Do not show lines for all datasets by default -Chart.defaults.datasets.line.showLine = false; +Chart.defaults.controllers.line.showLine = false; // This chart would show a line only for the third dataset var chart = new Chart(ctx, {
false
Other
chartjs
Chart.js
b55b361f97461996eec01c6013c6617601c77b12.json
Reject pending promises when animation is updated (#8184) * Reject pending promises when animation is updated * Add tests
src/core/core.animation.js
@@ -46,6 +46,8 @@ export default class Animation { update(cfg, to, date) { const me = this; if (me._active) { + me._notify(false); + const currentValue = me._target[me._prop]; const elapsed = date - me._start; const remain = me._duration - elapsed;
true
Other
chartjs
Chart.js
b55b361f97461996eec01c6013c6617601c77b12.json
Reject pending promises when animation is updated (#8184) * Reject pending promises when animation is updated * Add tests
src/core/core.animations.js
@@ -131,6 +131,8 @@ export default class Animations { // So any new updates to the shared options are observed awaitAll(target.options.$animations, newOptions).then(() => { target.options = newOptions; + }, () => { + // rejected, noop }); }
true
Other
chartjs
Chart.js
b55b361f97461996eec01c6013c6617601c77b12.json
Reject pending promises when animation is updated (#8184) * Reject pending promises when animation is updated * Add tests
test/specs/core.animations.tests.js
@@ -96,4 +96,93 @@ describe('Chart.animations', function() { done(); }, 300); }); + + it('should not assign shared options to target when animations are cancelled', function(done) { + const chart = { + draw: function() {}, + options: { + animation: { + debug: false + } + } + }; + const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}}); + + const target = { + value: 1, + options: { + option: 2 + } + }; + const sharedOpts = {option: 10, $shared: true}; + + expect(anims.update(target, { + options: sharedOpts + })).toBeTrue(); + + expect(target.options !== sharedOpts).toBeTrue(); + + Chart.animator.start(chart); + + setTimeout(function() { + expect(Chart.animator.running(chart)).toBeTrue(); + Chart.animator.stop(chart); + expect(Chart.animator.running(chart)).toBeFalse(); + + setTimeout(function() { + expect(target.options === sharedOpts).toBeFalse(); + + Chart.animator.remove(chart); + done(); + }, 250); + }, 50); + }); + + + it('should assign final shared options to target after animations complete', function(done) { + const chart = { + draw: function() {}, + options: { + animation: { + debug: false + } + } + }; + const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}}); + + const origOpts = {option: 2}; + const target = { + value: 1, + options: origOpts + }; + const sharedOpts = {option: 10, $shared: true}; + const sharedOpts2 = {option: 20, $shared: true}; + + expect(anims.update(target, { + options: sharedOpts + })).toBeTrue(); + + expect(target.options !== sharedOpts).toBeTrue(); + + Chart.animator.start(chart); + + setTimeout(function() { + expect(Chart.animator.running(chart)).toBeTrue(); + + expect(target.options === origOpts).toBeTrue(); + + expect(anims.update(target, { + options: sharedOpts2 + })).toBeUndefined(); + + expect(target.options === origOpts).toBeTrue(); + + setTimeout(function() { + expect(target.options === sharedOpts2).toBeTrue(); + + Chart.animator.remove(chart); + done(); + }, 250); + }, 50); + }); });
true
Other
chartjs
Chart.js
3c79d104d97aa7ed25ba4e9fc134809078a2f324.json
Add ArcElement to getting-started.md (#8174) * fix: add ArcElement to getting-started.md * fix: add all possible imports * fix: add text to integration.md
docs/docs/getting-started/integration.md
@@ -24,10 +24,58 @@ var myChart = new Chart(ctx, {...}); Chart.js 3 is tree-shakeable, so it is necessary to import and register the controllers, elements, scales and plugins you are going to use. +For all available imports see the example below. ```javascript -import { Chart, LineController, LineElement, PointElement, LinearScale, CategoryScale, Title, Tooltip, Filler, Legend } from 'chart.js'; +import { + Chart, + ArcElement, + LineElement, + BarElement, + PointElement, + BarController, + BubbleController, + DoughnutController, + LineController, + PieController, + PolarAreaController, + RadarController, + ScatterController, + CategoryScale, + LinearScale, + LogarithmicScale, + RadialLinearScale, + TimeScale, + TimeSeriesScale, + Filler, + Legend, + Title, + Tooltip +} from 'chart.js'; -Chart.register(LineController, LineElement, PointElement, LinearScale, CategoryScale, Title, Tooltip, Filler, Legend); +Chart.register( + ArcElement, + LineElement, + BarElement, + PointElement, + BarController, + BubbleController, + DoughnutController, + LineController, + PieController, + PolarAreaController, + RadarController, + ScatterController, + CategoryScale, + LinearScale, + LogarithmicScale, + RadialLinearScale, + TimeScale, + TimeSeriesScale, + Filler, + Legend, + Title, + Tooltip +); var myChart = new Chart(ctx, {...}); ```
false
Other
chartjs
Chart.js
f191f2f5f9a1e1e1a95f1722b41d168244b1d554.json
Remove dataset while hovered (#8181)
src/core/core.controller.js
@@ -725,7 +725,7 @@ class Chart { hidden: null, // See isDatasetVisible() comment xAxisID: null, yAxisID: null, - order: dataset.order || 0, + order: dataset && dataset.order || 0, index: datasetIndex, _dataset: dataset, _parsed: [], @@ -808,7 +808,7 @@ class Chart { const me = this; const meta = me._metasets && me._metasets[datasetIndex]; - if (meta) { + if (meta && meta.controller) { meta.controller._destroy(); delete me._metasets[datasetIndex]; } @@ -933,8 +933,9 @@ class Chart { for (i = 0, ilen = items.length; i < ilen; ++i) { item = items[i]; - if (item) { - this.getDatasetMeta(item.datasetIndex).controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index); + const controller = item && this.getDatasetMeta(item.datasetIndex).controller; + if (controller) { + controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index); } } }
false
Other
chartjs
Chart.js
8ab62f57be0c65f16520ede167590a95ef76c8cf.json
Use correct color for legend labels (#8167) * Legend colors fallback * Update test
docs/docs/configuration/legend.md
@@ -52,6 +52,7 @@ The legend label configuration is nested below the legend configuration using th | ---- | ---- | ------- | ----------- | `boxWidth` | `number` | `40` | Width of coloured box. | `boxHeight` | `number` | fontSize | Height of the coloured box. +| `color` |[`Color`](../general/colors.md) | `defaults.color` | Color of text. | `font` | `Font` | `defaults.font` | See [Fonts](../general/fonts.md) | `padding` | `number` | `10` | Padding between rows of colored boxes. | `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. @@ -66,9 +67,10 @@ The legend title configuration is nested below the legend configuration using th | Name | Type | Default | Description | ---- | ---- | ------- | ----------- +| `color` | [`Color`](../general/colors.md) | `defaults.color` | Color of text. | `display` | `boolean` | `false` | Is the legend title displayed. | `font` | `Font` | `defaults.font` | See [Fonts](../general/fonts.md) -| `padding` | <code>number&#124;object</code> | `0` | Padding around the title. If specified as a number, it applies evenly to all sides. +| `padding` | `number`\|`object` | `0` | Padding around the title. If specified as a number, it applies evenly to all sides. | `text` | `string` | | The string title. ## Legend Item Interface
true
Other
chartjs
Chart.js
8ab62f57be0c65f16520ede167590a95ef76c8cf.json
Use correct color for legend labels (#8167) * Legend colors fallback * Update test
src/plugins/plugin.legend.js
@@ -611,5 +611,10 @@ export default { position: 'center', text: '', } + }, + + defaultRoutes: { + 'labels.color': 'color', + 'title.color': 'color' } };
true
Other
chartjs
Chart.js
8ab62f57be0c65f16520ede167590a95ef76c8cf.json
Use correct color for legend labels (#8167) * Legend colors fallback * Update test
test/specs/plugin.legend.tests.js
@@ -17,12 +17,14 @@ describe('Legend block tests', function() { onLeave: null, labels: { + color: Chart.defaults.color, boxWidth: 40, padding: 10, generateLabels: jasmine.any(Function) }, title: { + color: Chart.defaults.color, display: false, position: 'center', text: '',
true
Other
chartjs
Chart.js
dc00ed08cb7753a8df61edda1e5c660c71f7ec57.json
Update docs on printing (#8149) From what I can tell from testing locally, Chrome doesn't reliably trigger resize events for the final print layout, so using `.resize()` with no parameters doesn't generally work. I'm not sure if there are circumstances in which the original docs' suggestion of using `.resize()` with no parameters can work; if the original text should be deleted, I can do so. I also noticed that the TypeScript type definitions for `.resize()` mark the parameters as required, even though the implementation and docs don't require them.
docs/docs/general/responsive.md
@@ -41,7 +41,7 @@ Note that in order for the above code to correctly resize the chart height, the ## 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. +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, you need to hook the [onbeforeprint](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeprint) event and manually trigger resizing of each chart. ```javascript function beforePrintHandler () { @@ -50,3 +50,14 @@ function beforePrintHandler () { } } ``` + +You may also find that, due to complexities in when the browser lays out the document for printing and when resize events are fired, Chart.js is unable to properly resize for the print layout. To work around this, you can pass an explicit size to `.resize()` then use an [onafterprint](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onafterprint) event to restore the automatic size when done. + +```javascript +window.addEventListener('beforeprint', () => { + myChart.resize(600, 600); +}); +window.addEventListener('afterprint', () => { + myChart.resize(); +}); +```
true
Other
chartjs
Chart.js
dc00ed08cb7753a8df61edda1e5c660c71f7ec57.json
Update docs on printing (#8149) From what I can tell from testing locally, Chrome doesn't reliably trigger resize events for the final print layout, so using `.resize()` with no parameters doesn't generally work. I'm not sure if there are circumstances in which the original docs' suggestion of using `.resize()` with no parameters can work; if the original text should be deleted, I can do so. I also noticed that the TypeScript type definitions for `.resize()` mark the parameters as required, even though the implementation and docs don't require them.
types/core/index.d.ts
@@ -197,7 +197,7 @@ export declare class Chart< clear(): this; stop(): this; - resize(width: number, height: number): void; + resize(width?: number, height?: number): void; ensureScalesHaveIDs(): void; buildOrUpdateScales(): void; buildOrUpdateControllers(): void;
true
Other
chartjs
Chart.js
ae04fcf3c3818a2ceb67556a9bde8da29d42b2c3.json
fix default font color for legend (#8139) * fix default font color for legend * adjusted docs to be consistent with fontColor to color
docs/docs/configuration/legend.md
@@ -125,7 +125,7 @@ var chart = new Chart(ctx, { legend: { display: true, labels: { - fontColor: 'rgb(255, 99, 132)' + color: 'rgb(255, 99, 132)' } } }
true
Other
chartjs
Chart.js
ae04fcf3c3818a2ceb67556a9bde8da29d42b2c3.json
fix default font color for legend (#8139) * fix default font color for legend * adjusted docs to be consistent with fontColor to color
src/plugins/plugin.legend.js
@@ -311,7 +311,7 @@ export class Legend extends Element { const rtlHelper = getRtlAdapter(opts.rtl, me.left, me._minSize.width); const ctx = me.ctx; const labelFont = toFont(labelOpts.font, me.chart.options.font); - const fontColor = labelOpts.color; + const fontColor = labelOpts.color || defaultColor; const fontSize = labelFont.size; let cursor;
true
Other
chartjs
Chart.js
39c2b92bb2858cdc381a5ec8fbbc5a27af7cb6cd.json
Fix the needs job name (#8129)
.github/workflows/release.yml
@@ -49,7 +49,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} publish: - needs: [version, draft] + needs: [version, notes] runs-on: ubuntu-latest steps: - uses: actions/checkout@v2
false
Other
chartjs
Chart.js
c1aeba1e67593d0cf1bd75b50fb2c7724f768cee.json
Add new scale hooks for plugins (#8112) * Add new scale hooks for plugins * Add notes * cc * cancelability
src/core/core.controller.js
@@ -440,7 +440,6 @@ class Chart { update(mode) { const me = this; - const args = {mode}; let i, ilen; each(me.scales, (scale) => { @@ -458,7 +457,7 @@ class Chart { // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167 me._plugins.invalidate(); - if (me.notifyPlugins('beforeUpdate', args) === false) { + if (me.notifyPlugins('beforeUpdate', {mode, cancelable: true}) === false) { return; } @@ -480,7 +479,7 @@ class Chart { me._updateDatasets(mode); // Do this before render so that any plugins that need final scale updates can use it - me.notifyPlugins('afterUpdate', args); + me.notifyPlugins('afterUpdate', {mode}); me._layers.sort(compare2Level('z', '_idx')); @@ -500,7 +499,7 @@ class Chart { _updateLayout() { const me = this; - if (me.notifyPlugins('beforeLayout') === false) { + if (me.notifyPlugins('beforeLayout', {cancelable: true}) === false) { return; } @@ -531,17 +530,16 @@ class Chart { _updateDatasets(mode) { const me = this; const isFunction = typeof mode === 'function'; - const args = {mode}; - if (me.notifyPlugins('beforeDatasetsUpdate', args) === false) { + if (me.notifyPlugins('beforeDatasetsUpdate', {mode, cancelable: true}) === false) { return; } for (let i = 0, ilen = me.data.datasets.length; i < ilen; ++i) { me._updateDataset(i, isFunction ? mode({datasetIndex: i}) : mode); } - me.notifyPlugins('afterDatasetsUpdate', args); + me.notifyPlugins('afterDatasetsUpdate', {mode}); } /** @@ -552,20 +550,21 @@ class Chart { _updateDataset(index, mode) { const me = this; const meta = me.getDatasetMeta(index); - const args = {meta, index, mode}; + const args = {meta, index, mode, cancelable: true}; if (me.notifyPlugins('beforeDatasetUpdate', args) === false) { return; } meta.controller._update(mode); + args.cancelable = false; me.notifyPlugins('afterDatasetUpdate', args); } render() { const me = this; - if (me.notifyPlugins('beforeRender') === false) { + if (me.notifyPlugins('beforeRender', {cancelable: true}) === false) { return; } @@ -593,7 +592,7 @@ class Chart { return; } - if (me.notifyPlugins('beforeDraw') === false) { + if (me.notifyPlugins('beforeDraw', {cancelable: true}) === false) { return; } @@ -650,7 +649,7 @@ class Chart { _drawDatasets() { const me = this; - if (me.notifyPlugins('beforeDatasetsDraw') === false) { + if (me.notifyPlugins('beforeDatasetsDraw', {cancelable: true}) === false) { return; } @@ -675,6 +674,7 @@ class Chart { const args = { meta, index: meta.index, + cancelable: true }; if (me.notifyPlugins('beforeDatasetDraw', args) === false) { @@ -692,6 +692,7 @@ class Chart { unclipArea(ctx); + args.cancelable = false; me.notifyPlugins('afterDatasetDraw', args); } @@ -1004,14 +1005,15 @@ class Chart { */ _eventHandler(e, replay) { const me = this; - const args = {event: e, replay}; + const args = {event: e, replay, cancelable: true}; if (me.notifyPlugins('beforeEvent', args) === false) { return; } const changed = me._handleEvent(e, replay); + args.cancelable = false; me.notifyPlugins('afterEvent', args); if (changed) {
true
Other
chartjs
Chart.js
c1aeba1e67593d0cf1bd75b50fb2c7724f768cee.json
Add new scale hooks for plugins (#8112) * Add new scale hooks for plugins * Add notes * cc * cancelability
src/core/core.plugins.js
@@ -49,7 +49,7 @@ export default class PluginService { const plugin = descriptor.plugin; const method = plugin[hook]; const params = [chart, args, descriptor.options]; - if (callCallback(method, params, plugin) === false) { + if (callCallback(method, params, plugin) === false && args.cancelable) { return false; } } @@ -149,272 +149,3 @@ function createDescriptors(plugins, options, all) { return result; } - -/** - * Plugin extension hooks. - * @interface Plugin - * @typedef {object} IPlugin - * @since 2.1.0 - */ -/** - * @method IPlugin#install - * @desc Called when plugin is installed for this chart instance. This hook is called on disabled plugins (options === false). - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {object} options - The plugin options. - * @since 3.0.0 - */ -/** - * @method IPlugin#start - * @desc Called when a plugin is starting. This happens when chart is created or plugin is enabled. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {object} options - The plugin options. - * @since 3.0.0 - */ -/** - * @method IPlugin#stop - * @desc Called when a plugin stopping. This happens when chart is destroyed or plugin is disabled. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {object} options - The plugin options. - * @since 3.0.0 - */ -/** - * @method IPlugin#beforeInit - * @desc Called before initializing `chart`. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {object} options - The plugin options. - */ -/** - * @method IPlugin#afterInit - * @desc Called after `chart` has been initialized and before the first update. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {object} options - The plugin options. - */ -/** - * @method IPlugin#beforeUpdate - * @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. - */ -/** - * @method IPlugin#afterUpdate - * @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. - */ -/** - * @method IPlugin#reset - * @desc Called during chart reset - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {object} options - The plugin options. - * @since version 3.0.0 - */ -/** - * @method IPlugin#beforeDatasetsUpdate - * @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 -*/ -/** - * @method IPlugin#afterDatasetsUpdate - * @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 - */ -/** - * @method IPlugin#beforeDatasetUpdate - * @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 {string} args.mode - The update mode - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart datasets drawing. - */ -/** - * @method IPlugin#afterDatasetUpdate - * @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 {string} args.mode - The update mode - * @param {object} options - The plugin options. - */ -/** - * @method IPlugin#beforeLayout - * @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} args - The call arguments. - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart layout. - */ -/** - * @method IPlugin#afterLayout - * @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} args - The call arguments. - * @param {object} options - The plugin options. - */ -/** - * @method IPlugin#beforeRender - * @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} args - The call arguments. - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart rendering. - */ -/** - * @method IPlugin#afterRender - * @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} args - The call arguments. - * @param {object} options - The plugin options. - */ -/** - * @method IPlugin#beforeDraw - * @desc Called before drawing `chart` at every animation frame. If any plugin returns `false`, - * the frame drawing is cancelled until another `render` is triggered. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart drawing. - */ -/** - * @method IPlugin#afterDraw - * @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} args - The call arguments. - * @param {object} options - The plugin options. - */ -/** - * @method IPlugin#beforeDatasetsDraw - * @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} args - The call arguments. - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart datasets drawing. - */ -/** - * @method IPlugin#afterDatasetsDraw - * @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} args - The call arguments. - * @param {object} options - The plugin options. - */ -/** - * @method IPlugin#beforeDatasetDraw - * @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. - */ -/** - * @method IPlugin#afterDatasetDraw - * @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. - */ -/** - * @method IPlugin#beforeTooltipDraw - * @desc Called before drawing the `tooltip`. If any plugin returns `false`, - * the tooltip drawing is cancelled until another `render` is triggered. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {Tooltip} args.tooltip - The tooltip. - * @param {object} options - The plugin options. - * @returns {boolean} `false` to cancel the chart tooltip drawing. - */ -/** - * @method IPlugin#afterTooltipDraw - * @desc Called after drawing the `tooltip`. Note that this hook will not - * be called if the tooltip drawing has been previously cancelled. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {Tooltip} args.tooltip - The tooltip. - * @param {object} options - The plugin options. - */ -/** - * @method IPlugin#beforeEvent - * @desc Called before processing the specified `event`. If any plugin returns `false`, - * the event will be discarded. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {ChartEvent} args.event - The event object. - * @param {boolean} args.replay - True if this event is replayed from `Chart.update` - * @param {object} options - The plugin options. - */ -/** - * @method IPlugin#afterEvent - * @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 {object} args - The call arguments. - * @param {ChartEvent} args.event - The event object. - * @param {boolean} args.replay - True if this event is replayed from `Chart.update` - * @param {object} options - The plugin options. - */ -/** - * @method IPlugin#resize - * @desc Called after the chart as been resized. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {number} args.size - The new canvas display size (eq. canvas.style width & height). - * @param {object} options - The plugin options. - */ -/** - * @method IPlugin#destroy - * @desc Called after the chart has been destroyed. - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {object} options - The plugin options. - */ -/** - * @method IPlugin#uninstall - * @desc Called after chart is destroyed on all plugins that were installed for that chart. This hook is called on disabled plugins (options === false). - * @param {Chart} chart - The chart instance. - * @param {object} args - The call arguments. - * @param {object} options - The plugin options. - * @since 3.0.0 - */
true
Other
chartjs
Chart.js
c1aeba1e67593d0cf1bd75b50fb2c7724f768cee.json
Add new scale hooks for plugins (#8112) * Add new scale hooks for plugins * Add notes * cc * cancelability
src/core/core.scale.js
@@ -649,18 +649,24 @@ export default class Scale extends Element { call(this.options.afterSetDimensions, [this]); } + _callHooks(name) { + const me = this; + me.chart.notifyPlugins(name, me.getContext()); + call(me.options[name], [me]); + } + // Data limits beforeDataLimits() { - call(this.options.beforeDataLimits, [this]); + this._callHooks('beforeDataLimits'); } determineDataLimits() {} afterDataLimits() { - call(this.options.afterDataLimits, [this]); + this._callHooks('afterDataLimits'); } // beforeBuildTicks() { - call(this.options.beforeBuildTicks, [this]); + this._callHooks('beforeBuildTicks'); } /** * @return {object[]} the ticks @@ -669,7 +675,7 @@ export default class Scale extends Element { return []; } afterBuildTicks() { - call(this.options.afterBuildTicks, [this]); + this._callHooks('afterBuildTicks'); } beforeTickToLabelConversion() {
true
Other
chartjs
Chart.js
c1aeba1e67593d0cf1bd75b50fb2c7724f768cee.json
Add new scale hooks for plugins (#8112) * Add new scale hooks for plugins * Add notes * cc * cancelability
test/specs/core.controller.tests.js
@@ -1396,6 +1396,14 @@ describe('Chart', function() { update: [ 'beforeUpdate', 'beforeLayout', + 'beforeDataLimits', + 'afterDataLimits', + 'beforeBuildTicks', + 'afterBuildTicks', + 'beforeDataLimits', + 'afterDataLimits', + 'beforeBuildTicks', + 'afterBuildTicks', 'afterLayout', 'beforeDatasetsUpdate', 'beforeDatasetUpdate',
true
Other
chartjs
Chart.js
c1aeba1e67593d0cf1bd75b50fb2c7724f768cee.json
Add new scale hooks for plugins (#8112) * Add new scale hooks for plugins * Add notes * cc * cancelability
test/specs/core.plugin.tests.js
@@ -151,7 +151,7 @@ describe('Chart.plugins', function() { spyOn(plugin, 'hook').and.callThrough(); }); - var ret = chart.notifyPlugins('hook'); + var ret = chart.notifyPlugins('hook', {cancelable: true}); expect(ret).toBeFalsy(); expect(plugins[0].hook).toHaveBeenCalled(); expect(plugins[1].hook).toHaveBeenCalled();
true
Other
chartjs
Chart.js
c1aeba1e67593d0cf1bd75b50fb2c7724f768cee.json
Add new scale hooks for plugins (#8112) * Add new scale hooks for plugins * Add notes * cc * cancelability
types/core/index.d.ts
@@ -597,14 +597,14 @@ export interface Plugin<O = {}> { * @param {object} args - The call arguments. * @param {object} options - The plugin options. */ - beforeInit?(chart: Chart, args: {}, options: O): boolean | void; + beforeInit?(chart: Chart, args: {}, options: O): void; /** * @desc Called after `chart` has been initialized and before the first update. * @param {Chart} chart - The chart instance. * @param {object} args - The call arguments. * @param {object} options - The plugin options. */ - afterInit?(chart: Chart, args: {}, options: O): boolean | void; + afterInit?(chart: Chart, args: {}, 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. @@ -623,7 +623,7 @@ export interface Plugin<O = {}> { * @param {UpdateMode} args.mode - The update mode * @param {object} options - The plugin options. */ - afterUpdate?(chart: Chart, args: { mode: UpdateMode }, options: O): boolean | void; + afterUpdate?(chart: Chart, args: { mode: UpdateMode }, options: O): void; /** * @desc Called during chart reset * @param {Chart} chart - The chart instance. @@ -652,7 +652,7 @@ export interface Plugin<O = {}> { * @param {object} options - The plugin options. * @since version 2.1.5 */ - afterDatasetsUpdate?(chart: Chart, args: { mode: UpdateMode }, options: O): boolean | void; + 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. @@ -675,7 +675,7 @@ export interface Plugin<O = {}> { * @param {UpdateMode} args.mode - The update mode. * @param {object} options - The plugin options. */ - afterDatasetUpdate?(chart: Chart, args: { index: number; meta: ChartMeta, mode: UpdateMode }, options: O): boolean | void; + afterDatasetUpdate?(chart: Chart, args: { index: number; meta: ChartMeta, 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. @@ -685,14 +685,46 @@ export interface Plugin<O = {}> { * @returns {boolean} `false` to cancel the chart layout. */ beforeLayout?(chart: Chart, args: {}, options: O): boolean | void; + /** + * @desc Called before scale data limits are calculated. This hook is called separately for each scale in the chart. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {Scale} args.scale - The scale. + * @param {object} options - The plugin options. + */ + beforeDataLimits?(chart: Chart, args: { scale: Scale }, options: O): void; + /** + * @desc Called after scale data limits are calculated. This hook is called separately for each scale in the chart. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {Scale} args.scale - The scale. + * @param {object} options - The plugin options. + */ + afterDataLimits?(chart: Chart, args: { scale: Scale }, options: O): void; + /** + * @desc Called before scale bulds its ticks. This hook is called separately for each scale in the chart. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {Scale} args.scale - The scale. + * @param {object} options - The plugin options. + */ + beforeBuildTicks?(chart: Chart, args: { scale: Scale }, options: O): void; + /** + * @desc Called after scale has build its ticks. This hook is called separately for each scale in the chart. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {Scale} args.scale - The scale. + * @param {object} options - The plugin options. + */ + afterBuildTicks?(chart: Chart, args: { scale: Scale }, options: O): 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} args - The call arguments. * @param {object} options - The plugin options. */ - afterLayout?(chart: Chart, args: {}, options: O): boolean | void; + afterLayout?(chart: Chart, args: {}, options: O): void; /** * @desc Called before rendering `chart`. If any plugin returns `false`, * the rendering is cancelled until another `render` is triggered. @@ -709,7 +741,7 @@ export interface Plugin<O = {}> { * @param {object} args - The call arguments. * @param {object} options - The plugin options. */ - afterRender?(chart: Chart, args: {}, options: O): boolean | void; + afterRender?(chart: Chart, args: {}, 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. @@ -726,7 +758,7 @@ export interface Plugin<O = {}> { * @param {object} args - The call arguments. * @param {object} options - The plugin options. */ - afterDraw?(chart: Chart, args: {}, options: O): boolean | void; + afterDraw?(chart: Chart, args: {}, 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. @@ -743,7 +775,7 @@ export interface Plugin<O = {}> { * @param {object} args - The call arguments. * @param {object} options - The plugin options. */ - afterDatasetsDraw?(chart: Chart, args: {}, options: O): boolean | void; + afterDatasetsDraw?(chart: Chart, args: {}, 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 @@ -766,7 +798,7 @@ export interface Plugin<O = {}> { * @param {object} args.meta - The dataset metadata. * @param {object} options - The plugin options. */ - afterDatasetDraw?(chart: Chart, args: { index: number; meta: ChartMeta }, options: O): boolean | void; + afterDatasetDraw?(chart: Chart, args: { index: number; meta: ChartMeta }, options: O): void; /** * @desc Called before processing the specified `event`. If any plugin returns `false`, * the event will be discarded. @@ -786,22 +818,22 @@ export interface Plugin<O = {}> { * @param {boolean} replay - True if this event is replayed from `Chart.update` * @param {object} options - The plugin options. */ - afterEvent?(chart: Chart, args: { event: ChartEvent, replay: boolean }, options: O): boolean | void; + afterEvent?(chart: Chart, args: { event: ChartEvent, replay: boolean }, options: O): void; /** * @desc Called after the chart as been resized. * @param {Chart} chart - The chart instance. * @param {object} args - The call arguments. * @param {number} args.size - The new canvas display size (eq. canvas.style width & height). * @param {object} options - The plugin options. */ - resize?(chart: Chart, args: { size: { width: number, height: number } }, options: O): boolean | void; + resize?(chart: Chart, args: { size: { width: number, height: number } }, options: O): void; /** * Called after the chart has been destroyed. * @param {Chart} chart - The chart instance. * @param {object} args - The call arguments. * @param {object} options - The plugin options. */ - destroy?(chart: Chart, args: {}, options: O): boolean | void; + destroy?(chart: Chart, args: {}, options: O): void; /** * Called after chart is destroyed on all plugins that were installed for that chart. This hook is also invoked for disabled plugins (options === false). * @param {Chart} chart - The chart instance.
true
Other
chartjs
Chart.js
6814b79b65afeeab09d3f03151ec0458be10686f.json
Fix CategoryScale.getValueForPixel with autoSkip (#8101)
src/scales/scale.category.js
@@ -111,8 +111,7 @@ export default class CategoryScale extends Scale { getValueForPixel(pixel) { const me = this; - const value = Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange); - return Math.min(Math.max(value, 0), me.ticks.length - 1); + return Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange); } getBasePixel() {
true
Other
chartjs
Chart.js
6814b79b65afeeab09d3f03151ec0458be10686f.json
Fix CategoryScale.getValueForPixel with autoSkip (#8101)
test/specs/scale.category.tests.js
@@ -476,6 +476,35 @@ describe('Category scale tests', function() { expect(yScale.getPixelForValue(4)).toBeCloseToPixel(538); }); + it('Should be consistent on pixels and values with autoSkipped ticks', function() { + var labels = []; + for (let i = 0; i < 50; i++) { + labels.push('very long label ' + i); + } + var chart = window.acquireChart({ + type: 'bar', + data: { + labels, + datasets: [{ + data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + }] + } + }); + + var scale = chart.scales.x; + expect(scale.ticks.length).toBeLessThan(50); + + let x = 0; + for (let i = 0; i < 50; i++) { + var x2 = scale.getPixelForValue(labels[i]); + var x3 = scale.getPixelForValue(i); + expect(x2).toEqual(x3); + expect(x2).toBeGreaterThan(x); + expect(scale.getValueForPixel(x2)).toBe(i); + x = x2; + } + }); + it('Should bound to ticks/data', function() { var chart = window.acquireChart({ type: 'line',
true
Other
chartjs
Chart.js
78dbeea1f0f09e2681ec3de55bbebb2f0ba71565.json
Add new hooks for plugins (#8103) * Notify beforeUpdate on disabled plugins cc? cc2 cc3 typo * init, unInit, enabled, disabled self review :) update the new hook signatures to unified merge error * Review update * start/stop, cc * types, jsdoc * stop between destroy and uninstall
docs/docs/getting-started/v3-migration.md
@@ -499,3 +499,4 @@ All helpers are now exposed in a flat hierarchy, e.g., `Chart.helpers.canvas.cli * `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 `event` property of the second argument. The native event is available via `args.event.native`. * Initial `resize` is no longer silent. Meaning that `resize` event can fire between `beforeInit` and `afterInit` +* New hooks: `install`, `start`, `stop`, and `uninstall`
true
Other
chartjs
Chart.js
78dbeea1f0f09e2681ec3de55bbebb2f0ba71565.json
Add new hooks for plugins (#8103) * Notify beforeUpdate on disabled plugins cc? cc2 cc3 typo * init, unInit, enabled, disabled self review :) update the new hook signatures to unified merge error * Review update * start/stop, cc * types, jsdoc * stop between destroy and uninstall
src/core/core.plugins.js
@@ -1,6 +1,6 @@ import defaults from './core.defaults'; import registry from './core.registry'; -import {mergeIf, valueOrDefault} from '../helpers/helpers.core'; +import {callback as callCallback, mergeIf, valueOrDefault} from '../helpers/helpers.core'; /** * @typedef { import("./core.controller").default } Chart @@ -9,6 +9,10 @@ import {mergeIf, valueOrDefault} from '../helpers/helpers.core'; */ export default class PluginService { + constructor() { + this._init = []; + } + /** * 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 @@ -19,25 +23,42 @@ export default class PluginService { * @returns {boolean} false if any of the plugins return false, else returns true. */ notify(chart, hook, args) { - args = args || {}; - const descriptors = this._descriptors(chart); + const me = this; - for (let i = 0; i < descriptors.length; ++i) { - const descriptor = descriptors[i]; + if (hook === 'beforeInit') { + me._init = me._createDescriptors(chart, true); + me._notify(me._init, chart, 'install'); + } + + const descriptors = me._descriptors(chart); + const result = me._notify(descriptors, chart, hook, args); + + if (hook === 'destroy') { + me._notify(descriptors, chart, 'stop'); + me._notify(me._init, chart, 'uninstall'); + } + return result; + } + + /** + * @private + */ + _notify(descriptors, chart, hook, args) { + args = args || {}; + for (const descriptor of descriptors) { const plugin = descriptor.plugin; const method = plugin[hook]; - if (typeof method === 'function') { - const params = [chart, args, descriptor.options]; - if (method.apply(plugin, params) === false) { - return false; - } + const params = [chart, args, descriptor.options]; + if (callCallback(method, params, plugin) === false) { + return false; } } return true; } invalidate() { + this._oldCache = this._cache; this._cache = undefined; } @@ -50,15 +71,31 @@ export default class PluginService { return this._cache; } + const descriptors = this._cache = this._createDescriptors(chart); + + this._notifyStateChanges(chart); + + return descriptors; + } + + _createDescriptors(chart, all) { const config = chart && chart.config; const options = valueOrDefault(config.options && config.options.plugins, {}); const plugins = allPlugins(config); // options === false => all plugins are disabled - const descriptors = options === false ? [] : createDescriptors(plugins, options); - - this._cache = descriptors; + return options === false && !all ? [] : createDescriptors(plugins, options, all); + } - return descriptors; + /** + * @param {Chart} chart + * @private + */ + _notifyStateChanges(chart) { + const previousDescriptors = this._oldCache || []; + const descriptors = this._cache; + const diff = (a, b) => a.filter(x => !b.some(y => x.plugin.id === y.plugin.id)); + this._notify(diff(previousDescriptors, descriptors), chart, 'stop'); + this._notify(diff(descriptors, previousDescriptors), chart, 'start'); } } @@ -84,20 +121,26 @@ function allPlugins(config) { return plugins; } -function createDescriptors(plugins, options) { +function getOpts(options, all) { + if (!all && options === false) { + return null; + } + if (options === true) { + return {}; + } + return options; +} + +function createDescriptors(plugins, options, all) { const result = []; for (let i = 0; i < plugins.length; i++) { const plugin = plugins[i]; const id = plugin.id; - - let opts = options[id]; - if (opts === false) { + const opts = getOpts(options[id], all); + if (opts === null) { continue; } - if (opts === true) { - opts = {}; - } result.push({ plugin, options: mergeIf({}, [opts, defaults.plugins[id]]) @@ -113,6 +156,30 @@ function createDescriptors(plugins, options) { * @typedef {object} IPlugin * @since 2.1.0 */ +/** + * @method IPlugin#install + * @desc Called when plugin is installed for this chart instance. This hook is called on disabled plugins (options === false). + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @since 3.0.0 + */ +/** + * @method IPlugin#start + * @desc Called when a plugin is starting. This happens when chart is created or plugin is enabled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @since 3.0.0 + */ +/** + * @method IPlugin#stop + * @desc Called when a plugin stopping. This happens when chart is destroyed or plugin is disabled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @since 3.0.0 + */ /** * @method IPlugin#beforeInit * @desc Called before initializing `chart`. @@ -338,8 +405,16 @@ function createDescriptors(plugins, options) { */ /** * @method IPlugin#destroy - * @desc Called after the chart as been destroyed. + * @desc Called after the chart has been destroyed. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + */ +/** + * @method IPlugin#uninstall + * @desc Called after chart is destroyed on all plugins that were installed for that chart. This hook is called on disabled plugins (options === false). * @param {Chart} chart - The chart instance. * @param {object} args - The call arguments. * @param {object} options - The plugin options. + * @since 3.0.0 */
true
Other
chartjs
Chart.js
78dbeea1f0f09e2681ec3de55bbebb2f0ba71565.json
Add new hooks for plugins (#8103) * Notify beforeUpdate on disabled plugins cc? cc2 cc3 typo * init, unInit, enabled, disabled self review :) update the new hook signatures to unified merge error * Review update * start/stop, cc * types, jsdoc * stop between destroy and uninstall
src/plugins/plugin.legend.js
@@ -653,12 +653,14 @@ export default { */ _element: Legend, - beforeInit(chart) { + start(chart) { const legendOpts = resolveOptions(chart.options.plugins.legend); + createNewLegendAndAttach(chart, legendOpts); + }, - if (legendOpts) { - createNewLegendAndAttach(chart, legendOpts); - } + stop(chart) { + layouts.removeBox(chart, chart.legend); + delete chart.legend; }, // During the beforeUpdate step, the layout configuration needs to run
true
Other
chartjs
Chart.js
78dbeea1f0f09e2681ec3de55bbebb2f0ba71565.json
Add new hooks for plugins (#8103) * Notify beforeUpdate on disabled plugins cc? cc2 cc3 typo * init, unInit, enabled, disabled self review :) update the new hook signatures to unified merge error * Review update * start/stop, cc * types, jsdoc * stop between destroy and uninstall
src/plugins/plugin.title.js
@@ -184,11 +184,17 @@ export default { */ _element: Title, - beforeInit(chart, options) { + start(chart, _args, options) { createTitle(chart, options); }, - beforeUpdate(chart, args, options) { + stop(chart) { + const titleBlock = chart.titleBlock; + layouts.removeBox(chart, titleBlock); + delete chart.titleBlock; + }, + + beforeUpdate(chart, _args, options) { if (options === false) { removeTitle(chart); } else {
true
Other
chartjs
Chart.js
78dbeea1f0f09e2681ec3de55bbebb2f0ba71565.json
Add new hooks for plugins (#8103) * Notify beforeUpdate on disabled plugins cc? cc2 cc3 typo * init, unInit, enabled, disabled self review :) update the new hook signatures to unified merge error * Review update * start/stop, cc * types, jsdoc * stop between destroy and uninstall
test/specs/core.controller.tests.js
@@ -1383,44 +1383,49 @@ describe('Chart', function() { }); describe('plugin.extensions', function() { + var hooks = { + install: ['install'], + uninstall: ['uninstall'], + init: [ + 'beforeInit', + 'resize', + 'afterInit' + ], + start: ['start'], + stop: ['stop'], + update: [ + 'beforeUpdate', + 'beforeLayout', + 'afterLayout', + 'beforeDatasetsUpdate', + 'beforeDatasetUpdate', + 'afterDatasetUpdate', + 'afterDatasetsUpdate', + 'afterUpdate', + ], + render: [ + 'beforeRender', + 'beforeDraw', + 'beforeDatasetsDraw', + 'beforeDatasetDraw', + 'afterDatasetDraw', + 'afterDatasetsDraw', + 'beforeTooltipDraw', + 'afterTooltipDraw', + 'afterDraw', + 'afterRender', + ], + resize: [ + 'resize' + ], + destroy: [ + 'destroy' + ] + }; + it ('should notify plugin in correct order', function(done) { var plugin = this.plugin = {}; var sequence = []; - var hooks = { - init: [ - 'beforeInit', - 'resize', - 'afterInit' - ], - update: [ - 'beforeUpdate', - 'beforeLayout', - 'afterLayout', - 'beforeDatasetsUpdate', - 'beforeDatasetUpdate', - 'afterDatasetUpdate', - 'afterDatasetsUpdate', - 'afterUpdate', - ], - render: [ - 'beforeRender', - 'beforeDraw', - 'beforeDatasetsDraw', - 'beforeDatasetDraw', - 'afterDatasetDraw', - 'afterDatasetsDraw', - 'beforeTooltipDraw', - 'afterTooltipDraw', - 'afterDraw', - 'afterRender', - ], - resize: [ - 'resize' - ], - destroy: [ - 'destroy' - ] - }; Object.keys(hooks).forEach(function(group) { hooks[group].forEach(function(name) { @@ -1447,20 +1452,73 @@ describe('Chart', function() { chart.destroy(); expect(sequence).toEqual([].concat( + hooks.install, + hooks.start, hooks.init, hooks.update, hooks.render, hooks.resize, hooks.update, hooks.render, - hooks.destroy + hooks.destroy, + hooks.stop, + hooks.uninstall )); done(); }); chart.canvas.parentNode.style.width = '400px'; }); + it ('should notify initially disabled plugin in correct order', function() { + var plugin = this.plugin = {id: 'plugin'}; + var sequence = []; + + Object.keys(hooks).forEach(function(group) { + hooks[group].forEach(function(name) { + plugin[name] = function() { + sequence.push(name); + }; + }); + }); + + var chart = window.acquireChart({ + type: 'line', + data: {datasets: [{}]}, + plugins: [plugin], + options: { + plugins: { + plugin: false + } + } + }); + + expect(sequence).toEqual([].concat( + hooks.install + )); + + sequence = []; + chart.options.plugins.plugin = true; + chart.update(); + + expect(sequence).toEqual([].concat( + hooks.start, + hooks.update, + hooks.render + )); + + sequence = []; + chart.options.plugins.plugin = false; + chart.update(); + + expect(sequence).toEqual(hooks.stop); + + sequence = []; + chart.destroy(); + + expect(sequence).toEqual(hooks.uninstall); + }); + it('should not notify before/afterDatasetDraw if dataset is hidden', function() { var sequence = []; var plugin = this.plugin = {
true
Other
chartjs
Chart.js
78dbeea1f0f09e2681ec3de55bbebb2f0ba71565.json
Add new hooks for plugins (#8103) * Notify beforeUpdate on disabled plugins cc? cc2 cc3 typo * init, unInit, enabled, disabled self review :) update the new hook signatures to unified merge error * Review update * start/stop, cc * types, jsdoc * stop between destroy and uninstall
test/specs/plugin.legend.tests.js
@@ -760,7 +760,7 @@ describe('Legend block tests', function() { expect(chart.legend.weight).toBe(42); }); - xit ('should remove the legend if the new options are false', function() { + it ('should remove the legend if the new options are false', function() { var chart = acquireChart({ type: 'line', data: {
true
Other
chartjs
Chart.js
78dbeea1f0f09e2681ec3de55bbebb2f0ba71565.json
Add new hooks for plugins (#8103) * Notify beforeUpdate on disabled plugins cc? cc2 cc3 typo * init, unInit, enabled, disabled self review :) update the new hook signatures to unified merge error * Review update * start/stop, cc * types, jsdoc * stop between destroy and uninstall
test/specs/plugin.title.tests.js
@@ -295,7 +295,7 @@ describe('Title block tests', function() { expect(chart.titleBlock.weight).toBe(42); }); - xit ('should remove the title if the new options are false', function() { + it ('should remove the title if the new options are false', function() { var chart = acquireChart({ type: 'line', data: {
true
Other
chartjs
Chart.js
78dbeea1f0f09e2681ec3de55bbebb2f0ba71565.json
Add new hooks for plugins (#8103) * Notify beforeUpdate on disabled plugins cc? cc2 cc3 typo * init, unInit, enabled, disabled self review :) update the new hook signatures to unified merge error * Review update * start/stop, cc * types, jsdoc * stop between destroy and uninstall
types/core/index.d.ts
@@ -567,6 +567,30 @@ export const layouts: { export interface Plugin<O = {}> { id: string; + /** + * @desc Called when plugin is installed for this chart instance. This hook is also invoked for disabled plugins (options === false). + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @since 3.0.0 + */ + install?(chart: Chart, args: {}, options: O): void; + /** + * @desc Called when a plugin is starting. This happens when chart is created or plugin is enabled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @since 3.0.0 + */ + start?(chart: Chart, args: {}, options: O): void; + /** + * @desc Called when a plugin stopping. This happens when chart is destroyed or plugin is disabled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @since 3.0.0 + */ + stop?(chart: Chart, args: {}, options: O): void; /** * @desc Called before initializing `chart`. * @param {Chart} chart - The chart instance. @@ -772,11 +796,20 @@ export interface Plugin<O = {}> { */ resize?(chart: Chart, args: { size: { width: number, height: number } }, options: O): boolean | void; /** - * Called after the chart as been destroyed. + * Called after the chart has been destroyed. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + */ + destroy?(chart: Chart, args: {}, options: O): boolean | void; + /** + * Called after chart is destroyed on all plugins that were installed for that chart. This hook is also invoked for disabled plugins (options === false). * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. * @param {object} options - The plugin options. + * @since 3.0.0 */ - destroy?(chart: Chart, options: O): boolean | void; + uninstall?(chart: Chart, args: {}, options: O): void; } export declare type ChartComponentLike = ChartComponent | ChartComponent[] | { [key: string]: ChartComponent };
true
Other
chartjs
Chart.js
f0148738644244fccd362abd2492a2244e8b2d08.json
fix color type & add background and border color (#8110)
types/core/interfaces.d.ts
@@ -99,7 +99,17 @@ export interface CoreChartOptions extends ParsingOptions { * base color * @see Defaults.color */ - color: string; + color: Color; + /** + * base background color + * @see Defaults.backgroundColor + */ + backgroundColor: Color; + /** + * base border color + * @see Defaults.borderColor + */ + borderColor: Color; /** * base font * @see Defaults.font
false
Other
chartjs
Chart.js
c5dcf5a20d0f86015491766b3c581e182c878d16.json
Update chart extension docs + add samples (#8540) * Update docs on chart extensions * Working sample for derived chart types * Add derived axis example * Remove duplicated line
docs/docs/developers/charts.md
@@ -26,17 +26,21 @@ Dataset controllers must implement the following interface. ```javascript { - // Create elements for each piece of data in the dataset. Store elements in an array on the dataset as dataset.metaData - addElements: function() {}, - - // Draw the representation of the dataset - draw: function() {}, - - // Remove hover styling from the given element - removeHoverStyle: function(element, datasetIndex, index) {}, + // Defaults for charts of this type + defaults: { + // If set to `false` or `null`, no dataset level element is created. + // If set to a string, this is the type of element to create for the dataset. + // For example, a line create needs to create a line element so this is the string 'line' + datasetElementType: string | null | false, + + // If set to `false` or `null`, no elements are created for each data value. + // If set to a string, this is the type of element to create for each data value. + // For example, a line create needs to create a point element so this is the string 'point' + dataElementType: string | null | false, + } - // Add hover styling to the given element - setHoverStyle: function(element, datasetIndex, index) {}, + // ID of the controller + id: string; // Update the elements in response to new data // @param mode : update mode, core calls this method using any of `'active'`, `'hide'`, `'reset'`, `'resize'`, `'show'` or `undefined` @@ -48,15 +52,20 @@ The following methods may optionally be overridden by derived dataset controller ```javascript { + // Draw the representation of the dataset. The base implementation works in most cases, and an example of a derived version + // can be found in the line controller + draw: function() {}, + // Initializes the controller initialize: function() {}, // Ensures that the dataset represented by this controller is linked to a scale. Overridden to helpers.noop in the polar area and doughnut controllers as these // chart types using a single scale linkScales: function() {}, - // Called by the main chart controller when an update is triggered. The default implementation handles the number of data points changing and creating elements appropriately. - buildOrUpdateElements: function() {} + // Parse the data into the controller meta data. The default implementation will work for cartesian parsing, but an example of an overridden + // version can be found in the doughnut controller + parse: function(start, count) {}, } ``` @@ -83,19 +92,21 @@ For example, to derive a new chart type that extends from a bubble chart, you wo import {BubbleController} from 'chart.js'; class Custom extends BubbleController { draw() { - // Call super method first + // Call bubble controller method to draw all the points super.draw(arguments); // Now we can do some custom drawing for this dataset. Here we'll draw a red box around the first point in each dataset - var meta = this.getMeta(); - var pt0 = meta.data[0]; - var radius = pt0.radius; + const meta = this.getMeta(); + const pt0 = meta.data[0]; + + const {x, y} = pt0.getProps(['x', 'y']); + const {radius} = pt0.options; - var ctx = this.chart.chart.ctx; + const ctx = this.chart.ctx; ctx.save(); ctx.strokeStyle = 'red'; ctx.lineWidth = 1; - ctx.strokeRect(pt0.x - radius, pt0.y - radius, 2 * radius, 2 * radius); + ctx.strokeRect(x - radius, y - radius, 2 * radius, 2 * radius); ctx.restore(); } });
true
Other
chartjs
Chart.js
c5dcf5a20d0f86015491766b3c581e182c878d16.json
Update chart extension docs + add samples (#8540) * Update docs on chart extensions * Working sample for derived chart types * Add derived axis example * Remove duplicated line
samples/advanced/derived-axis-type.html
@@ -0,0 +1,136 @@ +<!doctype html> +<html> + +<head> + <title>Logarithmic Line Chart</title> + <script src="../../dist/chart.min.js"></script> + <script src="../utils.js"></script> + <style> + canvas { + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; + } + </style> +</head> + +<body> + <div style="width:75%;"> + <canvas id="canvas"></canvas> + </div> + <script> + var randomScalingFactor = function() { + return Math.pow(2, Math.ceil(Math.random() * 10)); + }; + + class Log2Axis extends Chart.Scale { + constructor(cfg) { + super(cfg); + this._startValue = undefined; + this._valueRange = 0; + } + + parse(raw, index) { + const value = Chart.registry.getScale('linear').prototype.parse.apply(this, [raw, index]); + return isFinite(value) && value > 0 ? value : null; + } + + determineDataLimits() { + const {min, max} = this.getMinMax(true); + this.min = isFinite(min) ? Math.max(0, min) : null; + this.max = isFinite(max) ? Math.max(0, max) : null; + } + + buildTicks() { + const ticks = []; + + let power = Math.floor(Math.log2(this.min)); + let maxPower = Math.ceil(Math.log2(this.max)); + while (power <= maxPower) { + ticks.push({value: Math.pow(2, power)}); + power += 1; + } + + this.min = ticks[0].value; + this.max = ticks[ticks.length - 1].value; + return ticks; + } + + /** + * @protected + */ + configure() { + const start = this.min; + + super.configure(); + + this._startValue = Math.log2(start); + this._valueRange = Math.log2(this.max) - Math.log2(start); + } + + getPixelForValue(value) { + if (value === undefined || value === 0) { + value = this.min; + } + + return this.getPixelForDecimal(value === this.min ? 0 : (Math.log2(value) - this._startValue) / this._valueRange); + } + + getValueForPixel(pixel) { + const decimal = this.getDecimalForPixel(pixel); + return Math.pow(2, this._startValue + decimal * this._valueRange); + } + } + + Log2Axis.id = 'log2'; + Log2Axis.defaults = {}; + Chart.register(Log2Axis); + + var config = { + type: 'line', + data: { + labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], + datasets: [{ + label: 'My First dataset', + backgroundColor: window.chartColors.red, + borderColor: window.chartColors.red, + fill: false, + data: [ + randomScalingFactor(), + randomScalingFactor(), + randomScalingFactor(), + randomScalingFactor(), + randomScalingFactor(), + randomScalingFactor(), + randomScalingFactor() + ], + }] + }, + options: { + responsive: true, + plugins: { + title: { + display: true, + text: 'Derived Axis Type - Log2' + } + }, + scales: { + x: { + display: true, + }, + y: { + display: true, + type: 'log2', + } + } + } + }; + + window.onload = function() { + var ctx = document.getElementById('canvas').getContext('2d'); + window.myLine = new Chart(ctx, config); + }; + </script> +</body> + +</html>
true
Other
chartjs
Chart.js
c5dcf5a20d0f86015491766b3c581e182c878d16.json
Update chart extension docs + add samples (#8540) * Update docs on chart extensions * Working sample for derived chart types * Add derived axis example * Remove duplicated line
samples/advanced/derived-chart-type.html
@@ -0,0 +1,106 @@ +<!doctype html> +<html> + +<head> + <title>Derived Chart Type</title> + <script src="../../dist/chart.min.js"></script> + <script src="../utils.js"></script> + <style type="text/css"> + canvas{ + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; + } + </style> +</head> + +<body> + <div id="container" style="width: 75%;"> + <canvas id="canvas"></canvas> + </div> + <script> + class Custom extends Chart.controllers.bubble { + draw() { + // Call bubble controller method to draw all the points + super.draw(arguments); + + // Now we can do some custom drawing for this dataset. Here we'll draw a red box around the first point in each dataset + var meta = this.getMeta(); + var pt0 = meta.data[0]; + + const {x, y} = pt0.getProps(['x', 'y']); + const {radius} = pt0.options; + + var ctx = this.chart.ctx; + ctx.save(); + ctx.strokeStyle = 'red'; + ctx.lineWidth = 1; + ctx.strokeRect(x - radius, y - radius, 2 * radius, 2 * radius); + ctx.restore(); + } + } + Custom.id = 'derivedBubble'; + Custom.defaults = Chart.controllers.bubble.defaults; + + // Stores the controller so that the chart initialization routine can look it up + Chart.register(Custom); + + var color = Chart.helpers.color; + var bubbleChartData = { + datasets: [{ + label: 'My First dataset', + backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(), + borderColor: window.chartColors.blue, + borderWidth: 1, + data: [{ + x: randomScalingFactor(), + y: randomScalingFactor(), + r: Math.abs(randomScalingFactor()) / 5, + }, { + x: randomScalingFactor(), + y: randomScalingFactor(), + r: Math.abs(randomScalingFactor()) / 5, + }, { + x: randomScalingFactor(), + y: randomScalingFactor(), + r: Math.abs(randomScalingFactor()) / 5, + }, { + x: randomScalingFactor(), + y: randomScalingFactor(), + r: Math.abs(randomScalingFactor()) / 5, + }, { + x: randomScalingFactor(), + y: randomScalingFactor(), + r: Math.abs(randomScalingFactor()) / 5, + }, { + x: randomScalingFactor(), + y: randomScalingFactor(), + r: Math.abs(randomScalingFactor()) / 5, + }, { + x: randomScalingFactor(), + y: randomScalingFactor(), + r: Math.abs(randomScalingFactor()) / 5, + }] + }] + }; + + window.onload = function() { + var ctx = document.getElementById('canvas').getContext('2d'); + window.myChart = new Chart(ctx, { + type: 'derivedBubble', + data: bubbleChartData, + options: { + responsive: true, + plugins: { + title: { + display: true, + text: 'Derived Chart Type' + }, + } + } + }); + }; + </script> +</body> + +</html>
true
Other
chartjs
Chart.js
c5dcf5a20d0f86015491766b3c581e182c878d16.json
Update chart extension docs + add samples (#8540) * Update docs on chart extensions * Working sample for derived chart types * Add derived axis example * Remove duplicated line
samples/samples.js
@@ -268,6 +268,12 @@ }, { title: 'Programmatic Event Triggers', path: 'advanced/programmatic-events.html' + }, { + title: 'Derived Chart Type', + path: 'advanced/derived-chart-type.html' + }, { + title: 'Derived Axis Type', + path: 'advanced/derived-axis-type.html' }] }];
true
Other
chartjs
Chart.js
3460ef126e77c9a6ab83f5f03cdcc28e1aaeec84.json
Types: Add couple of tests, move utils to new file (#8526)
types/index.esm.d.ts
@@ -12,6 +12,8 @@ * } */ +import { DeepPartial, DistributiveArray } from './utils'; + import { TimeUnit } from './adapters'; import { AnimationEvent } from './animation'; import { AnyObject, EmptyObject } from './basic'; @@ -3085,21 +3087,6 @@ export const RadialLinearScale: ChartComponent & { new <O extends RadialLinearScaleOptions = RadialLinearScaleOptions>(cfg: AnyObject): RadialLinearScale<O>; }; -// DeepPartial implementation taken from the utility-types NPM package, which is -// Copyright (c) 2016 Piotr Witek <piotrek.witek@gmail.com> (http://piotrwitek.github.io) -// and used under the terms of the MIT license -export type DeepPartial<T> = T extends Function - ? T - : T extends Array<infer U> - ? _DeepPartialArray<U> - : T extends object - ? _DeepPartialObject<T> - : T | undefined; - type _DeepPartialArray<T> = Array<DeepPartial<T>> - type _DeepPartialObject<T> = { [P in keyof T]?: DeepPartial<T[P]> }; - -export type DistributiveArray<T> = T extends unknown ? T[] : never - export interface CartesianScaleTypeRegistry { linear: { options: LinearScaleOptions; @@ -3254,7 +3241,6 @@ export type DefaultDataPoint<TType extends ChartType> = DistributiveArray<ChartT export type ParsedDataType<TType extends ChartType = ChartType> = ChartTypeRegistry[TType]['parsedDataType']; - export interface ChartDatasetProperties<TType extends ChartType, TData> { type?: TType; data: TData;
true
Other
chartjs
Chart.js
3460ef126e77c9a6ab83f5f03cdcc28e1aaeec84.json
Types: Add couple of tests, move utils to new file (#8526)
types/tests/parsed.data.type.ts
@@ -0,0 +1,18 @@ +import { ParsedDataType } from '../index.esm'; + +interface test { + pie: ParsedDataType<'pie'>, + line: ParsedDataType<'line'>, + testA: ParsedDataType<'pie' | 'line' | 'bar'> + testB: ParsedDataType<'pie' | 'line' | 'bar'> + testC: ParsedDataType<'pie' | 'line' | 'bar'> +} + +export const testImpl: test = { + pie: 1, + line: { x: 1, y: 2 }, + testA: 1, + testB: { x: 1, y: 2 }, + // @ts-expect-error testC should be limited to pie/line datatypes + testC: 'test' +};
true
Other
chartjs
Chart.js
3460ef126e77c9a6ab83f5f03cdcc28e1aaeec84.json
Types: Add couple of tests, move utils to new file (#8526)
types/tests/scriptable.ts
@@ -0,0 +1,21 @@ +import { Scriptable } from '../index.esm'; + +interface test { + pie?: Scriptable<number, 'pie'>, + line?: Scriptable<number, 'line'>, + testA?: Scriptable<number, 'pie' | 'line' | 'bar'> + testB?: Scriptable<number, 'pie' | 'line' | 'bar'> + testC?: Scriptable<number, 'pie' | 'line' | 'bar'> +} + +const pieScriptable: Scriptable<number, 'pie'> = (ctx) => ctx.parsed; +const lineScriptable: Scriptable<number, 'line'> = (ctx) => ctx.parsed.x + ctx.parsed.y; + +export const testImpl: test = { + pie: (ctx) => ctx.parsed, + line: (ctx) => ctx.parsed.x + ctx.parsed.y, + testA: pieScriptable, + testB: lineScriptable, + // @FIXME ts-expect-error combined type should not be any + testC: (ctx) => ctx.fail +};
true
Other
chartjs
Chart.js
3460ef126e77c9a6ab83f5f03cdcc28e1aaeec84.json
Types: Add couple of tests, move utils to new file (#8526)
types/utils.d.ts
@@ -0,0 +1,15 @@ + +// DeepPartial implementation taken from the utility-types NPM package, which is +// Copyright (c) 2016 Piotr Witek <piotrek.witek@gmail.com> (http://piotrwitek.github.io) +// and used under the terms of the MIT license +export type DeepPartial<T> = T extends Function + ? T + : T extends Array<infer U> + ? _DeepPartialArray<U> + : T extends object + ? _DeepPartialObject<T> + : T | undefined; + type _DeepPartialArray<T> = Array<DeepPartial<T>> +type _DeepPartialObject<T> = { [P in keyof T]?: DeepPartial<T[P]> }; + +export type DistributiveArray<T> = T extends unknown ? T[] : never
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
docs/docs/charts/line.mdx
@@ -137,7 +137,7 @@ The style of the line can be controlled with the following properties: | `fill` | How to fill the area under the line. See [area charts](area.md). | `tension` | Bezier curve tension of the line. Set to 0 to draw straightlines. This option is ignored if monotone cubic interpolation is used. | `showLine` | If false, the line is not drawn for this dataset. -| `spanGaps` | If true, lines will be drawn between points with no or null data. If false, points with `NaN` data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used. +| `spanGaps` | If true, lines will be drawn between points with no or null data. If false, points with `null` data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used. If the value is `undefined`, `showLine` and `spanGaps` fallback to the associated [chart configuration options](#configuration-options). The rest of the values fallback to the associated [`elements.line.*`](../configuration/elements.md#line-configuration) options. @@ -184,7 +184,7 @@ The line chart defines the following configuration options. These options are me | Name | Type | Default | Description | ---- | ---- | ------- | ----------- | `showLine` | `boolean` | `true` | If false, the lines between points are not drawn. -| `spanGaps` | `boolean`\|`number` | `false` | If true, lines will be drawn between points with no or null data. If false, points with `NaN` data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used. +| `spanGaps` | `boolean`\|`number` | `false` | If true, lines will be drawn between points with no or null data. If false, points with `null` data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used. ## Default Options
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
docs/docs/charts/radar.mdx
@@ -149,7 +149,7 @@ The style of the line can be controlled with the following properties: | `borderWidth` | The line width (in pixels). | `fill` | How to fill the area under the line. See [area charts](area.md). | `tension` | Bezier curve tension of the line. Set to 0 to draw straight lines. -| `spanGaps` | If true, lines will be drawn between points with no or null data. If false, points with `NaN` data will create a break in the line. +| `spanGaps` | If true, lines will be drawn between points with no or null data. If false, points with `null` data will create a break in the line. If the value is `undefined`, `spanGaps` fallback to the associated [chart configuration options](#configuration-options). The rest of the values fallback to the associated [`elements.line.*`](../configuration/elements.md#line-configuration) options. @@ -170,7 +170,7 @@ The radar chart defines the following configuration options. These options are m | Name | Type | Default | Description | ---- | ---- | ------- | ----------- -| `spanGaps` | `boolean` | `false` | If false, NaN data causes a break in the line. +| `spanGaps` | `boolean` | `false` | If false, `null` data causes a break in the line. ## Scale Options
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
docs/docs/configuration/tooltip.md
@@ -139,7 +139,7 @@ var chart = new Chart(ctx, { if (label) { label += ': '; } - if (!isNaN(context.parsed.y)) { + if (context.parsed.y !== null) { label += new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(context.parsed.y); } return label;
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
docs/docs/developers/axes.md
@@ -132,13 +132,6 @@ The Core.Scale base class also has some utility functions that you may find usef // Returns true if the scale instance is horizontal isHorizontal: function() {}, - // Get the correct value from the value from this.chart.data.datasets[x].data[] - // If dataValue is an object, returns .x or .y depending on the return of isHorizontal() - // If the value is undefined, returns NaN - // Otherwise returns the value. - // Note that in all cases, the returned value is not guaranteed to be a number - getRightValue: function(dataValue) {}, - // Returns the scale tick objects ({label, major}) getTicks: function() {} }
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
docs/docs/general/data-structures.md
@@ -19,7 +19,7 @@ When the `data` is an array of numbers, values from `labels` array at the same i ## Object[] ```javascript -data: [{x: 10, y: 20}, {x: 15, y: 10}] +data: [{x: 10, y: 20}, {x: 15, y: null}, {x: 20, y: 10}] ``` ```javascript @@ -32,7 +32,7 @@ data: [{x:'Sales', y:20}, {x:'Revenue', y:10}] This is also the internal format used for parsed data. In this mode, parsing can be disabled by specifying `parsing: false` at chart options or dataset. If parsing is disabled, data must be sorted and in the formats the associated chart type and scales use internally. -The values provided must be parsable by the associated scales or in the internal format of the associated scales. A common mistake would be to provide integers for the `category` scale, which uses integers as an internal format, where each integer represents an index in the labels array. +The values provided must be parsable by the associated scales or in the internal format of the associated scales. A common mistake would be to provide integers for the `category` scale, which uses integers as an internal format, where each integer represents an index in the labels array. `null` can be used for skipped values. ## Object[] using custom properties
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
src/controllers/controller.bar.js
@@ -492,7 +492,7 @@ export default class BarController extends DatasetController { clipArea(chart.ctx, chart.chartArea); for (; i < ilen; ++i) { - if (!isNaN(me.getParsed(i)[vScale.axis])) { + if (me.getParsed(i)[vScale.axis] !== null) { rects[i].draw(me._ctx); } }
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
src/controllers/controller.doughnut.js
@@ -138,14 +138,17 @@ export default class DoughnutController extends DatasetController { } /** - * @private - */ + * @private + */ _circumference(i, reset) { const me = this; const opts = me.options; const meta = me._cachedMeta; const circumference = me._getCircumference(); - return reset && opts.animation.animateRotate ? 0 : this.chart.getDataVisibility(i) ? me.calculateCircumference(meta._parsed[i] * circumference / TAU) : 0; + if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null) { + return 0; + } + return me.calculateCircumference(meta._parsed[i] * circumference / TAU); } updateElements(arcs, start, count, mode) { @@ -200,7 +203,7 @@ export default class DoughnutController extends DatasetController { for (i = 0; i < metaData.length; i++) { const value = meta._parsed[i]; - if (!isNaN(value) && this.chart.getDataVisibility(i)) { + if (value !== null && this.chart.getDataVisibility(i)) { total += Math.abs(value); } }
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
src/core/core.datasetController.js
@@ -1,6 +1,6 @@ import Animations from './core.animations'; import defaults from './core.defaults'; -import {isObject, isArray, valueOrDefault, resolveObjectKey, defined} from '../helpers/helpers.core'; +import {isArray, isFinite, isObject, valueOrDefault, resolveObjectKey, defined} from '../helpers/helpers.core'; import {listenArrayEvents, unlistenArrayEvents} from '../helpers/helpers.collection'; import {sign} from '../helpers/helpers.math'; @@ -70,6 +70,10 @@ function applyStack(stack, value, dsIndex, allOther) { const keys = stack.keys; let i, ilen, datasetIndex, otherValue; + if (value === null) { + return; + } + for (i = 0, ilen = keys.length; i < ilen; ++i) { datasetIndex = +keys[i]; if (datasetIndex === dsIndex) { @@ -79,7 +83,7 @@ function applyStack(stack, value, dsIndex, allOther) { break; } otherValue = stack.values[datasetIndex]; - if (!isNaN(otherValue) && (value === 0 || sign(value) === sign(otherValue))) { + if (isFinite(otherValue) && (value === 0 || sign(value) === sign(otherValue))) { value += otherValue; } } @@ -393,7 +397,7 @@ export default class DatasetController { parsed = me.parsePrimitiveData(meta, data, start, count); } - const isNotInOrderComparedToPrev = () => isNaN(cur[iAxis]) || (prev && cur[iAxis] < prev[iAxis]); + const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]); for (i = 0; i < count; ++i) { meta._parsed[i + start] = cur = parsed[i]; if (sorted) { @@ -528,15 +532,16 @@ export default class DatasetController { * @protected */ updateRangeFromParsed(range, scale, parsed, stack) { - let value = parsed[scale.axis]; + const parsedValue = parsed[scale.axis]; + let value = parsedValue === null ? NaN : parsedValue; const values = stack && parsed._stacks[scale.axis]; if (stack && values) { stack.values = values; // Need to consider individual stack values for data range, // in addition to the stacked value range.min = Math.min(range.min, value); range.max = Math.max(range.max, value); - value = applyStack(stack, value, this._cachedMeta.index, true); + value = applyStack(stack, parsedValue, this._cachedMeta.index, true); } range.min = Math.min(range.min, value); range.max = Math.max(range.max, value); @@ -561,7 +566,7 @@ export default class DatasetController { parsed = _parsed[i]; value = parsed[scale.axis]; otherValue = parsed[otherScale.axis]; - return (isNaN(value) || isNaN(otherValue) || otherMin > otherValue || otherMax < otherValue); + return (!isFinite(value) || !isFinite(otherValue) || otherMin > otherValue || otherMax < otherValue); } for (i = 0; i < ilen; ++i) { @@ -594,7 +599,7 @@ export default class DatasetController { for (i = 0, ilen = parsed.length; i < ilen; ++i) { value = parsed[i][scale.axis]; - if (!isNaN(value)) { + if (isFinite(value)) { values.push(value); } }
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
src/scales/scale.linear.js
@@ -31,7 +31,7 @@ export default class LinearScale extends LinearScaleBase { // Utils getPixelForValue(value) { - return this.getPixelForDecimal((value - this._startValue) / this._valueRange); + return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange); } getValueForPixel(pixel) {
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
src/scales/scale.linearbase.js
@@ -115,10 +115,10 @@ export default class LinearScaleBase extends Scale { parse(raw, index) { // eslint-disable-line no-unused-vars if (isNullOrUndef(raw)) { - return NaN; + return null; } if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) { - return NaN; + return null; } return +raw;
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
src/scales/scale.logarithmic.js
@@ -64,7 +64,7 @@ export default class LogarithmicScale extends Scale { this._zero = true; return undefined; } - return isFinite(value) && value > 0 ? value : NaN; + return isFinite(value) && value > 0 ? value : null; } determineDataLimits() {
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
src/scales/scale.time.js
@@ -47,7 +47,7 @@ function sorter(a, b) { */ function parse(scale, input) { if (isNullOrUndef(input)) { - return NaN; + return null; } const adapter = scale._adapter; @@ -67,7 +67,7 @@ function parse(scale, input) { } if (value === null) { - return NaN; + return null; } if (round) { @@ -244,7 +244,7 @@ export default class TimeScale extends Scale { */ parse(raw, index) { // eslint-disable-line no-unused-vars if (raw === undefined) { - return NaN; + return null; } return parse(this, raw); } @@ -489,7 +489,7 @@ export default class TimeScale extends Scale { */ getDecimalForValue(value) { const me = this; - return (value - me.min) / (me.max - me.min); + return value === null ? NaN : (value - me.min) / (me.max - me.min); } /**
true
Other
chartjs
Chart.js
7c75310a0c048546591745840b0ece15b7868718.json
Use null for skipped values instead of NaN (#8510) * Use null for skipped values instead of NaN * Document skipped values when parsing is false * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * Update src/core/core.datasetController.js Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com> * fix lint issue * use isFinite * revert change checking for pixel values * ternary readability * revert accidental paren movement * test with parsing: false Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
test/fixtures/element.line/skip/middle-span.js
@@ -1,10 +1,11 @@ module.exports = { config: { type: 'line', + parsing: false, data: { datasets: [ { - data: [{x: 0, y: 10}, {x: 5, y: 0}, {x: NaN, y: -10}, {x: 19, y: -5}], + data: [{x: 0, y: 10}, {x: 5, y: 0}, {x: null, y: -10}, {x: 19, y: -5}], borderColor: 'red', fill: true, spanGaps: true,
true
Other
chartjs
Chart.js
12e9020ab7d842eca51e70f9153ba49dd180c9b8.json
Remove unused getRingIndex from Doughnut (#8521)
docs/docs/getting-started/v3-migration.md
@@ -303,6 +303,7 @@ The following properties and methods were removed: * `DatasetController.addElementAndReset` * `DatasetController.createMetaData` * `DatasetController.createMetaDataset` +* `DoughnutController.getRingIndex` #### Removed from Elements
true
Other
chartjs
Chart.js
12e9020ab7d842eca51e70f9153ba49dd180c9b8.json
Remove unused getRingIndex from Doughnut (#8521)
src/controllers/controller.doughnut.js
@@ -60,19 +60,6 @@ export default class DoughnutController extends DatasetController { } } - // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly - getRingIndex(datasetIndex) { - let ringIndex = 0; - - for (let j = 0; j < datasetIndex; ++j) { - if (this.chart.isDatasetVisible(j)) { - ++ringIndex; - } - } - - return ringIndex; - } - /** * @private */
true
Other
chartjs
Chart.js
12e9020ab7d842eca51e70f9153ba49dd180c9b8.json
Remove unused getRingIndex from Doughnut (#8521)
types/index.esm.d.ts
@@ -314,7 +314,6 @@ export interface DoughnutController extends DatasetController { readonly offsetX: number; readonly offsetY: number; - getRingIndex(datasetIndex: number): number; calculateTotal(): number; calculateCircumference(value: number): number; }
true
Other
chartjs
Chart.js
b31352c665ee41aeae538219dabb39ed18aa8ecc.json
Reduce duplication in PointElement (#8517)
src/elements/element.point.js
@@ -1,6 +1,13 @@ import Element from '../core/core.element'; import {drawPoint} from '../helpers/helpers.canvas'; +function inRange(el, pos, axis, useFinalPosition) { + const options = el.options; + const {[axis]: value} = el.getProps([axis], useFinalPosition); + + return (Math.abs(pos - value) < options.radius + options.hitRadius); +} + export default class PointElement extends Element { constructor(cfg) { @@ -22,16 +29,11 @@ export default class PointElement extends Element { } inXRange(mouseX, useFinalPosition) { - const options = this.options; - const {x} = this.getProps(['x'], useFinalPosition); - - return (Math.abs(mouseX - x) < options.radius + options.hitRadius); + return inRange(this, mouseX, 'x', useFinalPosition); } inYRange(mouseY, useFinalPosition) { - const options = this.options; - const {y} = this.getProps(['x'], useFinalPosition); - return (Math.abs(mouseY - y) < options.radius + options.hitRadius); + return inRange(this, mouseY, 'y', useFinalPosition); } getCenterPoint(useFinalPosition) {
false
Other
chartjs
Chart.js
692d8a41281e65b66195835ff69b887dfa65af5f.json
Remove unreachable code paths from plugins (#8513)
src/plugins/plugin.filler.js
@@ -114,24 +114,18 @@ class simpleArc { pathSegment(ctx, bounds, opts) { const {x, y, radius} = this; bounds = bounds || {start: 0, end: TAU}; - if (opts.reverse) { - ctx.arc(x, y, radius, bounds.end, bounds.start, true); - } else { - ctx.arc(x, y, radius, bounds.start, bounds.end); - } + ctx.arc(x, y, radius, bounds.end, bounds.start, true); return !opts.bounds; } - interpolate(point, property) { + interpolate(point) { const {x, y, radius} = this; const angle = point.angle; - if (property === 'angle') { - return { - x: x + Math.cos(angle) * radius, - y: y + Math.sin(angle) * radius, - angle - }; - } + return { + x: x + Math.cos(angle) * radius, + y: y + Math.sin(angle) * radius, + angle + }; } }
true
Other
chartjs
Chart.js
692d8a41281e65b66195835ff69b887dfa65af5f.json
Remove unreachable code paths from plugins (#8513)
src/plugins/plugin.title.js
@@ -119,24 +119,6 @@ function createTitle(chart, titleOpts) { chart.titleBlock = title; } -function removeTitle(chart) { - const title = chart.titleBlock; - if (title) { - layouts.removeBox(chart, title); - delete chart.titleBlock; - } -} - -function createOrUpdateTitle(chart, options) { - const title = chart.titleBlock; - if (title) { - layouts.configure(chart, title, options); - title.options = options; - } else { - createTitle(chart, options); - } -} - export default { id: 'title', @@ -157,11 +139,9 @@ export default { }, beforeUpdate(chart, _args, options) { - if (options === false) { - removeTitle(chart); - } else { - createOrUpdateTitle(chart, options); - } + const title = chart.titleBlock; + layouts.configure(chart, title, options); + title.options = options; }, defaults: {
true