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
b78b7c3534eb55e1294679a32dd93cfc74b45f48.json
Add explanation on how to run the samples locally (#9207) * add explenation on how to run the samples locally * Remove unecesarry parts from link
docs/getting-started/index.md
@@ -69,3 +69,5 @@ Finally, render the chart using our configuration: It's that easy to get started using Chart.js! From here you can explore the many options that can help you customise your charts with scales, tooltips, labels, colors, custom actions, and much more. All our examples are [available online](/samples/) but you can also download the `Chart.js.zip` archive attached to every [release](https://github.com/chartjs/Chart.js/releases) to experiment with our samples locally from the `/samples` folder. + +To run the samples locally you first have to install all the necessary packages using the `npm ci` command, after this you can run `npm run docs:dev` to build the documentation. As soon as the build is done, you can go to [http://localhost:8080/samples/](http://localhost:8080/samples/) to see the samples.
false
Other
chartjs
Chart.js
9326309afd4676f16a123fa5bafe7f1f1f26b5e2.json
Fix error when swapping dataset locations (#9183)
src/core/core.controller.js
@@ -347,23 +347,6 @@ class Chart { }); } - /** - * Updates the given metaset with the given dataset index. Ensures it's stored at that index - * in the _metasets array by swapping with the metaset at that index if necessary. - * @param {Object} meta - the dataset metadata - * @param {number} index - the dataset index - * @private - */ - _updateMetasetIndex(meta, index) { - const metasets = this._metasets; - const oldIndex = meta.index; - if (oldIndex !== index) { - metasets[oldIndex] = metasets[index]; - metasets[index] = meta; - meta.index = index; - } - } - /** * @private */ @@ -373,6 +356,7 @@ class Chart { const numData = me.data.datasets.length; const numMeta = metasets.length; + metasets.sort((a, b) => a.index - b.index); if (numMeta > numData) { for (let i = numData; i < numMeta; ++i) { me._destroyDatasetMeta(i); @@ -418,7 +402,7 @@ class Chart { meta.type = type; meta.indexAxis = dataset.indexAxis || getIndexAxis(type, me.options); meta.order = dataset.order || 0; - me._updateMetasetIndex(meta, i); + meta.index = i; meta.label = '' + dataset.label; meta.visible = me.isDatasetVisible(i); @@ -764,7 +748,7 @@ class Chart { let meta = metasets.filter(x => x && x._dataset === dataset).pop(); if (!meta) { - meta = metasets[datasetIndex] = { + meta = { type: null, data: [], dataset: null, @@ -778,6 +762,7 @@ class Chart { _parsed: [], _sorted: false }; + metasets.push(meta); } return meta;
true
Other
chartjs
Chart.js
9326309afd4676f16a123fa5bafe7f1f1f26b5e2.json
Fix error when swapping dataset locations (#9183)
test/specs/core.controller.tests.js
@@ -1778,6 +1778,33 @@ describe('Chart', function() { expect(metasets[2].order).toEqual(4); expect(metasets[3].order).toEqual(3); }); + it('should update properly when dataset locations are swapped', function() { + const orig = this.chart.data.datasets; + this.chart.data.datasets = [orig[0], orig[2], orig[1], orig[3]]; + this.chart.update(); + let metasets = this.chart._metasets; + expect(metasets[0].label).toEqual('1'); + expect(metasets[1].label).toEqual('3'); + expect(metasets[2].label).toEqual('2'); + expect(metasets[3].label).toEqual('4'); + + this.chart.data.datasets = [{label: 'new', order: 10}, orig[3], orig[2], orig[1], orig[0]]; + this.chart.update(); + metasets = this.chart._metasets; + expect(metasets[0].label).toEqual('new'); + expect(metasets[1].label).toEqual('4'); + expect(metasets[2].label).toEqual('3'); + expect(metasets[3].label).toEqual('2'); + expect(metasets[4].label).toEqual('1'); + + this.chart.data.datasets = [orig[3], orig[2], orig[1], {label: 'new', order: 10}]; + this.chart.update(); + metasets = this.chart._metasets; + expect(metasets[0].label).toEqual('4'); + expect(metasets[1].label).toEqual('3'); + expect(metasets[2].label).toEqual('2'); + expect(metasets[3].label).toEqual('new'); + }); }); describe('data visibility', function() {
true
Other
chartjs
Chart.js
8c6335106707309d1b2441c82ac66bd9641c13cd.json
Add documentation about default scales (#9173)
docs/axes/index.md
@@ -11,6 +11,86 @@ Scales in Chart.js >v2.0 are significantly more powerful, but also different tha * Scale titles are supported. * New scale types can be extended without writing an entirely new chart type. +## Default scales + +The default `scaleId`'s for carterian charts are `'x'` and `'y'`. For radial charts: `'r'`. +Each dataset is mapped to a scale for each axis (x, y or r) it requires. The scaleId's that a dataset is mapped to, is determined by the `xAxisID`, `yAxisID` or `rAxisID`. +If the ID for an axis is not specified, first scale for that axis is used. If no scale for an axis is found, a new scale is created. + +Some examples: + +The following chart will have `'x'` and `'y'` scales: + +```js +let chart = new Chart(ctx, { + type: 'line' +}); +``` + +The following chart will have scales `'x'` and `'myScale'`: + +```js +let chart = new Chart(ctx, { + type: 'bar', + data: { + datasets: [{ + data: [1, 2, 3] + }] + }, + options: { + scales: { + myScale: { + type: 'logarithmic', + position: 'right', // `axis` is determined by the position as `'y'` + } + } + } +}); +``` + +The following chart will have scales `'xAxis'` and `'yAxis'`: + +```js +let chart = new Chart(ctx, { + type: 'bar', + data: { + datasets: [{ + yAxisID: 'yAxis' + }] + }, + options: { + scales: { + xAxis: { + // The axis for this scale is determined from the first letter of the id as `'x'` + // It is recommended to specify `position` and / or `axis` explicitly. + type: 'time', + } + } + } +}); +``` + +The following chart will have `'r'` scale: + +```js +let chart = new Chart(ctx, { + type: 'radar' +}); +``` + +The following chart will have `'myScale'` scale: + +```js +let chart = new Chart(ctx, { + type: 'radar', + scales: { + myScale: { + axis: 'r' + } + } +}); +``` + ## Common Configuration !!!include(axes/_common.md)!!!
false
Other
chartjs
Chart.js
aa6a9737bd780231b0684eeaf6df132a12b7ecec.json
Add declaration for Decimation plugin (#9172)
types/index.esm.d.ts
@@ -1953,6 +1953,8 @@ export class BasePlatform { export class BasicPlatform extends BasePlatform {} export class DomPlatform extends BasePlatform {} +export const Decimation: Plugin; + export const enum DecimationAlgorithm { lttb = 'lttb', minmax = 'min-max',
true
Other
chartjs
Chart.js
aa6a9737bd780231b0684eeaf6df132a12b7ecec.json
Add declaration for Decimation plugin (#9172)
types/tests/register.ts
@@ -0,0 +1,52 @@ +import { + Chart, + ArcElement, + LineElement, + BarElement, + PointElement, + BarController, + BubbleController, + DoughnutController, + LineController, + PieController, + PolarAreaController, + RadarController, + ScatterController, + CategoryScale, + LinearScale, + LogarithmicScale, + RadialLinearScale, + TimeScale, + TimeSeriesScale, + Decimation, + Filler, + Legend, + Title, + Tooltip +} from '../index.esm'; + +Chart.register( + ArcElement, + LineElement, + BarElement, + PointElement, + BarController, + BubbleController, + DoughnutController, + LineController, + PieController, + PolarAreaController, + RadarController, + ScatterController, + CategoryScale, + LinearScale, + LogarithmicScale, + RadialLinearScale, + TimeScale, + TimeSeriesScale, + Decimation, + Filler, + Legend, + Title, + Tooltip +);
true
Other
chartjs
Chart.js
77cfac17859c0e086dc90b4c85ac2108581d56dc.json
Ignore items outside chart area for interaction (#9171)
src/core/core.interaction.js
@@ -166,6 +166,9 @@ function getNearestItems(chart, position, axis, intersect, useFinalPosition) { } const center = element.getCenterPoint(useFinalPosition); + if (!_isPointInArea(center, chart.chartArea, chart._minPadding)) { + return; + } const distance = distanceMetric(position, center); if (distance < minDistance) { items = [{element, datasetIndex, index}];
false
Other
chartjs
Chart.js
8c5d6be19748e1f0479473f75627c28268034e3a.json
Add missing props to ChartArea type (#9123)
types/geometric.d.ts
@@ -1,11 +1,13 @@ export interface ChartArea { - top: number; - left: number; - right: number; - bottom: number; + top: number; + left: number; + right: number; + bottom: number; + width: number; + height: number; } export interface Point { - x: number; - y: number; + x: number; + y: number; }
false
Other
chartjs
Chart.js
749d1fc9422d7e35276da3097480707c59263e72.json
Fix animations when data is replaced (#9120)
src/core/core.datasetController.js
@@ -332,16 +332,15 @@ export default class DatasetController { if (_data) { // This case happens when the user replaced the data array instance. unlistenArrayEvents(_data, me); - // Discard old elements, parsed data and stacks + // Discard old parsed data and stacks const meta = me._cachedMeta; clearStacks(meta); meta._parsed = []; - meta.data = []; } if (data && Object.isExtensible(data)) { listenArrayEvents(data, me); - me._syncList = []; } + me._syncList = []; me._data = data; } } @@ -933,7 +932,8 @@ export default class DatasetController { me._insertElements(numMeta, numData - numMeta, resetNewElements); } else if (numData < numMeta) { me._removeElements(numData, numMeta - numData); - } else if (count) { + } + if (count) { // TODO: It is not optimal to always parse the old data // This is done because we are not detecting direct assignments: // chart.data.datasets[0].data[5] = 10;
true
Other
chartjs
Chart.js
749d1fc9422d7e35276da3097480707c59263e72.json
Fix animations when data is replaced (#9120)
test/specs/core.datasetController.tests.js
@@ -392,12 +392,14 @@ describe('Chart.DatasetController', function() { expect(meta.data.length).toBe(6); expect(meta._parsed.map(p => p.y)).toEqual(data0); + const point0 = meta.data[0]; chart.data.datasets[0].data = data1; chart.update(); expect(meta.data.length).toBe(3); expect(meta._parsed.map(p => p.y)).toEqual(data1); + expect(meta.data[0]).toEqual(point0); data1.push(9); chart.update();
true
Other
chartjs
Chart.js
d1a243efec9532db630268e0584d766b4ce2c73b.json
Delay data to elements synchronization to update (#9105)
src/core/core.datasetController.js
@@ -228,6 +228,7 @@ export default class DatasetController { this._drawCount = undefined; this.enableOptionSharing = false; this.$context = undefined; + this._syncList = []; this.initialize(); } @@ -242,6 +243,9 @@ export default class DatasetController { } updateIndex(datasetIndex) { + if (this.index !== datasetIndex) { + clearStacks(this._cachedMeta); + } this.index = datasetIndex; } @@ -316,21 +320,27 @@ export default class DatasetController { const me = this; const dataset = me.getDataset(); const data = dataset.data || (dataset.data = []); + const _data = me._data; // In order to correctly handle data addition/deletion animation (an thus simulate // real-time charts), we need to monitor these data modifications and synchronize // the internal meta data accordingly. if (isObject(data)) { me._data = convertObjectDataToArray(data); - } else if (me._data !== data) { - if (me._data) { + } else if (_data !== data) { + if (_data) { // This case happens when the user replaced the data array instance. - unlistenArrayEvents(me._data, me); - clearStacks(me._cachedMeta); + unlistenArrayEvents(_data, me); + // Discard old elements, parsed data and stacks + const meta = me._cachedMeta; + clearStacks(meta); + meta._parsed = []; + meta.data = []; } if (data && Object.isExtensible(data)) { listenArrayEvents(data, me); + me._syncList = []; } me._data = data; } @@ -356,6 +366,7 @@ export default class DatasetController { me._dataCheck(); // make sure cached _stacked status is current + const oldStacked = meta._stacked; meta._stacked = isStacked(meta.vScale, meta); // detect change in stack option @@ -371,7 +382,7 @@ export default class DatasetController { me._resyncElements(resetNewElements); // if stack changed, update stack values for the whole dataset - if (stackChanged) { + if (stackChanged || oldStacked !== meta._stacked) { updateStacks(me, meta._parsed); } } @@ -905,17 +916,28 @@ export default class DatasetController { */ _resyncElements(resetNewElements) { const me = this; - const numMeta = me._cachedMeta.data.length; - const numData = me._data.length; + const data = me._data; + const elements = me._cachedMeta.data; + + // Apply changes detected through array listeners + for (const [method, arg1, arg2] of me._syncList) { + me[method](arg1, arg2); + } + me._syncList = []; + + const numMeta = elements.length; + const numData = data.length; + const count = Math.min(numData, numMeta); if (numData > numMeta) { me._insertElements(numMeta, numData - numMeta, resetNewElements); } else if (numData < numMeta) { me._removeElements(numData, numMeta - numData); - } - // Re-parse the old elements (new elements are parsed in _insertElements) - const count = Math.min(numData, numMeta); - if (count) { + } else if (count) { + // TODO: It is not optimal to always parse the old data + // This is done because we are not detecting direct assignments: + // chart.data.datasets[0].data[5] = 10; + // chart.data.datasets[0].data[5].y = 10; me.parse(0, count); } } @@ -975,36 +997,36 @@ export default class DatasetController { */ _onDataPush() { const count = arguments.length; - this._insertElements(this.getDataset().data.length - count, count); + this._syncList.push(['_insertElements', this.getDataset().data.length - count, count]); } /** * @private */ _onDataPop() { - this._removeElements(this._cachedMeta.data.length - 1, 1); + this._syncList.push(['_removeElements', this._cachedMeta.data.length - 1, 1]); } /** * @private */ _onDataShift() { - this._removeElements(0, 1); + this._syncList.push(['_removeElements', 0, 1]); } /** * @private */ _onDataSplice(start, count) { - this._removeElements(start, count); - this._insertElements(start, arguments.length - 2); + this._syncList.push(['_removeElements', start, count]); + this._syncList.push(['_insertElements', start, arguments.length - 2]); } /** * @private */ _onDataUnshift() { - this._insertElements(0, arguments.length); + this._syncList.push(['_insertElements', 0, arguments.length]); } }
true
Other
chartjs
Chart.js
d1a243efec9532db630268e0584d766b4ce2c73b.json
Delay data to elements synchronization to update (#9105)
test/specs/core.datasetController.tests.js
@@ -268,13 +268,15 @@ describe('Chart.DatasetController', function() { last = meta.data[5]; data.push(6, 7, 8); data.push(9); + chart.update(); expect(meta.data.length).toBe(10); expect(meta.data[0]).toBe(first); expect(meta.data[5]).toBe(last); expect(parsedYValues()).toEqual(data); last = meta.data[9]; data.pop(); + chart.update(); expect(meta.data.length).toBe(9); expect(meta.data[0]).toBe(first); expect(meta.data.indexOf(last)).toBe(-1); @@ -284,6 +286,7 @@ describe('Chart.DatasetController', function() { data.shift(); data.shift(); data.shift(); + chart.update(); expect(meta.data.length).toBe(6); expect(meta.data.indexOf(first)).toBe(-1); expect(meta.data[5]).toBe(last); @@ -293,6 +296,7 @@ describe('Chart.DatasetController', function() { second = meta.data[1]; last = meta.data[5]; data.splice(1, 4, 10, 11); + chart.update(); expect(meta.data.length).toBe(4); expect(meta.data[0]).toBe(first); expect(meta.data[3]).toBe(last); @@ -301,6 +305,7 @@ describe('Chart.DatasetController', function() { data.unshift(12, 13, 14, 15); data.unshift(16, 17); + chart.update(); expect(meta.data.length).toBe(10); expect(meta.data[6]).toBe(first); expect(meta.data[9]).toBe(last); @@ -333,12 +338,14 @@ describe('Chart.DatasetController', function() { last = controller.getParsed(5); data.push({x: 6, y: 6}, {x: 7, y: 7}, {x: 8, y: 8}); data.push({x: 9, y: 9}); + chart.update(); expect(meta.data.length).toBe(10); expect(controller.getParsed(0)).toBe(first); expect(controller.getParsed(5)).toBe(last); last = controller.getParsed(9); data.pop(); + chart.update(); expect(meta.data.length).toBe(9); expect(controller.getParsed(0)).toBe(first); expect(controller.getParsed(9)).toBe(undefined); @@ -348,19 +355,22 @@ describe('Chart.DatasetController', function() { data.shift(); data.shift(); data.shift(); + chart.update(); expect(meta.data.length).toBe(6); expect(controller.getParsed(5)).toBe(last); first = controller.getParsed(0); last = controller.getParsed(5); data.splice(1, 4, {x: 10, y: 10}, {x: 11, y: 11}); + chart.update(); expect(meta.data.length).toBe(4); expect(controller.getParsed(0)).toBe(first); expect(controller.getParsed(3)).toBe(last); expect(controller.getParsed(1)).toEqual({x: 10, y: 10}); data.unshift({x: 12, y: 12}, {x: 13, y: 13}, {x: 14, y: 14}, {x: 15, y: 15}); data.unshift({x: 16, y: 16}, {x: 17, y: 17}); + chart.update(); expect(meta.data.length).toBe(10); expect(controller.getParsed(6)).toBe(first); expect(controller.getParsed(9)).toBe(last); @@ -390,6 +400,7 @@ describe('Chart.DatasetController', function() { expect(meta._parsed.map(p => p.y)).toEqual(data1); data1.push(9); + chart.update(); expect(meta.data.length).toBe(4); chart.data.datasets[0].data = data0;
true
Other
chartjs
Chart.js
927f24a809834100c138dc70cffd9e9b920478a5.json
Add test for issue 9085 (#9091)
types/tests/scales/chart_options.ts
@@ -0,0 +1,12 @@ +import { ChartOptions } from '../../index.esm'; + +const chartOptions: ChartOptions<'line'> = { + scales: { + x: { + type: 'time', + time: { + unit: 'year' + } + }, + } +};
false
Other
chartjs
Chart.js
1a1e677699f7b466c970529bbb988dde81f0ad9c.json
Fix: Avoid negative layout dimensions (#9027)
src/core/core.layouts.js
@@ -309,8 +309,8 @@ export default { } const padding = toPadding(chart.options.layout.padding); - const availableWidth = width - padding.width; - const availableHeight = height - padding.height; + const availableWidth = Math.max(width - padding.width, 0); + const availableHeight = Math.max(height - padding.height, 0); const boxes = buildLayoutBoxes(chart.boxes); const verticalBoxes = boxes.vertical; const horizontalBoxes = boxes.horizontal;
true
Other
chartjs
Chart.js
1a1e677699f7b466c970529bbb988dde81f0ad9c.json
Fix: Avoid negative layout dimensions (#9027)
test/specs/scale.linear.tests.js
@@ -1220,4 +1220,31 @@ describe('Linear Scale', function() { expect(scale.getValueForPixel(end)).toBeCloseTo(min, 4); expect(scale.getValueForPixel(start)).toBeCloseTo(max, 4); }); + + it('should not throw errors when chart size is negative', function() { + function createChart() { + return window.acquireChart({ + type: 'bar', + data: { + labels: [0, 1, 2, 3, 4, 5, 6, 7, '7+'], + datasets: [{ + data: [29.05, 4, 15.69, 11.69, 2.84, 4, 0, 3.84, 4], + }], + }, + options: { + plugins: false, + layout: { + padding: {top: 30, left: 1, right: 1, bottom: 1} + } + } + }, { + canvas: { + height: 0, + width: 0 + } + }); + } + + expect(createChart).not.toThrow(); + }); });
true
Other
chartjs
Chart.js
f5c51afd5186b2389250159a333a1160c09aee4b.json
fix typo on api.md (#9030)
docs/developers/api.md
@@ -103,7 +103,7 @@ To get an item that was clicked on, `getElementsAtEventForMode` can be used. ```javascript function clickHandler(evt) { - const points = myChart.getElementAtEventForMode(evt, 'nearest', { intersect: true }, true); + const points = myChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true); if (points.length) { const firstPoint = points[0];
false
Other
chartjs
Chart.js
49e7edae49467fd74a52b3cc934b33ad0219554e.json
Enable scriptable element chart options (#9012)
types/index.esm.d.ts
@@ -604,7 +604,7 @@ export interface DatasetControllerChartComponent extends ChartComponent { }; } -export interface Defaults extends CoreChartOptions<ChartType>, ElementChartOptions, PluginChartOptions<ChartType> { +export interface Defaults extends CoreChartOptions<ChartType>, ElementChartOptions<ChartType>, PluginChartOptions<ChartType> { scale: ScaleOptionsByType; scales: { @@ -641,7 +641,7 @@ export interface Defaults extends CoreChartOptions<ChartType>, ElementChartOptio export type Overrides = { [key in ChartType]: CoreChartOptions<key> & - ElementChartOptions & + ElementChartOptions<key> & PluginChartOptions<key> & DatasetChartOptions<ChartType> & ScaleChartOptions<key> & @@ -1887,16 +1887,17 @@ export const BarElement: ChartComponent & { new (cfg: AnyObject): BarElement; }; -export interface ElementOptionsByType { - arc: ArcOptions & ArcHoverOptions; - bar: BarOptions & BarHoverOptions; - line: LineOptions & LineHoverOptions; - point: PointOptions & PointHoverOptions; -} -export interface ElementChartOptions { - elements: Partial<ElementOptionsByType>; +export interface ElementOptionsByType<TType extends ChartType> { + arc: ScriptableAndArrayOptions<ArcOptions & ArcHoverOptions, ScriptableContext<TType>>; + bar: ScriptableAndArrayOptions<BarOptions & BarHoverOptions, ScriptableContext<TType>>; + line: ScriptableAndArrayOptions<LineOptions & LineHoverOptions, ScriptableContext<TType>>; + point: ScriptableAndArrayOptions<PointOptions & PointHoverOptions, ScriptableContext<TType>>; } +export type ElementChartOptions<TType extends ChartType = ChartType> = { + elements: ElementOptionsByType<TType> +}; + export class BasePlatform { /** * Called at chart construction time, returns a context2d instance implementing @@ -3321,7 +3322,7 @@ export type ScaleChartOptions<TType extends ChartType = ChartType> = { export type ChartOptions<TType extends ChartType = ChartType> = DeepPartial< CoreChartOptions<TType> & - ElementChartOptions & + ElementChartOptions<TType> & PluginChartOptions<TType> & DatasetChartOptions<TType> & ScaleChartOptions<TType> &
true
Other
chartjs
Chart.js
49e7edae49467fd74a52b3cc934b33ad0219554e.json
Enable scriptable element chart options (#9012)
types/tests/elements/scriptable_element_options.ts
@@ -0,0 +1,49 @@ +import { Chart } from '../../index.esm'; + +const chart = new Chart('id', { + type: 'line', + data: { + labels: [], + datasets: [] + }, + options: { + elements: { + line: { + borderWidth: () => 2, + }, + point: { + pointStyle: (ctx) => 'star', + } + } + } +}); + +const chart2 = new Chart('id', { + type: 'bar', + data: { + labels: [], + datasets: [] + }, + options: { + elements: { + bar: { + borderWidth: (ctx) => 2, + } + } + } +}); + +const chart3 = new Chart('id', { + type: 'doughnut', + data: { + labels: [], + datasets: [] + }, + options: { + elements: { + arc: { + borderWidth: (ctx) => 3, + } + } + } +});
true
Other
chartjs
Chart.js
ea7b8cb04f528fe0c9fac526f2bdbf809397d0bd.json
Add test for DecimationAlgorithm type (#9010) * Add test for DecimationAlgorithm type * Allow strings to be set * Linting
types/index.esm.d.ts
@@ -1961,12 +1961,12 @@ interface BaseDecimationOptions { } interface LttbDecimationOptions extends BaseDecimationOptions { - algorithm: DecimationAlgorithm.lttb; + algorithm: DecimationAlgorithm.lttb | 'lttb'; samples?: number; } interface MinMaxDecimationOptions extends BaseDecimationOptions { - algorithm: DecimationAlgorithm.minmax; + algorithm: DecimationAlgorithm.minmax | 'min-max'; } export type DecimationOptions = LttbDecimationOptions | MinMaxDecimationOptions;
true
Other
chartjs
Chart.js
ea7b8cb04f528fe0c9fac526f2bdbf809397d0bd.json
Add test for DecimationAlgorithm type (#9010) * Add test for DecimationAlgorithm type * Allow strings to be set * Linting
types/tests/plugins/plugin.decimation/decimation_algorithm.ts
@@ -0,0 +1,72 @@ +import { Chart, DecimationAlgorithm } from '../../../index.esm'; + +const chart = new Chart('id', { + type: 'bubble', + data: { + labels: [], + datasets: [{ + data: [] + }] + }, + options: { + plugins: { + decimation: { + algorithm: DecimationAlgorithm.lttb, + } + } + } +}); + + +const chart2 = new Chart('id', { + type: 'bubble', + data: { + labels: [], + datasets: [{ + data: [] + }] + }, + options: { + plugins: { + decimation: { + algorithm: 'lttb', + } + } + } +}); + + +const chart3 = new Chart('id', { + type: 'bubble', + data: { + labels: [], + datasets: [{ + data: [] + }] + }, + options: { + plugins: { + decimation: { + algorithm: DecimationAlgorithm.minmax, + } + } + } +}); + + +const chart4 = new Chart('id', { + type: 'bubble', + data: { + labels: [], + datasets: [{ + data: [] + }] + }, + options: { + plugins: { + decimation: { + algorithm: 'min-max', + } + } + } +});
true
Other
chartjs
Chart.js
55dd426a412c89cc0457a3ec925cb2df11ccfa28.json
Add documentation on tooltip xAlign and yAlign (#9011)
docs/configuration/tooltip.md
@@ -17,16 +17,16 @@ Namespace: `options.plugins.tooltip`, the global options for the chart tooltips | `backgroundColor` | [`Color`](../general/colors.md) | `'rgba(0, 0, 0, 0.8)'` | Background color of the tooltip. | `titleColor` | [`Color`](../general/colors.md) | `'#fff'` | Color of title text. | `titleFont` | `Font` | `{weight: 'bold'}` | See [Fonts](../general/fonts.md). -| `titleAlign` | `string` | `'left'` | Horizontal alignment of the title text lines. [more...](#alignment) +| `titleAlign` | `string` | `'left'` | Horizontal alignment of the title text lines. [more...](#text-alignment) | `titleSpacing` | `number` | `2` | Spacing to add to top and bottom of each title line. | `titleMarginBottom` | `number` | `6` | Margin to add on bottom of title section. | `bodyColor` | [`Color`](../general/colors.md) | `'#fff'` | Color of body text. | `bodyFont` | `Font` | `{}` | See [Fonts](../general/fonts.md). -| `bodyAlign` | `string` | `'left'` | Horizontal alignment of the body text lines. [more...](#alignment) +| `bodyAlign` | `string` | `'left'` | Horizontal alignment of the body text lines. [more...](#text-alignment) | `bodySpacing` | `number` | `2` | Spacing to add to top and bottom of each tooltip item. | `footerColor` | [`Color`](../general/colors.md) | `'#fff'` | Color of footer text. | `footerFont` | `Font` | `{weight: 'bold'}` | See [Fonts](../general/fonts.md). -| `footerAlign` | `string` | `'left'` | Horizontal alignment of the footer text lines. [more...](#alignment) +| `footerAlign` | `string` | `'left'` | Horizontal alignment of the footer text lines. [more...](#text-alignment) | `footerSpacing` | `number` | `2` | Spacing to add to top and bottom of each footer line. | `footerMarginTop` | `number` | `6` | Margin to add before drawing the footer. | `padding` | [`Padding`](../general/padding.md) | `6` | Padding inside the tooltip. @@ -42,6 +42,8 @@ Namespace: `options.plugins.tooltip`, the global options for the chart tooltips | `borderWidth` | `number` | `0` | Size of the border. | `rtl` | `boolean` | | `true` for rendering the tooltip from right to left. | `textDirection` | `string` | canvas' default | This will force the text direction `'rtl' or 'ltr` on the canvas for rendering the tooltips, regardless of the css specified on the canvas +| `xAlign` | `string` | `undefined` | Position of the tooltip caret in the X direction. [more](#tooltip-alignment) +| `yAlign` | `string` | `undefined` | Position of the tooltip caret in the Y direction. [more](#tooltip-alignment) ### Position Modes @@ -78,7 +80,23 @@ tooltipPlugin.positioners.myCustomPositioner = function(elements, eventPosition) }; ``` -### Alignment +### Tooltip Alignment + +The `xAlign` and `yAlign` options define the position of the tooltip caret. If these parameters are unset, the optimal caret position is determined. + +The following values for the `xAlign` setting are supported. + +* `'left'` +* `'center'` +* `'right'` + +The following values for the `yAlign` setting are supported. + +* `'top'` +* `'center'` +* `'bottom'` + +### Text Alignment The `titleAlign`, `bodyAlign` and `footerAlign` options define the horizontal position of the text lines with respect to the tooltip box. The following values are supported.
false
Other
chartjs
Chart.js
12bf256fd551b172f4a72111433eb69382640956.json
Ignore truncated pixels in bar width calculation (#8995)
src/controllers/controller.bar.js
@@ -1,7 +1,7 @@ import DatasetController from '../core/core.datasetController'; import { clipArea, unclipArea, _arrayUnique, isArray, isNullOrUndef, - valueOrDefault, resolveObjectKey, sign + valueOrDefault, resolveObjectKey, sign, defined } from '../helpers'; function getAllScaleValues(scale) { @@ -26,7 +26,14 @@ function computeMinSampleSize(scale) { let min = scale._length; let i, ilen, curr, prev; const updateMinAndPrev = () => { - min = Math.min(min, i && Math.abs(curr - prev) || min); + if (curr === 32767 || curr === -32768) { + // Ingnore truncated pixels + return; + } + if (defined(prev)) { + // curr - prev === 0 is ignored + min = Math.min(min, Math.abs(curr - prev) || min); + } prev = curr; }; @@ -35,6 +42,7 @@ function computeMinSampleSize(scale) { updateMinAndPrev(); } + prev = undefined; for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) { curr = scale.getPixelForTick(i); updateMinAndPrev();
false
Other
chartjs
Chart.js
019cb9f3052a803d09da664d8aa4f33c210e8ed0.json
Add example plugins for border and quadrants (#8942)
docs/.vuepress/config.js
@@ -257,6 +257,13 @@ module.exports = { 'advanced/derived-chart-type', ] }, + { + title: 'Plugins', + children: [ + 'plugins/chart-area-border', + 'plugins/quadrants', + ] + }, ], '/': [ '',
true
Other
chartjs
Chart.js
019cb9f3052a803d09da664d8aa4f33c210e8ed0.json
Add example plugins for border and quadrants (#8942)
docs/samples/plugins/chart-area-border.md
@@ -0,0 +1,63 @@ +# Chart Area Border + +```js chart-editor +// <block:data:2> +const DATA_COUNT = 7; +const NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100}; +const labels = Utils.months({count: 7}); +const data = { + labels: labels, + datasets: [ + { + label: 'Dataset 1', + data: Utils.numbers(NUMBER_CFG), + borderColor: Utils.CHART_COLORS.red, + backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5), + }, + { + label: 'Dataset 2', + data: Utils.numbers(NUMBER_CFG), + borderColor: Utils.CHART_COLORS.blue, + backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5), + } + ] +}; +// </block:data> + +// <block:plugin:1> +const chartAreaBorder = { + id: 'chartAreaBorder', + beforeDraw(chart, args, options) { + const {ctx, chartArea: {left, top, width, height}} = chart; + ctx.save(); + ctx.strokeStyle = options.borderColor; + ctx.lineWidth = options.borderWidth; + ctx.setLineDash(options.borderDash || []); + ctx.lineDashOffset = options.borderDashOffset; + ctx.strokeRect(left, top, width, height); + ctx.restore(); + } +}; +// </block:plugin> + +// <block:config:0> +const config = { + type: 'line', + data: data, + options: { + plugins: { + chartAreaBorder: { + borderColor: 'red', + borderWidth: 2, + borderDash: [5, 5], + borderDashOffset: 2, + } + } + }, + plugins: [chartAreaBorder] +}; +// </block:config> + +module.exports = { + config: config, +};
true
Other
chartjs
Chart.js
019cb9f3052a803d09da664d8aa4f33c210e8ed0.json
Add example plugins for border and quadrants (#8942)
docs/samples/plugins/quadrants.md
@@ -0,0 +1,79 @@ +# Quadrants + +```js chart-editor +// <block:data:2> +const DATA_COUNT = 7; +const NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100}; +const data = { + datasets: [ + { + label: 'Dataset 1', + data: Utils.points(NUMBER_CFG), + borderColor: Utils.CHART_COLORS.red, + backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5), + }, + { + label: 'Dataset 2', + data: Utils.points(NUMBER_CFG), + borderColor: Utils.CHART_COLORS.blue, + backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5), + } + ] +}; +// </block:data> + +// <block:plugin:1> +const quadrants = { + id: 'quadrants', + beforeDraw(chart, args, options) { + const {ctx, chartArea: {left, top, right, bottom}, scales: {x, y}} = chart; + const midX = x.getPixelForValue(0); + const midY = y.getPixelForValue(0); + ctx.save(); + ctx.fillStyle = options.topLeft; + ctx.fillRect(left, top, midX - left, midY - top); + ctx.fillStyle = options.topRight; + ctx.fillRect(midX, top, right - midX, midY - top); + ctx.fillStyle = options.bottomRight; + ctx.fillRect(midX, midY, right - midX, bottom - midY); + ctx.fillStyle = options.bottomLeft; + ctx.fillRect(left, midY, midX - left, bottom - midY); + ctx.restore(); + } +}; +// </block:plugin> + +// <block:config:0> +const config = { + type: 'scatter', + data: data, + options: { + plugins: { + quadrants: { + topLeft: Utils.CHART_COLORS.red, + topRight: Utils.CHART_COLORS.blue, + bottomRight: Utils.CHART_COLORS.green, + bottomLeft: Utils.CHART_COLORS.yellow, + } + } + }, + plugins: [quadrants] +}; +// </block:config> + +const actions = [ + { + name: 'Randomize', + handler(chart) { + chart.data.datasets.forEach(dataset => { + dataset.data = Utils.points(NUMBER_CFG); + }); + chart.update(); + } + }, +]; + +module.exports = { + actions, + config, +};
true
Other
chartjs
Chart.js
877f4c6b2d5cdd732d79f2ed088095f5768c6bb2.json
Fix tooltip align & external types (#8782)
types/index.esm.d.ts
@@ -2208,15 +2208,16 @@ export interface TitleOptions { text: string | string[]; } -export type TooltipAlignment = 'start' | 'center' | 'end'; +export type TooltipXAlignment = 'left' | 'center' | 'right'; +export type TooltipYAlignment = 'top' | 'center' | 'bottom'; export interface TooltipModel<TType extends ChartType> { // The items that we are rendering in the tooltip. See Tooltip Item Interface section dataPoints: TooltipItem<TType>[]; // Positioning - xAlign: TooltipAlignment; - yAlign: TooltipAlignment; + xAlign: TooltipXAlignment; + yAlign: TooltipYAlignment; // X and Y properties are the top left of the tooltip x: number; @@ -2331,9 +2332,9 @@ export interface TooltipOptions<TType extends ChartType> extends CoreInteraction */ enabled: Scriptable<boolean, ScriptableTooltipContext<TType>>; /** - * See custom tooltip section. + * See external tooltip section. */ - custom(this: TooltipModel<TType>, args: { chart: Chart; tooltip: TooltipModel<TType> }): void; + external(this: TooltipModel<TType>, args: { chart: Chart; tooltip: TooltipModel<TType> }): void; /** * The mode for positioning the tooltip */ @@ -2342,8 +2343,8 @@ export interface TooltipOptions<TType extends ChartType> extends CoreInteraction /** * Override the tooltip alignment calculations */ - xAlign: Scriptable<TooltipAlignment, ScriptableTooltipContext<TType>>; - yAlign: Scriptable<TooltipAlignment, ScriptableTooltipContext<TType>>; + xAlign: Scriptable<TooltipXAlignment, ScriptableTooltipContext<TType>>; + yAlign: Scriptable<TooltipYAlignment, ScriptableTooltipContext<TType>>; /** * Sort tooltip items.
false
Other
chartjs
Chart.js
5cb60d51109d4200ea6ac1fe65554f542075d11b.json
Remove .d.ts from helper types location (#8761)
helpers/helpers.esm.d.ts
@@ -1 +1 @@ -export * from '../types/helpers/index.d.ts'; +export * from '../types/helpers/index';
true
Other
chartjs
Chart.js
5cb60d51109d4200ea6ac1fe65554f542075d11b.json
Remove .d.ts from helper types location (#8761)
helpers/helpers.esm.js
@@ -1 +1 @@ -export * from '../dist/helpers.esm'; \ No newline at end of file +export * from '../dist/helpers.esm';
true
Other
chartjs
Chart.js
5cb60d51109d4200ea6ac1fe65554f542075d11b.json
Remove .d.ts from helper types location (#8761)
helpers/helpers.js
@@ -1 +1 @@ -module.exports = require('..').helpers; \ No newline at end of file +module.exports = require('..').helpers;
true
Other
chartjs
Chart.js
a6eaaf771f60575927d368bf9b6d48a87c14f902.json
Change the title of the tip block to Note (#8758)
docs/charts/area.md
@@ -2,7 +2,7 @@ Both [line](./line.mdx) and [radar](./radar.mdx) charts support a `fill` option on the dataset object which can be used to create space between two datasets or a dataset and a boundary, i.e. the scale `origin`, `start,` or `end` (see [filling modes](#filling-modes)). -:::tip +:::tip Note This feature is implemented by the [`filler` plugin](https://github.com/chartjs/Chart.js/blob/master/src/plugins/plugin.filler.js). :::
true
Other
chartjs
Chart.js
a6eaaf771f60575927d368bf9b6d48a87c14f902.json
Change the title of the tip block to Note (#8758)
docs/charts/bar.md
@@ -123,7 +123,7 @@ This setting is used to avoid drawing the bar stroke at the base of the fill, or In general, this does not need to be changed except when creating chart types that derive from a bar chart. -:::tip +:::tip Note For negative bars in a vertical chart, `top` and `bottom` are flipped. Same goes for `left` and `right` in a horizontal chart. :::
true
Other
chartjs
Chart.js
a6eaaf771f60575927d368bf9b6d48a87c14f902.json
Change the title of the tip block to Note (#8758)
docs/configuration/animations.md
@@ -164,7 +164,7 @@ Namespace: `options.animations[animation]` | `colors` | `properties` | `['color', 'borderColor', 'backgroundColor']` | `colors` | `type` | `'color'` -:::tip +:::tip Note These default animations are overridden by most of the dataset controllers. :::
true
Other
chartjs
Chart.js
a6eaaf771f60575927d368bf9b6d48a87c14f902.json
Change the title of the tip block to Note (#8758)
docs/general/options.md
@@ -68,7 +68,7 @@ A plugin can provide `additionalOptionScopes` array of paths to additionally loo Scriptable options also accept a function which is called for each of the underlying data values and that takes the unique argument `context` representing contextual information (see [option context](options.md#option-context)). A resolver is passed as second parameter, that can be used to access other options in the same context. -:::tip +:::tip Note The `context` argument should be validated in the scriptable function, because the function can be invoked in different contexts. The `type` field is a good candidate for this validation.
true
Other
chartjs
Chart.js
4b7b3f277fcf87820bb3be0b2180927f1a59e86b.json
Build docs with node14 (#8754)
.github/workflows/deploy-docs.yml
@@ -21,6 +21,8 @@ jobs: - uses: actions/checkout@v2 - name: Use Node.js uses: actions/setup-node@v1 + with: + node-version: '14.x' - name: Package & Deploy Docs run: | npm ci
true
Other
chartjs
Chart.js
4b7b3f277fcf87820bb3be0b2180927f1a59e86b.json
Build docs with node14 (#8754)
.github/workflows/npmpublish.yml
@@ -36,7 +36,7 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-node@v1 with: - node-version: 12 + node-version: '14.x' registry-url: https://registry.npmjs.org/ - name: Setup and build run: |
true
Other
chartjs
Chart.js
88c585b11e82ab9fa8d83f1878543ab293c8f0fa.json
Legend: adjust lifecycle and event handling (#8753)
src/plugins/plugin.legend.js
@@ -27,6 +27,8 @@ const getBoxSize = (labelOpts, fontSize) => { }; }; +const itemsEqual = (a, b) => a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index; + export class Legend extends Element { /** @@ -154,51 +156,61 @@ export class Legend extends Element { */ _fitRows(titleHeight, fontSize, boxWidth, itemHeight) { const me = this; - const {ctx, maxWidth} = me; - const padding = me.options.labels.padding; + const {ctx, maxWidth, options: {labels: {padding}}} = me; const hitboxes = me.legendHitBoxes = []; // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one const lineWidths = me.lineWidths = [0]; + const lineHeight = itemHeight + padding; let totalHeight = titleHeight; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; + let row = -1; + let top = -lineHeight; me.legendItems.forEach((legendItem, i) => { const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) { - totalHeight += itemHeight + padding; + totalHeight += lineHeight; lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0; + top += lineHeight; + row++; } - // Store the hitbox width and height here. Final position will be updated in `draw` - hitboxes[i] = {left: 0, top: 0, width: itemWidth, height: itemHeight}; + hitboxes[i] = {left: 0, top, row, width: itemWidth, height: itemHeight}; lineWidths[lineWidths.length - 1] += itemWidth + padding; - }); + return totalHeight; } _fitCols(titleHeight, fontSize, boxWidth, itemHeight) { const me = this; - const {ctx, maxHeight} = me; - const padding = me.options.labels.padding; + const {ctx, maxHeight, options: {labels: {padding}}} = me; const hitboxes = me.legendHitBoxes = []; const columnSizes = me.columnSizes = []; + const heightLimit = maxHeight - titleHeight; + let totalWidth = padding; let currentColWidth = 0; let currentColHeight = 0; - const heightLimit = maxHeight - titleHeight; + let left = 0; + let top = 0; + let col = 0; + me.legendItems.forEach((legendItem, i) => { const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; // If too tall, go to new column if (i > 0 && currentColHeight + fontSize + 2 * padding > heightLimit) { totalWidth += currentColWidth + padding; columnSizes.push({width: currentColWidth, height: currentColHeight}); // previous column size + left += currentColWidth + padding; + col++; + top = 0; currentColWidth = currentColHeight = 0; } @@ -207,7 +219,8 @@ export class Legend extends Element { currentColHeight += fontSize + padding; // Store the hitbox width and height here. Final position will be updated in `draw` - hitboxes[i] = {left: 0, top: 0, width: itemWidth, height: itemHeight}; + hitboxes[i] = {left, top, col, width: itemWidth, height: itemHeight}; + top += itemHeight + padding; }); totalWidth += currentColWidth; @@ -216,6 +229,40 @@ export class Legend extends Element { return totalWidth; } + adjustHitBoxes() { + const me = this; + if (!me.options.display) { + return; + } + const titleHeight = me._computeTitleHeight(); + const {legendHitBoxes: hitboxes, options: {align, labels: {padding}}} = me; + if (this.isHorizontal()) { + let row = 0; + let left = _alignStartEnd(align, me.left + padding, me.right - me.lineWidths[row]); + for (const hitbox of hitboxes) { + if (row !== hitbox.row) { + row = hitbox.row; + left = _alignStartEnd(align, me.left + padding, me.right - me.lineWidths[row]); + } + hitbox.top += me.top + titleHeight + padding; + hitbox.left = left; + left += hitbox.width + padding; + } + } else { + let col = 0; + let top = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - me.columnSizes[col].height); + for (const hitbox of hitboxes) { + if (hitbox.col !== col) { + col = hitbox.col; + top = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - me.columnSizes[col].height); + } + hitbox.top = top; + hitbox.left += me.left + padding; + top += hitbox.height + padding; + } + } + } + isHorizontal() { return this.options.position === 'top' || this.options.position === 'bottom'; } @@ -237,7 +284,7 @@ export class Legend extends Element { */ _draw() { const me = this; - const {options: opts, columnSizes, lineWidths, ctx, legendHitBoxes} = me; + const {options: opts, columnSizes, lineWidths, ctx} = me; const {align, labels: labelOpts} = opts; const defaultColor = defaults.color; const rtlHelper = getRtlAdapter(opts.rtl, me.left, me.width); @@ -358,9 +405,6 @@ export class Legend extends Element { drawLegendBox(realX, y, legendItem); - legendHitBoxes[i].left = rtlHelper.leftForLtr(realX, legendHitBoxes[i].width); - legendHitBoxes[i].top = y; - x = _textX(textAlign, x + boxWidth + halfFontSize, me.right); // Fill the actual label @@ -476,13 +520,14 @@ export class Legend extends Element { if (e.type === 'mousemove') { const previous = me._hoveredItem; - if (previous && previous !== hoveredItem) { + const sameItem = itemsEqual(previous, hoveredItem); + if (previous && !sameItem) { call(opts.onLeave, [e, previous, me], me); } me._hoveredItem = hoveredItem; - if (hoveredItem) { + if (hoveredItem && !sameItem) { call(opts.onHover, [e, hoveredItem, me], me); } } else if (hoveredItem) { @@ -533,7 +578,9 @@ export default { // The labels need to be built after datasets are updated to ensure that colors // and other styling are correct. See https://github.com/chartjs/Chart.js/issues/6968 afterUpdate(chart) { - chart.legend.buildLabels(); + const legend = chart.legend; + legend.buildLabels(); + legend.adjustHitBoxes(); },
false
Other
chartjs
Chart.js
fe406bf717444def6e7a6cb10b8e9120d9679450.json
Legend: Ignore replayed events (#8749)
src/plugins/plugin.legend.js
@@ -538,7 +538,9 @@ export default { afterEvent(chart, args) { - chart.legend.handleEvent(args.event); + if (!args.replay) { + chart.legend.handleEvent(args.event); + } }, defaults: {
false
Other
chartjs
Chart.js
d6972abd48b4012d38a7b0cc7133aee25ea90112.json
Add note about inline plugins and registration (#8741)
docs/docs/developers/plugins.md
@@ -27,6 +27,8 @@ var chart3 = new Chart(ctx, {}); Plugins can also be defined directly in the chart `plugins` config (a.k.a. *inline plugins*): +> Note: *inline* plugins are not registered. Some plugins require registering, i.e. can't be used *inline*. + ```javascript var chart = new Chart(ctx, { plugins: [{
false
Other
chartjs
Chart.js
37080c9a8db7b4ff94bebcee3df990127d8d263a.json
Add comments for finding registry hook calls (#8734)
src/core/core.registry.js
@@ -151,9 +151,9 @@ export class Registry { */ _exec(method, registry, component) { const camelMethod = _capitalize(method); - call(component['before' + camelMethod], [], component); + call(component['before' + camelMethod], [], component); // beforeRegister / beforeUnregister registry[method](component); - call(component['after' + camelMethod], [], component); + call(component['after' + camelMethod], [], component); // afterRegister / afterUnregister } /**
false
Other
chartjs
Chart.js
54c5b7a084576d9ccf8f7b6af943b04415e0c321.json
Add a convenience alias for scale options (#8732) * Add a convenience alias for scale options Closes #8731 * Add an automated test * Use parameter for a more realistic test
types/index.esm.d.ts
@@ -3248,6 +3248,9 @@ export type ScaleOptionsByType<TScale extends ScaleType = ScaleType> = { [key in ScaleType]: { type: key } & ScaleTypeRegistry[key]['options'] }[TScale] ; +// Convenience alias for creating and manipulating scale options in user code +export type ScaleOptions<TScale extends ScaleType = ScaleType> = DeepPartial<ScaleOptionsByType<TScale>>; + export type DatasetChartOptions<TType extends ChartType = ChartType> = { [key in TType]: { datasets: ChartTypeRegistry[key]['datasetOptions'];
true
Other
chartjs
Chart.js
54c5b7a084576d9ccf8f7b6af943b04415e0c321.json
Add a convenience alias for scale options (#8732) * Add a convenience alias for scale options Closes #8731 * Add an automated test * Use parameter for a more realistic test
types/tests/scales/options.ts
@@ -1,4 +1,4 @@ -import { Chart } from '../../index.esm'; +import { Chart, ScaleOptions } from '../../index.esm'; const chart = new Chart('test', { type: 'bar', @@ -30,3 +30,29 @@ const chart = new Chart('test', { } } }); + +function makeChartScale(range: number): ScaleOptions<'linear'> { + return { + type: 'linear', + min: 0, + suggestedMax: range, + }; +} + +const composedChart = new Chart('test2', { + type: 'bar', + data: { + labels: ['a'], + datasets: [{ + data: [1], + }, { + type: 'line', + data: [{ x: 1, y: 1 }] + }] + }, + options: { + scales: { + x: makeChartScale(10) + } + } +});
true
Other
chartjs
Chart.js
3671c01c26cf96da4d94c01991421cf6734669db.json
Distribute types as is (#8720) I had initially seen some oddities around type augmentation for type definitions in subdirectories of `types`, and using Rollup seemed to help with that. However, now that all of Chart.js's main types are directly under `types`, there seems to be no need for this. This simplifies the build process, since it no longer needs to use rollup-plugin-dts. It also improves some third-party tools. For example, I'm in the habit of using WebStorm's "Go To Declaration or Usages" hotkey with third-party TypeScript definitions as a quick way of getting more information about an API. With the Rollup-generate types, that works poorly; WebStorm goes to the imported-and-re-exported symbol within the barely-readable machine-generated dist/chart.esm.d.ts file, and I have to navigate two more hops to find the actual definitions.
MAINTAINING.md
@@ -13,7 +13,7 @@ Chart.js relies on [Travis CI](https://travis-ci.org/) to automate the library [ Creation of this tag triggers a new build: * `Chart.js.zip` package is generated, containing dist files and examples -* `dist/*.js` and `Chart.js.zip` are attached to the GitHub release (downloads) +* `dist/*.js`, `types/*.ts`, and `Chart.js.zip` are attached to the GitHub release (downloads) * A new npm package is published on [npmjs](https://www.npmjs.com/package/chart.js) Finally, [cdnjs](https://cdnjs.com/libraries/Chart.js) is automatically updated from the npm release.
true
Other
chartjs
Chart.js
3671c01c26cf96da4d94c01991421cf6734669db.json
Distribute types as is (#8720) I had initially seen some oddities around type augmentation for type definitions in subdirectories of `types`, and using Rollup seemed to help with that. However, now that all of Chart.js's main types are directly under `types`, there seems to be no need for this. This simplifies the build process, since it no longer needs to use rollup-plugin-dts. It also improves some third-party tools. For example, I'm in the habit of using WebStorm's "Go To Declaration or Usages" hotkey with third-party TypeScript definitions as a quick way of getting more information about an API. With the Rollup-generate types, that works poorly; WebStorm goes to the imported-and-re-exported symbol within the barely-readable machine-generated dist/chart.esm.d.ts file, and I have to navigate two more hops to find the actual definitions.
package-lock.json
@@ -3581,40 +3581,6 @@ "rollup-pluginutils": "^2.8.2" } }, - "rollup-plugin-dts": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/rollup-plugin-dts/-/rollup-plugin-dts-3.0.1.tgz", - "integrity": "sha512-sdTsd0tEIV1b5Bio1k4Ei3N4/7jbwcVRdlYotGYdJOKR59JH7DzqKTSCbfaKPzuAcKTp7k317z2BzYJ3bkhDTw==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.12.13", - "magic-string": "^0.25.7" - }, - "dependencies": { - "@babel/code-frame": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz", - "integrity": "sha512-HV1Cm0Q3ZrpCR93tkWOYiuYIgLxZXZFVG2VgK+MBWjUqZTundupbfx2aXarXuw5Ko5aMcjtJgbSs4vUGBS5v6g==", - "dev": true, - "optional": true, - "requires": { - "@babel/highlight": "^7.12.13" - } - }, - "@babel/highlight": { - "version": "7.13.10", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.13.10.tgz", - "integrity": "sha512-5aPpe5XQPzflQrFwL1/QoeHkP2MsA4JCntcXHRhEsdsfPVkvPi2w7Qix4iV7t5S/oC9OodGrggd8aco1g3SZFg==", - "dev": true, - "optional": true, - "requires": { - "@babel/helper-validator-identifier": "^7.12.11", - "chalk": "^2.0.0", - "js-tokens": "^4.0.0" - } - } - } - }, "rollup-plugin-istanbul": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/rollup-plugin-istanbul/-/rollup-plugin-istanbul-3.0.0.tgz",
true
Other
chartjs
Chart.js
3671c01c26cf96da4d94c01991421cf6734669db.json
Distribute types as is (#8720) I had initially seen some oddities around type augmentation for type definitions in subdirectories of `types`, and using Rollup seemed to help with that. However, now that all of Chart.js's main types are directly under `types`, there seems to be no need for this. This simplifies the build process, since it no longer needs to use rollup-plugin-dts. It also improves some third-party tools. For example, I'm in the habit of using WebStorm's "Go To Declaration or Usages" hotkey with third-party TypeScript definitions as a quick way of getting more information about an API. With the Rollup-generate types, that works poorly; WebStorm goes to the imported-and-re-exported symbol within the barely-readable machine-generated dist/chart.esm.d.ts file, and I have to navigate two more hops to find the actual definitions.
package.json
@@ -8,7 +8,7 @@ "unpkg": "dist/chart.min.js", "main": "dist/chart.js", "module": "dist/chart.esm.js", - "types": "dist/chart.esm.d.ts", + "types": "types/chart.esm.d.ts", "keywords": [ "canvas", "charts", @@ -28,9 +28,9 @@ "auto/**/*.js", "auto/**/*.d.ts", "dist/*.js", - "dist/*.d.ts", "dist/chunks/*.js", - "dist/chunks/*.d.ts", + "types/*.d.ts", + "types/helpers/*.d.ts", "helpers/**/*.js", "helpers/**/*.d.ts" ], @@ -84,7 +84,6 @@ "rollup": "^2.41.4", "rollup-plugin-analyzer": "^4.0.0", "rollup-plugin-cleanup": "^3.2.1", - "rollup-plugin-dts": "^3.0.1", "rollup-plugin-istanbul": "^3.0.0", "rollup-plugin-terser": "^7.0.2", "typedoc": "^0.20.32",
true
Other
chartjs
Chart.js
3671c01c26cf96da4d94c01991421cf6734669db.json
Distribute types as is (#8720) I had initially seen some oddities around type augmentation for type definitions in subdirectories of `types`, and using Rollup seemed to help with that. However, now that all of Chart.js's main types are directly under `types`, there seems to be no need for this. This simplifies the build process, since it no longer needs to use rollup-plugin-dts. It also improves some third-party tools. For example, I'm in the habit of using WebStorm's "Go To Declaration or Usages" hotkey with third-party TypeScript definitions as a quick way of getting more information about an API. With the Rollup-generate types, that works poorly; WebStorm goes to the imported-and-re-exported symbol within the barely-readable machine-generated dist/chart.esm.d.ts file, and I have to navigate two more hops to find the actual definitions.
rollup.config.js
@@ -1,6 +1,5 @@ const analyze = require('rollup-plugin-analyzer'); const cleanup = require('rollup-plugin-cleanup'); -const dts = require('rollup-plugin-dts').default; const json = require('@rollup/plugin-json'); const resolve = require('@rollup/plugin-node-resolve').default; const terser = require('rollup-plugin-terser').terser; @@ -11,10 +10,6 @@ const inputESM = { 'dist/chart.esm': 'src/index.esm.js', 'dist/helpers.esm': 'src/helpers/index.js' }; -const inputESMTypings = { - 'dist/chart.esm': 'types/index.esm.d.ts', - 'dist/helpers.esm': 'types/helpers/index.d.ts' -}; const banner = `/*! * Chart.js v${pkg.version} @@ -84,20 +79,4 @@ module.exports = [ indent: false, }, }, - // ES6 Typings builds - // dist/chart.esm.d.ts - // helpers/*.d.ts - { - input: inputESMTypings, - plugins: [ - dts() - ], - output: { - dir: './', - chunkFileNames: 'dist/chunks/[name].ts', - banner, - format: 'esm', - indent: false, - }, - } ];
true
Other
chartjs
Chart.js
3671c01c26cf96da4d94c01991421cf6734669db.json
Distribute types as is (#8720) I had initially seen some oddities around type augmentation for type definitions in subdirectories of `types`, and using Rollup seemed to help with that. However, now that all of Chart.js's main types are directly under `types`, there seems to be no need for this. This simplifies the build process, since it no longer needs to use rollup-plugin-dts. It also improves some third-party tools. For example, I'm in the habit of using WebStorm's "Go To Declaration or Usages" hotkey with third-party TypeScript definitions as a quick way of getting more information about an API. With the Rollup-generate types, that works poorly; WebStorm goes to the imported-and-re-exported symbol within the barely-readable machine-generated dist/chart.esm.d.ts file, and I have to navigate two more hops to find the actual definitions.
types/index.esm.d.ts
@@ -1,17 +1,3 @@ -/** - * Top-level type definitions. These are processed by Rollup and rollup-plugin-dts - * to make a combined .d.ts file under dist; that way, all of the type definitions - * appear directly within the "chart.js" module; that matches the layout of the - * distributed chart.esm.js bundle and means that users of Chart.js can easily use - * module augmentation to extend Chart.js's types and plugins within their own - * code, like so: - * - * @example - * declare module "chart.js" { - * // Add types here - * } - */ - import { DeepPartial, DistributiveArray, UnionToIntersection } from './utils'; import { TimeUnit } from './adapters';
true
Other
chartjs
Chart.js
7fff21b3bb2f240237a3349ad0e207ea2774507a.json
Add defaults.describe/defaults.override typings (#8716)
types/index.esm.d.ts
@@ -623,6 +623,9 @@ export interface Defaults extends CoreChartOptions<ChartType>, ElementChartOptio set(scope: string, values: AnyObject): AnyObject; get(scope: string): AnyObject; + describe(scope: string, values: AnyObject): AnyObject; + override(scope: string, values: AnyObject): AnyObject; + /** * Routes the named defaults to fallback to another scope/name. * This routing is useful when those target values, like defaults.color, are changed runtime.
false
Other
chartjs
Chart.js
39140cca2e36333abb7ab4309a6b4ee2c52e4d95.json
Remove the comparrison doc page (#8709)
docs/docs/notes/comparison.md
@@ -1,33 +0,0 @@ ---- -title: Comparison with Other Libraries ---- - -Library Features - -| Feature | Chart.js | D3 | HighCharts | Chartist | -| ------- | -------- | --- | ---------- | -------- | -| Completely Free | &check; | &check; | | &check; | -| Canvas | &check; | | | | -| SVG | | &check; | &check; | &check; | -| Built-in Charts | &check; | | &check; | &check; | -| 8+ Chart Types | &check; | &check; | &check; | | -| Extendable to Custom Charts | &check; | &check; | | | -| Supports Modern Browsers | &check; | &check; | &check; | &check; | -| Extensive Documentation | &check; | &check; | &check; | &check; | -| Open Source | &check; | &check; | | &check; | - -Built in Chart Types - -| Type | Chart.js | HighCharts | Chartist | -| ---- | -------- | ---------- | -------- | -| Combined Types | &check; | &check; | | -| Line | &check; | &check; | &check; | -| Bar | &check; | &check; | &check; | -| Horizontal Bar | &check; | &check; | &check; | -| Pie/Doughnut | &check; | &check; | &check; | -| Polar Area | &check; | &check; | | -| Radar | &check; | | | -| Scatter | &check; | &check; | &check; | -| Bubble | &check; | | | -| Gauges | | &check; | | -| Maps (Heat/Tree/etc.) | | &check; | |
true
Other
chartjs
Chart.js
39140cca2e36333abb7ab4309a6b4ee2c52e4d95.json
Remove the comparrison doc page (#8709)
docs/sidebars.js
@@ -83,7 +83,6 @@ module.exports = { 'developers/publishing' ], 'Additional Notes': [ - 'notes/comparison', { type: 'link', label: 'Extensions',
true
Other
chartjs
Chart.js
bbf298f4614c058e2ec86329566a56bfcd8bc685.json
formatters.numeric: verify ticks length (#8705) * formatters.numeric: verify ticks length * use tickValue as fallback delta, add tests * cc, chore
src/core/core.ticks.js
@@ -8,45 +8,40 @@ import {log10} from '../helpers/helpers.math'; */ const formatters = { /** - * Formatter for value labels - * @method Chart.Ticks.formatters.values - * @param value the value to display - * @return {string|string[]} the label to display - */ + * Formatter for value labels + * @method Chart.Ticks.formatters.values + * @param value the value to display + * @return {string|string[]} the label to display + */ values(value) { return isArray(value) ? value : '' + value; }, /** - * Formatter for numeric ticks - * @method Chart.Ticks.formatters.numeric - * @param tickValue {number} the value to be formatted - * @param index {number} the position of the tickValue parameter in the ticks array - * @param ticks {object[]} the list of ticks being converted - * @return {string} string representation of the tickValue parameter - */ + * Formatter for numeric ticks + * @method Chart.Ticks.formatters.numeric + * @param tickValue {number} the value to be formatted + * @param index {number} the position of the tickValue parameter in the ticks array + * @param ticks {object[]} the list of ticks being converted + * @return {string} string representation of the tickValue parameter + */ numeric(tickValue, index, ticks) { if (tickValue === 0) { return '0'; // never show decimal places for 0 } const locale = this.chart.options.locale; - - // all ticks are small or there huge numbers; use scientific notation - const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value)); let notation; - if (maxTick < 1e-4 || maxTick > 1e+15) { - notation = 'scientific'; - } + let delta = tickValue; // This is used when there are less than 2 ticks as the tick interval. - // Figure out how many digits to show - // The space between the first two ticks might be smaller than normal spacing - let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value; + if (ticks.length > 1) { + // all ticks are small or there huge numbers; use scientific notation + const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value)); + if (maxTick < 1e-4 || maxTick > 1e+15) { + notation = 'scientific'; + } - // If we have a number like 2.5 as the delta, figure out how many decimal places we need - if (Math.abs(delta) > 1 && tickValue !== Math.floor(tickValue)) { - // not an integer - delta = tickValue - Math.floor(tickValue); + delta = calculateDelta(tickValue, ticks); } const logDelta = log10(Math.abs(delta)); @@ -56,27 +51,43 @@ const formatters = { Object.assign(options, this.options.ticks.format); return formatNumber(tickValue, locale, options); + }, + + + /** + * Formatter for logarithmic ticks + * @method Chart.Ticks.formatters.logarithmic + * @param tickValue {number} the value to be formatted + * @param index {number} the position of the tickValue parameter in the ticks array + * @param ticks {object[]} the list of ticks being converted + * @return {string} string representation of the tickValue parameter + */ + logarithmic(tickValue, index, ticks) { + if (tickValue === 0) { + return '0'; + } + const remain = tickValue / (Math.pow(10, Math.floor(log10(tickValue)))); + if (remain === 1 || remain === 2 || remain === 5) { + return formatters.numeric.call(this, tickValue, index, ticks); + } + return ''; } + }; -/** - * Formatter for logarithmic ticks - * @method Chart.Ticks.formatters.logarithmic - * @param tickValue {number} the value to be formatted - * @param index {number} the position of the tickValue parameter in the ticks array - * @param ticks {object[]} the list of ticks being converted - * @return {string} string representation of the tickValue parameter - */ -formatters.logarithmic = function(tickValue, index, ticks) { - if (tickValue === 0) { - return '0'; - } - const remain = tickValue / (Math.pow(10, Math.floor(log10(tickValue)))); - if (remain === 1 || remain === 2 || remain === 5) { - return formatters.numeric.call(this, tickValue, index, ticks); + +function calculateDelta(tickValue, ticks) { + // Figure out how many digits to show + // The space between the first two ticks might be smaller than normal spacing + let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value; + + // If we have a number like 2.5 as the delta, figure out how many decimal places we need + if (Math.abs(delta) > 1 && tickValue !== Math.floor(tickValue)) { + // not an integer + delta = tickValue - Math.floor(tickValue); } - return ''; -}; + return delta; +} /** * Namespace to hold static tick generation functions
true
Other
chartjs
Chart.js
bbf298f4614c058e2ec86329566a56bfcd8bc685.json
formatters.numeric: verify ticks length (#8705) * formatters.numeric: verify ticks length * use tickValue as fallback delta, add tests * cc, chore
test/specs/core.ticks.tests.js
@@ -96,4 +96,13 @@ describe('Test tick generators', function() { expect(xLabels).toEqual(['0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']); expect(yLabels).toEqual(['0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']); }); + + describe('formatters.numeric', function() { + it('should not fail on empty or 1 item array', function() { + const scale = {chart: {options: {locale: 'en'}}, options: {ticks: {format: {}}}}; + expect(Chart.Ticks.formatters.numeric.apply(scale, [1, 0, []])).toEqual('1'); + expect(Chart.Ticks.formatters.numeric.apply(scale, [1, 0, [{value: 1}]])).toEqual('1'); + expect(Chart.Ticks.formatters.numeric.apply(scale, [1, 0, [{value: 1}, {value: 1.01}]])).toEqual('1.00'); + }); + }); });
true
Other
chartjs
Chart.js
d79b5a3d60bba39a285f4eb878839dee2b4027da.json
Add typings for throttled and debounce (#8689) * Add typings for throttled and debounce * Review feedback * args for fn too * one more
types/helpers/helpers.extras.d.ts
@@ -4,3 +4,20 @@ export function fontString(pixelSize: number, fontStyle: string, fontFamily: str * Request animation polyfill */ export function requestAnimFrame(cb: () => void): void; + +/** + * Throttles calling `fn` once per animation frame + * Latest argments are used on the actual call + * @param {function} fn + * @param {*} thisArg + * @param {function} [updateFn] + */ +export function throttled(fn: (...args: any[]) => void, thisArg: any, updateFn?: (...args: any[]) => any[]): (...args: any[]) => void; + +/** + * Debounces calling `fn` for `delay` ms + * @param {function} fn - Function to call. No arguments are passed. + * @param {number} delay - Delay in ms. 0 = immediate invocation. + * @returns {function} + */ +export function debounce(fn: () => void, delay: number): () => number;
false
Other
chartjs
Chart.js
7e8e7f01374d2c3e7633d4acf1d1e38928ba2a07.json
Generalize toTRBL and toTRBLCorners (#8686)
src/helpers/helpers.options.js
@@ -38,7 +38,22 @@ export function toLineHeight(value, size) { } const numberOrZero = v => +v || 0; -const numberOrZero2 = (v1, v2) => numberOrZero(valueOrDefault(v1, v2)); + +function readValueToProps(value, props) { + const ret = {}; + const objProps = isObject(props); + const keys = objProps ? Object.keys(props) : props; + const read = isObject(value) + ? objProps + ? prop => valueOrDefault(value[prop], value[props[prop]]) + : prop => value[prop] + : () => value; + + for (const prop of keys) { + ret[prop] = numberOrZero(read(prop)); + } + return ret; +} /** * Converts the given value into a TRBL object. @@ -49,24 +64,7 @@ const numberOrZero2 = (v1, v2) => numberOrZero(valueOrDefault(v1, v2)); * @since 3.0.0 */ export function toTRBL(value) { - let t, r, b, l; - - if (isObject(value)) { - const {x, y} = value; - t = numberOrZero2(value.top, y); - r = numberOrZero2(value.right, x); - b = numberOrZero2(value.bottom, y); - l = numberOrZero2(value.left, x); - } else { - t = r = b = l = numberOrZero(value); - } - - return { - top: t, - right: r, - bottom: b, - left: l - }; + return readValueToProps(value, {top: 'y', right: 'x', bottom: 'y', left: 'x'}); } /** @@ -77,23 +75,7 @@ export function toTRBL(value) { * @since 3.0.0 */ export function toTRBLCorners(value) { - let tl, tr, bl, br; - - if (isObject(value)) { - tl = numberOrZero(value.topLeft); - tr = numberOrZero(value.topRight); - bl = numberOrZero(value.bottomLeft); - br = numberOrZero(value.bottomRight); - } else { - tl = tr = bl = br = numberOrZero(value); - } - - return { - topLeft: tl, - topRight: tr, - bottomLeft: bl, - bottomRight: br - }; + return readValueToProps(value, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']); } /**
false
Other
chartjs
Chart.js
537064be9cc221b9c68a68cdc7f4e823eabda52e.json
Modify Scale typing (#8681)
types/index.esm.d.ts
@@ -1260,10 +1260,9 @@ export interface Scale<O extends CoreScaleOptions = CoreScaleOptions> extends El isFullSize(): boolean; } -export const Scale: { - prototype: Scale; - new <O extends CoreScaleOptions = CoreScaleOptions>(cfg: AnyObject): Scale<O>; -}; +export declare class Scale { + constructor(cfg: {id: string, type: string, ctx: CanvasRenderingContext2D, chart: Chart}); +} export interface ScriptableScaleContext { chart: Chart;
true
Other
chartjs
Chart.js
537064be9cc221b9c68a68cdc7f4e823eabda52e.json
Modify Scale typing (#8681)
types/tests/extensions/scale.ts
@@ -0,0 +1,48 @@ +import { AnyObject } from '../../basic'; +import { CartesianScaleOptions, Chart, Scale } from '../../index.esm'; + +export type TestScaleOptions = CartesianScaleOptions & { + testOption?: boolean +} + +export class TestScale<O extends TestScaleOptions = TestScaleOptions> extends Scale<O> { + static id: 'test'; + + getBasePixel(): number { + return 0; + } + + testMethod(): void { + // + } +} + +declare module '../../index.esm' { + interface CartesianScaleTypeRegistry { + test: { + options: TestScaleOptions + } + } +} + + +Chart.register(TestScale); + +const chart = new Chart('id', { + type: 'line', + data: { + datasets: [] + }, + options: { + scales: { + x: { + type: 'test', + position: 'bottom', + testOption: true, + min: 0 + } + } + } +}); + +Chart.unregister([TestScale]);
true
Other
chartjs
Chart.js
185f83aca3f01020616468d98be05ad8b6a774eb.json
Update doc samples for changed file name (#7447)
docs/docusaurus.config.js
@@ -9,7 +9,7 @@ module.exports = { organizationName: 'chartjs', // Usually your GitHub org/user name. projectName: 'chartjs.github.io', // Usually your repo name. plugins: [require.resolve('@docusaurus/plugin-google-analytics')], - scripts: ['https://www.chartjs.org/dist/VERSION/Chart.min.js'], + scripts: ['https://www.chartjs.org/dist/VERSION/chart.min.js'], themes: [require.resolve('@docusaurus/theme-live-codeblock')], themeConfig: { algolia: {
false
Other
chartjs
Chart.js
553ae385a8382609ca30d53a91aa3ea4b0db6745.json
Consistency: Use lower case for instances (#7436) Consistency: Use lover case for instances
src/core/core.animations.js
@@ -1,4 +1,4 @@ -import Animator from './core.animator'; +import animator from './core.animator'; import Animation from './core.animation'; import defaults from './core.defaults'; import {noop, isObject} from '../helpers/helpers.core'; @@ -206,7 +206,7 @@ export default class Animations { const animations = this._createAnimations(target, values); if (animations.length) { - Animator.add(this._chart, animations); + animator.add(this._chart, animations); return true; } }
true
Other
chartjs
Chart.js
553ae385a8382609ca30d53a91aa3ea4b0db6745.json
Consistency: Use lower case for instances (#7436) Consistency: Use lover case for instances
src/core/core.animator.js
@@ -20,6 +20,7 @@ function drawFPS(chart, count, date, lastDate) { /** * Please use the module's default export which provides a singleton instance + * Note: class is export for typedoc */ export class Animator { constructor() {
true
Other
chartjs
Chart.js
553ae385a8382609ca30d53a91aa3ea4b0db6745.json
Consistency: Use lower case for instances (#7436) Consistency: Use lover case for instances
src/core/core.controller.js
@@ -1,5 +1,5 @@ /* eslint-disable import/no-namespace, import/namespace */ -import {default as Animator} from './core.animator'; +import animator from './core.animator'; import * as controllers from '../controllers'; import defaults from './core.defaults'; import Interaction from './core.interaction'; @@ -254,8 +254,8 @@ class Chart { return; } - Animator.listen(me, 'complete', onAnimationsComplete); - Animator.listen(me, 'progress', onAnimationProgress); + animator.listen(me, 'complete', onAnimationsComplete); + animator.listen(me, 'progress', onAnimationProgress); me._initialize(); if (me.attached) { @@ -305,7 +305,7 @@ class Chart { } stop() { - Animator.stop(this); + animator.stop(this); return this; } @@ -665,9 +665,9 @@ class Chart { callCallback(animationOptions && animationOptions.onComplete, [], me); }; - if (Animator.has(me)) { - if (me.attached && !Animator.running(me)) { - Animator.start(me); + if (animator.has(me)) { + if (me.attached && !animator.running(me)) { + animator.start(me); } } else { me.draw(); @@ -910,7 +910,7 @@ class Chart { let i, ilen; me.stop(); - Animator.remove(me); + animator.remove(me); // dataset controllers need to cleanup associated data for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
true
Other
chartjs
Chart.js
553ae385a8382609ca30d53a91aa3ea4b0db6745.json
Consistency: Use lower case for instances (#7436) Consistency: Use lover case for instances
src/core/index.js
@@ -1,14 +1,14 @@ export {default as _adapters} from './core.adapters'; export {default as Animation} from './core.animation'; export {default as Animations} from './core.animations'; -export {default as Animator} from './core.animator'; +export {default as animator} from './core.animator'; export {default as Chart} from './core.controller'; export {default as DatasetController} from './core.datasetController'; -export {default as Defaults} from './core.defaults'; +export {default as defaults} from './core.defaults'; export {default as Element} from './core.element'; export {default as Interaction} from './core.interaction'; -export {default as Layouts} from './core.layouts'; -export {default as Plugins} from './core.plugins'; +export {default as layouts} from './core.layouts'; +export {default as plugins} from './core.plugins'; export {default as Scale} from './core.scale'; export {default as ScaleService} from './core.scaleService'; export {default as Ticks} from './core.ticks';
true
Other
chartjs
Chart.js
553ae385a8382609ca30d53a91aa3ea4b0db6745.json
Consistency: Use lower case for instances (#7436) Consistency: Use lover case for instances
src/index.js
@@ -8,7 +8,7 @@ import Chart from './core/core.controller'; import helpers from './helpers/index'; import _adapters from './core/core.adapters'; import Animation from './core/core.animation'; -import {default as Animator} from './core/core.animator'; +import animator from './core/core.animator'; import animationService from './core/core.animations'; import * as controllers from './controllers'; import DatasetController from './core/core.datasetController'; @@ -26,7 +26,7 @@ import Ticks from './core/core.ticks'; Chart.helpers = helpers; Chart._adapters = _adapters; Chart.Animation = Animation; -Chart.Animator = Animator; +Chart.animator = animator; Chart.animationService = animationService; Chart.controllers = controllers; Chart.DatasetController = DatasetController;
true
Other
chartjs
Chart.js
7752566a482f71f9905e794f9ef962bb8634127a.json
Remove missing setDataVisibility for documentation (#7437)
docs/docs/developers/api.md
@@ -159,15 +159,6 @@ chart.setDatasetVisibility(1, false); // hides dataset at index 1 chart.update(); // chart now renders with dataset hidden ``` -## setDataVisibility(datasetIndex, index, visibility) - -Like [setDatasetVisibility](#setdatasetvisibility) except that it hides only a single item in the dataset. **Note** this only applies to polar area and doughnut charts at the moment. It will have no affect on line, bar, radar, or scatter charts. - -```javascript -chart.setDataVisibility(0, 2, false); // hides the item in dataset 0, at index 2 -chart.update(); // chart now renders with item hidden -``` - ## toggleDataVisibility(index) Toggles the visibility of an item in all datasets. A dataset needs to explicitly support this feature for it to have an effect. From internal chart types, doughnut / pie and polar area use this.
false
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
babel.config.json
@@ -3,27 +3,9 @@ "@babel/preset-env" ], "plugins": [ - "@babel/plugin-proposal-class-properties", "@babel/plugin-transform-object-assign" ], "env": { - "es6": { - "presets": [ - [ - "@babel/preset-env", - { - "targets": { - "esmodules": true - }, - "modules": false, - "useBuiltIns": false - } - ] - ], - "plugins": [ - "@babel/plugin-proposal-class-properties" - ] - }, "test": { "plugins": [ "istanbul"
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
docs/docs/developers/axes.md
@@ -5,9 +5,9 @@ title: New Axes Axes in Chart.js can be individually extended. Axes should always derive from `Chart.Scale` but this is not a mandatory requirement. ```javascript -let MyScale = Chart.Scale.extend({ +class MyScale extends Chart.Scale{ /* extensions ... */ -}); +} MyScale.id = 'myScale'; MyScale.defaults = defaultConfigObject;
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
docs/docs/developers/charts.md
@@ -5,10 +5,11 @@ title: New Charts Chart.js 2.0 introduces the concept of controllers for each dataset. Like scales, new controllers can be written as needed. ```javascript -Chart.controllers.MyType = Chart.DatasetController.extend({ +class MyType extends Chart.DatasetController { -}); +} +Chart.controllers.MyType = MyType; // Now we can create a new instance of our chart, using the Chart.js API new Chart(ctx, { @@ -67,6 +68,7 @@ The following methods may optionally be overridden by derived dataset controller Extending or replacing an existing controller type is easy. Simply replace the constructor for one of the built in types with your own. The built in controller types are: + * `Chart.controllers.line` * `Chart.controllers.bar` * `Chart.controllers.horizontalBar` @@ -84,10 +86,10 @@ For example, to derive a new chart type that extends from a bubble chart, you wo Chart.defaults.derivedBubble = Chart.defaults.bubble; // I think the recommend using Chart.controllers.bubble.extend({ extensions here }); -var custom = Chart.controllers.bubble.extend({ - draw: function(ease) { +class Custom extends Chart.controllers.bubble { + draw() { // Call super method first - Chart.controllers.bubble.prototype.draw.call(this, ease); + 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(); @@ -105,7 +107,7 @@ var custom = Chart.controllers.bubble.extend({ // Stores the controller so that the chart initialization routine can look it up with // Chart.controllers[type] -Chart.controllers.derivedBubble = custom; +Chart.controllers.derivedBubble = Custom; // Now we can create and use our new chart type new Chart(ctx, {
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
package-lock.json
@@ -92,20 +92,6 @@ "semver": "^5.5.0" } }, - "@babel/helper-create-class-features-plugin": { - "version": "7.9.6", - "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.9.6.tgz", - "integrity": "sha512-6N9IeuyHvMBRyjNYOMJHrhwtu4WJMrYf8hVbEHD3pbbbmNOk1kmXSQs7bA4dYDUaIx4ZEzdnvo6NwC3WHd/Qow==", - "dev": true, - "requires": { - "@babel/helper-function-name": "^7.9.5", - "@babel/helper-member-expression-to-functions": "^7.8.3", - "@babel/helper-optimise-call-expression": "^7.8.3", - "@babel/helper-plugin-utils": "^7.8.3", - "@babel/helper-replace-supers": "^7.9.6", - "@babel/helper-split-export-declaration": "^7.8.3" - } - }, "@babel/helper-create-regexp-features-plugin": { "version": "7.8.8", "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.8.8.tgz", @@ -325,16 +311,6 @@ "@babel/plugin-syntax-async-generators": "^7.8.0" } }, - "@babel/plugin-proposal-class-properties": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.8.3.tgz", - "integrity": "sha512-EqFhbo7IosdgPgZggHaNObkmO1kNUe3slaKu54d5OWvy+p9QIKOzK1GAEpAIsZtWVtPXUHSMcT4smvDrCfY4AA==", - "dev": true, - "requires": { - "@babel/helper-create-class-features-plugin": "^7.8.3", - "@babel/helper-plugin-utils": "^7.8.3" - } - }, "@babel/plugin-proposal-dynamic-import": { "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-dynamic-import/-/plugin-proposal-dynamic-import-7.8.3.tgz",
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
package.json
@@ -34,7 +34,6 @@ }, "devDependencies": { "@babel/core": "^7.9.6", - "@babel/plugin-proposal-class-properties": "^7.8.3", "@babel/plugin-transform-object-assign": "^7.8.3", "@babel/preset-env": "^7.9.6", "@rollup/plugin-commonjs": "^11.1.0",
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
rollup.config.js
@@ -74,7 +74,6 @@ module.exports = [ plugins: [ json(), resolve(), - babel({envName: 'es6'}), cleanup({ sourcemap: true }) @@ -92,7 +91,6 @@ module.exports = [ plugins: [ json(), resolve(), - babel({envName: 'es6'}), terser({ output: { preamble: banner
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/core/core.controller.js
@@ -172,16 +172,7 @@ function getCanvas(item) { return item; } -export default class Chart { - - static version = version; - - /** - * NOTE(SB) We actually don't use this container anymore but we need to keep it - * for backward compatibility. Though, it can still be useful for plugins that - * would need to work on multiple charts?! - */ - static instances = {}; +class Chart { constructor(item, config) { const me = this; @@ -1128,3 +1119,14 @@ export default class Chart { return changed; } } + +Chart.version = version; + +/** + * NOTE(SB) We actually don't use this container anymore but we need to keep it + * for backward compatibility. Though, it can still be useful for plugins that + * would need to work on multiple charts?! + */ +Chart.instances = {}; + +export default Chart;
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/core/core.datasetController.js
@@ -1,5 +1,5 @@ import Animations from './core.animations'; -import {isObject, inherits, merge, _merger, isArray, valueOrDefault, mergeIf, arrayEquals} from '../helpers/helpers.core'; +import {isObject, merge, _merger, isArray, valueOrDefault, mergeIf, arrayEquals} from '../helpers/helpers.core'; import {resolve} from '../helpers/helpers.options'; import {getHoverColor} from '../helpers/helpers.color'; import {sign} from '../helpers/helpers.math'; @@ -218,8 +218,6 @@ function getFirstScaleId(chart, axis) { export default class DatasetController { - static extend = inherits; - /** * @param {Chart} chart * @param {number} datasetIndex
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/core/core.element.js
@@ -1,10 +1,7 @@ -import {inherits} from '../helpers/helpers.core'; import {isNumber} from '../helpers/helpers.math'; export default class Element { - static extend = inherits; - constructor() { this.x = undefined; this.y = undefined;
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/elements/element.arc.js
@@ -84,9 +84,7 @@ function drawBorder(ctx, vm, arc) { ctx.stroke(); } -export default class Arc extends Element { - - static _type = 'arc'; +class Arc extends Element { constructor(cfg) { super(); @@ -197,3 +195,7 @@ export default class Arc extends Element { ctx.restore(); } } + +Arc._type = 'arc'; + +export default Arc;
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/elements/element.line.js
@@ -196,9 +196,7 @@ function _getInterpolationMethod(options) { return _pointInLine; } -export default class Line extends Element { - - static _type = 'line'; +class Line extends Element { constructor(cfg) { super(); @@ -357,3 +355,7 @@ export default class Line extends Element { ctx.restore(); } } + +Line._type = 'line'; + +export default Line;
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/elements/element.point.js
@@ -17,9 +17,7 @@ defaults.set('elements', { } }); -export default class Point extends Element { - - static _type = 'point'; +class Point extends Element { constructor(cfg) { super(); @@ -86,3 +84,7 @@ export default class Point extends Element { return options.radius + options.hitRadius; } } + +Point._type = 'point'; + +export default Point;
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/elements/element.rectangle.js
@@ -124,9 +124,7 @@ function inRange(bar, x, y, useFinalPosition) { && (skipY || y >= bounds.top && y <= bounds.bottom); } -export default class Rectangle extends Element { - - static _type = 'rectangle'; +class Rectangle extends Element { constructor(cfg) { super(); @@ -187,3 +185,7 @@ export default class Rectangle extends Element { return axis === 'x' ? this.width / 2 : this.height / 2; } } + +Rectangle._type = 'rectangle'; + +export default Rectangle;
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/helpers/helpers.core.js
@@ -293,33 +293,6 @@ export function _mergerIf(key, target, source) { } } -/** - * Basic javascript inheritance based on the model created in Backbone.js - */ -export function inherits(extensions) { - // eslint-disable-next-line no-invalid-this - const me = this; - const ChartElement = (extensions && Object.prototype.hasOwnProperty.call(extensions, 'constructor')) ? extensions.constructor : function() { - // eslint-disable-next-line prefer-rest-params - return me.apply(this, arguments); - }; - - const Surrogate = function() { - this.constructor = ChartElement; - }; - - Surrogate.prototype = me.prototype; - ChartElement.prototype = new Surrogate(); - ChartElement.extend = inherits; - - if (extensions) { - Object.assign(ChartElement.prototype, extensions); - } - - ChartElement.__super__ = me.prototype; - return ChartElement; -} - /** * @private */
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/scales/scale.category.js
@@ -3,11 +3,7 @@ import Scale from '../core/core.scale'; const defaultConfig = { }; -export default class CategoryScale extends Scale { - - static id = 'category'; - // INTERNAL: static default options, registered in src/index.js - static defaults = defaultConfig; +class CategoryScale extends Scale { constructor(cfg) { super(cfg); @@ -109,3 +105,10 @@ export default class CategoryScale extends Scale { return this.bottom; } } + +CategoryScale.id = 'category'; + +// INTERNAL: default options, registered in src/index.js +CategoryScale.defaults = defaultConfig; + +export default CategoryScale;
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/scales/scale.linear.js
@@ -8,11 +8,7 @@ const defaultConfig = { } }; -export default class LinearScale extends LinearScaleBase { - - static id = 'linear'; - // INTERNAL: static default options, registered in src/index.js - static defaults = defaultConfig; +class LinearScale extends LinearScaleBase { determineDataLimits() { const me = this; @@ -66,3 +62,10 @@ export default class LinearScale extends LinearScaleBase { return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange; } } + +LinearScale.id = 'linear'; + +// INTERNAL: default options, registered in src/index.js +LinearScale.defaults = defaultConfig; + +export default LinearScale;
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/scales/scale.logarithmic.js
@@ -57,11 +57,7 @@ const defaultConfig = { } }; -export default class LogarithmicScale extends Scale { - - static id = 'logarithmic'; - // INTERNAL: static default options, registered in src/index.js - static defaults = defaultConfig; +class LogarithmicScale extends Scale { constructor(cfg) { super(cfg); @@ -187,3 +183,10 @@ export default class LogarithmicScale extends Scale { return Math.pow(10, me._startValue + decimal * me._valueRange); } } + +LogarithmicScale.id = 'logarithmic'; + +// INTERNAL: default options, registered in src/index.js +LogarithmicScale.defaults = defaultConfig; + +export default LogarithmicScale;
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/scales/scale.radialLinear.js
@@ -289,11 +289,7 @@ function numberOrZero(param) { return isNumber(param) ? param : 0; } -export default class RadialLinearScale extends LinearScaleBase { - - static id = 'radialLinear'; - // INTERNAL: static default options, registered in src/index.js - static defaults = defaultConfig; +class RadialLinearScale extends LinearScaleBase { constructor(cfg) { super(cfg); @@ -547,3 +543,10 @@ export default class RadialLinearScale extends LinearScaleBase { */ drawTitle() {} } + +RadialLinearScale.id = 'radialLinear'; + +// INTERNAL: default options, registered in src/index.js +RadialLinearScale.defaults = defaultConfig; + +export default RadialLinearScale;
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
src/scales/scale.time.js
@@ -542,11 +542,7 @@ const defaultConfig = { } }; -export default class TimeScale extends Scale { - - static id = 'time'; - // INTERNAL: static default options, registered in src/index.js - static defaults = defaultConfig; +class TimeScale extends Scale { /** * @param {object} props @@ -812,3 +808,10 @@ export default class TimeScale extends Scale { return capacity > 0 ? capacity : 1; } } + +TimeScale.id = 'time'; + +// INTERNAL: default options, registered in src/index.js +TimeScale.defaults = defaultConfig; + +export default TimeScale;
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
test/specs/core.scale.tests.js
@@ -454,15 +454,15 @@ describe('Core.scale', function() { }); it('should default to one layer for custom scales', function() { - var customScale = Chart.Scale.extend({ - draw: function() {}, - convertTicksToLabels: function() { + class CustomScale extends Chart.Scale { + draw() {} + convertTicksToLabels() { return ['tick']; } - }); - customScale.id = 'customScale'; - customScale.defaults = {}; - Chart.scaleService.registerScale(customScale); + } + CustomScale.id = 'customScale'; + CustomScale.defaults = {}; + Chart.scaleService.registerScale(CustomScale); var chart = window.acquireChart({ type: 'line',
true
Other
chartjs
Chart.js
f472a3f9a761c876b56771a107a7f0f36924c3cb.json
Remove proposal and obsolete features (#7425)
test/specs/helpers.core.tests.js
@@ -429,57 +429,4 @@ describe('Chart.helpers.core', function() { expect(output.o.a).not.toBe(a1); }); }); - - describe('extend', function() { - it('should merge object properties in target and return target', function() { - var target = {a: 'abc', b: 56}; - var object = {b: 0, c: [2, 5, 6]}; - var result = Object.assign(target, object); - - expect(result).toBe(target); - expect(target).toEqual({a: 'abc', b: 0, c: [2, 5, 6]}); - }); - it('should merge multiple objects properties in target', function() { - var target = {a: 0, b: 1}; - var o0 = {a: 2, c: 3, d: 4}; - var o1 = {a: 5, c: 6}; - var o2 = {a: 7, e: 8}; - - Object.assign(target, o0, o1, o2); - - expect(target).toEqual({a: 7, b: 1, c: 6, d: 4, e: 8}); - }); - it('should not deeply merge object properties in target', function() { - var target = {a: {b: 0, c: 1}}; - var object = {a: {b: 2, d: 3}}; - - Object.assign(target, object); - - expect(target).toEqual({a: {b: 2, d: 3}}); - expect(target.a).toBe(object.a); - }); - }); - - describe('inherits', function() { - it('should return a derived class', function() { - var A = function() {}; - A.prototype.p0 = 41; - A.prototype.p1 = function() { - return '42'; - }; - - A.inherits = helpers.inherits; - var B = A.inherits({p0: 43, p2: [44]}); - var C = A.inherits({p3: 45, p4: [46]}); - var b = new B(); - - expect(b instanceof A).toBeTruthy(); - expect(b instanceof B).toBeTruthy(); - expect(b instanceof C).toBeFalsy(); - - expect(b.p0).toBe(43); - expect(b.p1()).toBe('42'); - expect(b.p2).toEqual([44]); - }); - }); });
true
Other
chartjs
Chart.js
94763bff351236ff5936280737b594701f0528b8.json
Fix chart resizing issue (#7297) (#7298) Fix chart resizing issue
src/platform/platform.dom.js
@@ -236,7 +236,15 @@ function createResizeObserver(chart, type, listener) { // @ts-ignore until https://github.com/microsoft/TypeScript/issues/37861 implemented const observer = new ResizeObserver(entries => { const entry = entries[0]; - resize(entry.contentRect.width, entry.contentRect.height); + const width = entry.contentRect.width; + const height = entry.contentRect.height; + // When its container's display is set to 'none' the callback will be called with a + // size of (0, 0), which will cause the chart to lost its original height, so skip + // resizing in such case. + if (width === 0 && height === 0) { + return; + } + resize(width, height); }); observer.observe(container); return observer;
true
Other
chartjs
Chart.js
94763bff351236ff5936280737b594701f0528b8.json
Fix chart resizing issue (#7297) (#7298) Fix chart resizing issue
test/specs/core.controller.tests.js
@@ -365,6 +365,59 @@ describe('Chart', function() { wrapper.style.width = '455px'; }); + it('should restore the original size when parent became invisible', function(done) { + var chart = acquireChart({ + options: { + responsive: true, + maintainAspectRatio: false + } + }, { + canvas: { + style: '' + }, + wrapper: { + style: 'width: 300px; height: 350px; position: relative' + } + }); + + waitForResize(chart, function() { + expect(chart).toBeChartOfSize({ + dw: 300, dh: 350, + rw: 300, rh: 350, + }); + + var original = chart.resize; + chart.resize = function() { + fail('resize should not have been called'); + }; + + var wrapper = chart.canvas.parentNode; + wrapper.style.display = 'none'; + + setTimeout(function() { + expect(wrapper.clientWidth).toEqual(0); + expect(wrapper.clientHeight).toEqual(0); + + expect(chart).toBeChartOfSize({ + dw: 300, dh: 350, + rw: 300, rh: 350, + }); + + chart.resize = original; + + waitForResize(chart, function() { + expect(chart).toBeChartOfSize({ + dw: 300, dh: 350, + rw: 300, rh: 350, + }); + + done(); + }); + wrapper.style.display = 'block'; + }, 200); + }); + }); + it('should resize the canvas when parent is RTL and width changes', function(done) { var chart = acquireChart({ options: {
true
Other
chartjs
Chart.js
5cf054ef257ce28407ae5c13bcc0b5f8c0199c80.json
Use full URL for TypeDocs (#7380) Use full URL for TypeDocs
docs/docusaurus.config.js
@@ -1,96 +1,96 @@ +/* eslint-disable import/no-commonjs */ // VERSION replaced by deploy script module.exports = { - title: 'Chart.js', - tagline: 'Open source HTML5 Charts for your website', - url: 'https://chartjs.org', - baseUrl: '/docs/VERSION/', - favicon: 'img/favicon.ico', - organizationName: 'chartjs', // Usually your GitHub org/user name. - projectName: 'chartjs.github.io', // Usually your repo name. - plugins: ['@docusaurus/plugin-google-analytics'], - scripts: ['https://www.chartjs.org/dist/VERSION/Chart.min.js'], - themes: ['@docusaurus/theme-live-codeblock'], - themeConfig: { - algolia: { - apiKey: 'd7ee00a3cbaaf3c33e28ad1c274e7ba6', - indexName: 'chartjs', - algoliaOptions: { - facetFilters: [`version:VERSION`], - } - }, - googleAnalytics: { - trackingID: 'UA-28909194-3', - // Optional fields. - anonymizeIP: true, // Should IPs be anonymized? - }, - disableDarkMode: true, // Would need to implement for Charts embedded in docs - navbar: { - title: 'Chart.js', - logo: { - alt: 'Chart.js Logo', - src: 'img/logo.svg', - }, - }, - footer: { - style: 'dark', - links: [ - { - title: 'Other Docs', - items: [ - { - label: 'Samples', - href: 'https://www.chartjs.org/samples/VERSION/', - }, - { - label: 'v2 Docs', - href: 'https://www.chartjs.org/docs/2.9.3/', - }, - ], - }, - { - title: 'Community', - items: [ - { - label: 'Slack', - href: 'https://chartjs-slack.herokuapp.com/', - }, - { - label: 'Stack Overflow', - href: 'https://stackoverflow.com/questions/tagged/chart.js', - }, - ], - }, - { - title: 'Developers', - items: [ - { - label: 'GitHub', - href: 'https://github.com/chartjs/Chart.js', - }, - { - label: 'Contributing', - to: 'developers/contributing', - }, - ], - }, - ], - copyright: `Copyright © ${new Date().getFullYear()} Chart.js contributors.`, - }, - }, - presets: [ - [ - '@docusaurus/preset-classic', - { - docs: { - sidebarPath: require.resolve('./sidebars.js'), - routeBasePath: '', - editUrl: - 'https://github.com/chartjs/Chart.js/edit/master/docs/', - }, - theme: { - customCss: require.resolve('./src/css/custom.css'), - }, - }, - ], - ], + title: 'Chart.js', + tagline: 'Open source HTML5 Charts for your website', + url: 'https://chartjs.org', + baseUrl: '/docs/VERSION/', + favicon: 'img/favicon.ico', + organizationName: 'chartjs', // Usually your GitHub org/user name. + projectName: 'chartjs.github.io', // Usually your repo name. + plugins: ['@docusaurus/plugin-google-analytics'], + scripts: ['https://www.chartjs.org/dist/VERSION/Chart.min.js'], + themes: ['@docusaurus/theme-live-codeblock'], + themeConfig: { + algolia: { + apiKey: 'd7ee00a3cbaaf3c33e28ad1c274e7ba6', + indexName: 'chartjs', + algoliaOptions: { + facetFilters: ['version:VERSION'], + } + }, + googleAnalytics: { + trackingID: 'UA-28909194-3', + // Optional fields. + anonymizeIP: true, // Should IPs be anonymized? + }, + disableDarkMode: true, // Would need to implement for Charts embedded in docs + navbar: { + title: 'Chart.js', + logo: { + alt: 'Chart.js Logo', + src: 'img/logo.svg', + }, + }, + footer: { + style: 'dark', + links: [ + { + title: 'Other Docs', + items: [ + { + label: 'Samples', + href: 'https://www.chartjs.org/samples/VERSION/', + }, + { + label: 'v2 Docs', + href: 'https://www.chartjs.org/docs/2.9.3/', + }, + ], + }, + { + title: 'Community', + items: [ + { + label: 'Slack', + href: 'https://chartjs-slack.herokuapp.com/', + }, + { + label: 'Stack Overflow', + href: 'https://stackoverflow.com/questions/tagged/chart.js', + }, + ], + }, + { + title: 'Developers', + items: [ + { + label: 'GitHub', + href: 'https://github.com/chartjs/Chart.js', + }, + { + label: 'Contributing', + to: 'developers/contributing', + }, + ], + }, + ], + copyright: `Copyright © ${new Date().getFullYear()} Chart.js contributors.`, + }, + }, + presets: [ + [ + '@docusaurus/preset-classic', + { + docs: { + sidebarPath: require.resolve('./sidebars.js'), + routeBasePath: '', + editUrl: 'https://github.com/chartjs/Chart.js/edit/master/docs/', + }, + theme: { + customCss: require.resolve('./src/css/custom.css'), + }, + }, + ], + ], };
true
Other
chartjs
Chart.js
5cf054ef257ce28407ae5c13bcc0b5f8c0199c80.json
Use full URL for TypeDocs (#7380) Use full URL for TypeDocs
docs/sidebars.js
@@ -1,82 +1,85 @@ +const pkg = require('../package.json'); +const docsVersion = pkg.version.indexOf('-') > -1 ? 'next' : 'latest'; + module.exports = { - someSidebar: { - Introduction: ['index'], - 'Getting Started': [ - 'getting-started/index', - 'getting-started/installation', - 'getting-started/integration', - 'getting-started/usage', - 'getting-started/v3-migration' - ], - General: [ - 'general/data-structures', - 'general/accessibility', - 'general/responsive', - 'general/device-pixel-ratio', - {Interactions: ['general/interactions/index', 'general/interactions/events', 'general/interactions/modes']}, - 'general/options', - 'general/colors', - 'general/fonts', - 'general/performance' - ], - Configuration: [ - 'configuration/index', - 'configuration/animations', - 'configuration/layout', - 'configuration/legend', - 'configuration/title', - 'configuration/tooltip', - 'configuration/elements' - ], - 'Chart Types': [ - 'charts/line', - 'charts/bar', - 'charts/radar', - 'charts/doughnut', - 'charts/polar', - 'charts/bubble', - 'charts/scatter', - 'charts/area', - 'charts/mixed' - ], - Axes:[ - 'axes/index', - { Cartesian: [ - 'axes/cartesian/index', - 'axes/cartesian/category', - 'axes/cartesian/linear', - 'axes/cartesian/logarithmic', - 'axes/cartesian/time' - ]}, - { Radial: [ - 'axes/radial/index', - 'axes/radial/linear' - ]}, - 'axes/labelling', - 'axes/styling' - ], - Developers: [ - 'developers/index', - 'developers/api', - { - type: 'link', - label: 'TypeDoc', - href: 'typedoc/index.html' - }, - 'developers/updates', - 'developers/plugins', - 'developers/charts', - 'developers/axes', - 'developers/contributing' - ], - 'Additional Notes':[ - 'notes/comparison', - { - type: 'link', - label: 'Extensions', - href: 'https://github.com/chartjs/awesome' - }, - 'notes/license' - ] - }, + someSidebar: { + Introduction: ['index'], + 'Getting Started': [ + 'getting-started/index', + 'getting-started/installation', + 'getting-started/integration', + 'getting-started/usage', + 'getting-started/v3-migration' + ], + General: [ + 'general/data-structures', + 'general/accessibility', + 'general/responsive', + 'general/device-pixel-ratio', + {Interactions: ['general/interactions/index', 'general/interactions/events', 'general/interactions/modes']}, + 'general/options', + 'general/colors', + 'general/fonts', + 'general/performance' + ], + Configuration: [ + 'configuration/index', + 'configuration/animations', + 'configuration/layout', + 'configuration/legend', + 'configuration/title', + 'configuration/tooltip', + 'configuration/elements' + ], + 'Chart Types': [ + 'charts/line', + 'charts/bar', + 'charts/radar', + 'charts/doughnut', + 'charts/polar', + 'charts/bubble', + 'charts/scatter', + 'charts/area', + 'charts/mixed' + ], + Axes: [ + 'axes/index', + {Cartesian: [ + 'axes/cartesian/index', + 'axes/cartesian/category', + 'axes/cartesian/linear', + 'axes/cartesian/logarithmic', + 'axes/cartesian/time' + ]}, + {Radial: [ + 'axes/radial/index', + 'axes/radial/linear' + ]}, + 'axes/labelling', + 'axes/styling' + ], + Developers: [ + 'developers/index', + 'developers/api', + { + type: 'link', + label: 'TypeDoc', + href: 'https://chartjs.org/docs/' + docsVersion + '/typedoc/' + }, + 'developers/updates', + 'developers/plugins', + 'developers/charts', + 'developers/axes', + 'developers/contributing' + ], + 'Additional Notes': [ + 'notes/comparison', + { + type: 'link', + label: 'Extensions', + href: 'https://github.com/chartjs/awesome' + }, + 'notes/license' + ] + }, };
true
Other
chartjs
Chart.js
37633c221ac41b4a4cbcc5093b2049c83bee19b8.json
Remove default export from controllers/index (#7388) Remove default export from controllers/index
src/controllers/index.js
@@ -1,25 +1,9 @@ -import bar from './controller.bar'; -import bubble from './controller.bubble'; -import doughnut from './controller.doughnut'; -import horizontalBar from './controller.horizontalBar'; -import line from './controller.line'; -import polarArea from './controller.polarArea'; -import pie from './controller.pie'; -import radar from './controller.radar'; -import scatter from './controller.scatter'; - -// NOTE export a map in which the key represents the controller type, not -// the class, and so must be CamelCase in order to be correctly retrieved -// by the controller in core.controller.js (`controllers[meta.type]`). - -export default { - bar, - bubble, - doughnut, - horizontalBar, - line, - polarArea, - pie, - radar, - scatter -}; +export {default as bar} from './controller.bar'; +export {default as bubble} from './controller.bubble'; +export {default as doughnut} from './controller.doughnut'; +export {default as horizontalBar} from './controller.horizontalBar'; +export {default as line} from './controller.line'; +export {default as polarArea} from './controller.polarArea'; +export {default as pie} from './controller.pie'; +export {default as radar} from './controller.radar'; +export {default as scatter} from './controller.scatter';
true
Other
chartjs
Chart.js
37633c221ac41b4a4cbcc5093b2049c83bee19b8.json
Remove default export from controllers/index (#7388) Remove default export from controllers/index
src/core/core.controller.js
@@ -1,5 +1,6 @@ -import Animator from './core.animator'; -import controllers from '../controllers/index'; +/* eslint-disable import/no-namespace, import/namespace */ +import {default as Animator} from './core.animator'; +import * as controllers from '../controllers'; import defaults from './core.defaults'; import Interaction from './core.interaction'; import layouts from './core.layouts';
true
Other
chartjs
Chart.js
37633c221ac41b4a4cbcc5093b2049c83bee19b8.json
Remove default export from controllers/index (#7388) Remove default export from controllers/index
src/index.js
@@ -8,9 +8,9 @@ import Chart from './core/core.controller'; import helpers from './helpers/index'; import _adapters from './core/core.adapters'; import Animation from './core/core.animation'; -import Animator from './core/core.animator'; +import {default as Animator} from './core/core.animator'; import animationService from './core/core.animations'; -import controllers from './controllers/index'; +import * as controllers from './controllers'; import DatasetController from './core/core.datasetController'; import defaults from './core/core.defaults'; import Element from './core/core.element';
true
Other
chartjs
Chart.js
5920858513710276dc33d33a172ce67bd4215d13.json
Remove default export from plugins/index (#7389)
src/index.js
@@ -42,11 +42,11 @@ Chart.scaleService = scaleService; Chart.Ticks = Ticks; // Register built-in scales -import * as scales from './scales/index'; +import * as scales from './scales'; Object.keys(scales).forEach(key => Chart.scaleService.registerScale(scales[key])); // Loading built-in plugins -import plugins from './plugins/index'; +import * as plugins from './plugins'; for (const k in plugins) { if (Object.prototype.hasOwnProperty.call(plugins, k)) { Chart.plugins.register(plugins[k]);
true
Other
chartjs
Chart.js
5920858513710276dc33d33a172ce67bd4215d13.json
Remove default export from plugins/index (#7389)
src/plugins/index.js
@@ -1,11 +1,4 @@ -import filler from './plugin.filler'; -import legend from './plugin.legend'; -import title from './plugin.title'; -import tooltip from './plugin.tooltip'; - -export default { - filler, - legend, - title, - tooltip -}; +export {default as filler} from './plugin.filler'; +export {default as legend} from './plugin.legend'; +export {default as title} from './plugin.title'; +export {default as tooltip} from './plugin.tooltip';
true
Other
chartjs
Chart.js
087ba88da6d76f9aea00608923eac8ba1e6679f5.json
Add index to core (#7390)
src/core/index.js
@@ -0,0 +1,14 @@ +export {default as _adapters} from './core.adapters'; +export {default as Animation} from './core.animation'; +export {default as Animations} from './core.animations'; +export {default as Animator} from './core.animator'; +export {default as Chart} from './core.controller'; +export {default as DatasetController} from './core.datasetController'; +export {default as Defaults} from './core.defaults'; +export {default as Element} from './core.element'; +export {default as Interaction} from './core.interaction'; +export {default as Layouts} from './core.layouts'; +export {default as Plugins} from './core.plugins'; +export {default as Scale} from './core.scale'; +export {default as ScaleService} from './core.scaleService'; +export {default as Ticks} from './core.ticks';
false
Other
chartjs
Chart.js
7ac61441a63efdcf1e3f1951832970c9ac1f1f60.json
Run tests in series to avoid timeouts (#7392)
gulpfile.js
@@ -31,7 +31,7 @@ gulp.task('lint-js', lintJsTask); gulp.task('lint', gulp.parallel('lint-html', 'lint-js')); gulp.task('tsc', typescriptTask); gulp.task('unittest', unittestTask); -gulp.task('test', gulp.parallel('lint', 'tsc', 'unittest')); +gulp.task('test', gulp.series('lint', 'tsc', 'unittest')); gulp.task('library-size', librarySizeTask); gulp.task('module-sizes', moduleSizesTask); gulp.task('size', gulp.parallel('library-size', 'module-sizes'));
false
Other
chartjs
Chart.js
cfb5fba527cd93b596329fb05079e320b6586701.json
Delay animations until attached (#7370) * Delay animations until attached * Detect container detachment
docs/docs/getting-started/v3-migration.md
@@ -141,7 +141,6 @@ options: { Animation system was completely rewritten in Chart.js v3. Each property can now be animated separately. Please see [animations](../configuration/animations.md) docs for details. - #### Customizability * `custom` attribute of elements was removed. Please use scriptable options @@ -169,6 +168,7 @@ Animation system was completely rewritten in Chart.js v3. Each property can now While the end-user migration for Chart.js 3 is fairly straight-forward, the developer migration can be more complicated. Please reach out for help in the #dev [Slack](https://chartjs-slack.herokuapp.com/) channel if tips on migrating would be helpful. Some of the biggest things that have changed: + * There is a completely rewritten and more performant animation system. * `Element._model` and `Element._view` are no longer used and properties are now set directly on the elements. You will have to use the method `getProps` to access these properties inside most methods such as `inXRange`/`inYRange` and `getCenterPoint`. Please take a look at [the Chart.js-provided elements](https://github.com/chartjs/Chart.js/tree/master/src/elements) for examples. * When building the elements in a controller, it's now suggested to call `updateElement` to provide the element properties. There are also methods such as `getSharedOptions` and `includeOptions` that have been added to skip redundant computation. Please take a look at [the Chart.js-provided controllers](https://github.com/chartjs/Chart.js/tree/master/src/controllers) for examples. @@ -187,6 +187,7 @@ A few changes were made to controllers that are more straight-forward, but will The following properties and methods were removed: #### Chart + * `Chart.borderWidth` * `Chart.chart.chart` * `Chart.Bar`. New charts are created via `new Chart` and providing the appropriate `type` parameter @@ -411,3 +412,4 @@ The APIs listed in this section have changed in signature or behaviour from vers * `Chart.platform` is no longer the platform object used by charts. Every chart instance now has a separate platform instance. * `Chart.platforms` is an object that contains two usable platform classes, `BasicPlatform` and `DomPlatform`. It also contains `BasePlatform`, a class that all platforms must extend from. * If the canvas passed in is an instance of `OffscreenCanvas`, the `BasicPlatform` is automatically used. +* `isAttached` method was added to platform.
true
Other
chartjs
Chart.js
cfb5fba527cd93b596329fb05079e320b6586701.json
Delay animations until attached (#7370) * Delay animations until attached * Detect container detachment
src/core/core.controller.js
@@ -212,7 +212,7 @@ export default class Chart { this.active = undefined; this.lastActive = []; this._lastEvent = undefined; - /** @type {{resize?: function}} */ + /** @type {{attach?: function, detach?: function, resize?: function}} */ this._listeners = {}; this._sortedMetasets = []; this._updating = false; @@ -221,6 +221,7 @@ export default class Chart { this.$plugins = undefined; this.$proxies = {}; this._hiddenIndices = {}; + this.attached = true; // Add the chart instance to the global namespace Chart.instances[me.id] = me; @@ -248,7 +249,9 @@ export default class Chart { Animator.listen(me, 'progress', onAnimationProgress); me._initialize(); - me.update(); + if (me.attached) { + me.update(); + } } /** @@ -341,7 +344,8 @@ export default class Chart { options.onResize(me, newSize); } - me.update('resize'); + // Only apply 'resize' mode if we are attached, else do a regular update. + me.update(me.attached && 'resize'); } } @@ -664,7 +668,7 @@ export default class Chart { }; if (Animator.has(me)) { - if (!Animator.running(me)) { + if (me.attached && !Animator.running(me)) { Animator.start(me); } } else { @@ -938,24 +942,57 @@ export default class Chart { bindEvents() { const me = this; const listeners = me._listeners; + const platform = me.platform; + + const _add = (type, listener) => { + platform.addEventListener(me, type, listener); + listeners[type] = listener; + }; + const _remove = (type, listener) => { + if (listeners[type]) { + platform.removeEventListener(me, type, listener); + delete listeners[type]; + } + }; + let listener = function(e) { me._eventHandler(e); }; - helpers.each(me.options.events, (type) => { - me.platform.addEventListener(me, type, listener); - listeners[type] = listener; - }); + helpers.each(me.options.events, (type) => _add(type, listener)); if (me.options.responsive) { - listener = function(width, height) { + listener = (width, height) => { if (me.canvas) { me.resize(false, width, height); } }; - me.platform.addEventListener(me, 'resize', listener); - listeners.resize = listener; + let detached; // eslint-disable-line prefer-const + const attached = () => { + _remove('attach', attached); + + me.resize(); + me.attached = true; + + _add('resize', listener); + _add('detach', detached); + }; + + detached = () => { + me.attached = false; + + _remove('resize', listener); + _add('attach', attached); + }; + + if (platform.isAttached(me.canvas)) { + attached(); + } else { + detached(); + } + } else { + me.attached = true; } }
true
Other
chartjs
Chart.js
cfb5fba527cd93b596329fb05079e320b6586701.json
Delay animations until attached (#7370) * Delay animations until attached * Detect container detachment
src/helpers/helpers.dom.js
@@ -126,13 +126,14 @@ export function getRelativePosition(evt, chart) { }; } +function fallbackIfNotValid(measure, fallback) { + return typeof measure === 'number' ? measure : fallback; +} + export function getMaximumWidth(domNode) { const container = _getParentNode(domNode); if (!container) { - if (typeof domNode.clientWidth === 'number') { - return domNode.clientWidth; - } - return domNode.width; + return fallbackIfNotValid(domNode.clientWidth, domNode.width); } const clientWidth = container.clientWidth; @@ -147,10 +148,7 @@ export function getMaximumWidth(domNode) { export function getMaximumHeight(domNode) { const container = _getParentNode(domNode); if (!container) { - if (typeof domNode.clientHeight === 'number') { - return domNode.clientHeight; - } - return domNode.height; + return fallbackIfNotValid(domNode.clientHeight, domNode.height); } const clientHeight = container.clientHeight;
true
Other
chartjs
Chart.js
cfb5fba527cd93b596329fb05079e320b6586701.json
Delay animations until attached (#7370) * Delay animations until attached * Detect container detachment
src/platform/platform.base.js
@@ -48,6 +48,14 @@ export default class BasePlatform { getDevicePixelRatio() { return 1; } + + /** + * @param {HTMLCanvasElement} canvas + * @returns {boolean} true if the canvas is attached to the platform, false if not. + */ + isAttached(canvas) { // eslint-disable-line no-unused-vars + return true; + } } /**
true
Other
chartjs
Chart.js
cfb5fba527cd93b596329fb05079e320b6586701.json
Delay animations until attached (#7370) * Delay animations until attached * Detect container detachment
src/platform/platform.dom.js
@@ -172,51 +172,17 @@ function throttled(fn, thisArg) { }; } -/** - * Watch for resize of `element`. - * Calling `fn` is limited to once per animation frame - * @param {Element} element - The element to monitor - * @param {function} fn - Callback function to call when resized - */ -function watchForResize(element, fn) { - const resize = throttled((width, height) => { - const w = element.clientWidth; - fn(width, height); - if (w < element.clientWidth) { - // If the container size shrank during chart resize, let's assume - // scrollbar appeared. So we resize again with the scrollbar visible - - // effectively making chart smaller and the scrollbar hidden again. - // Because we are inside `throttled`, and currently `ticking`, scroll - // events are ignored during this whole 2 resize process. - // If we assumed wrong and something else happened, we are resizing - // twice in a frame (potential performance issue) - fn(); - } - }, window); - - // @ts-ignore until https://github.com/Microsoft/TypeScript/issues/28502 implemented - const observer = new ResizeObserver(entries => { - const entry = entries[0]; - resize(entry.contentRect.width, entry.contentRect.height); - }); - observer.observe(element); - return observer; -} - -/** - * Detect attachment of `element` or its direct `parent` to DOM - * @param {Element} element - The element to watch for - * @param {function} fn - Callback function to call when attachment is detected - * @return {MutationObserver} - */ -function watchForAttachment(element, fn) { +function createAttachObserver(chart, type, listener) { + const canvas = chart.canvas; + const container = canvas && _getParentNode(canvas); + const element = container || canvas; const observer = new MutationObserver(entries => { const parent = _getParentNode(element); entries.forEach(entry => { for (let i = 0; i < entry.addedNodes.length; i++) { const added = entry.addedNodes[i]; if (added === element || added === parent) { - fn(entry.target); + listener(entry.target); } } }); @@ -225,79 +191,76 @@ function watchForAttachment(element, fn) { return observer; } -/** - * Watch for detachment of `element` from its direct `parent`. - * @param {Element} element - The element to watch - * @param {function} fn - Callback function to call when detached. - * @return {MutationObserver=} - */ -function watchForDetachment(element, fn) { - const parent = _getParentNode(element); - if (!parent) { +function createDetachObserver(chart, type, listener) { + const canvas = chart.canvas; + const container = canvas && _getParentNode(canvas); + if (!container) { return; } const observer = new MutationObserver(entries => { entries.forEach(entry => { for (let i = 0; i < entry.removedNodes.length; i++) { - if (entry.removedNodes[i] === element) { - fn(); + if (entry.removedNodes[i] === canvas) { + listener(); break; } } }); }); - observer.observe(parent, {childList: true}); + observer.observe(container, {childList: true}); return observer; } -/** - * @param {{ [x: string]: any; resize?: any; detach?: MutationObserver; attach?: MutationObserver; }} proxies - * @param {string} type - */ -function removeObserver(proxies, type) { - const observer = proxies[type]; +function createResizeObserver(chart, type, listener) { + const canvas = chart.canvas; + const container = canvas && _getParentNode(canvas); + if (!container) { + return; + } + const resize = throttled((width, height) => { + const w = container.clientWidth; + listener(width, height); + if (w < container.clientWidth) { + // If the container size shrank during chart resize, let's assume + // scrollbar appeared. So we resize again with the scrollbar visible - + // effectively making chart smaller and the scrollbar hidden again. + // Because we are inside `throttled`, and currently `ticking`, scroll + // events are ignored during this whole 2 resize process. + // If we assumed wrong and something else happened, we are resizing + // twice in a frame (potential performance issue) + listener(); + } + }, window); + + // @ts-ignore until https://github.com/microsoft/TypeScript/issues/37861 implemented + const observer = new ResizeObserver(entries => { + const entry = entries[0]; + resize(entry.contentRect.width, entry.contentRect.height); + }); + observer.observe(container); + return observer; +} + +function releaseObserver(canvas, type, observer) { if (observer) { observer.disconnect(); - proxies[type] = undefined; } } -/** - * @param {{ resize?: any; detach?: MutationObserver; attach?: MutationObserver; }} proxies - */ -function unlistenForResize(proxies) { - removeObserver(proxies, 'attach'); - removeObserver(proxies, 'detach'); - removeObserver(proxies, 'resize'); -} +function createProxyAndListen(chart, type, listener) { + const canvas = chart.canvas; + const proxy = throttled((event) => { + // This case can occur if the chart is destroyed while waiting + // for the throttled function to occur. We prevent crashes by checking + // for a destroyed chart + if (chart.ctx !== null) { + listener(fromNativeEvent(event, chart)); + } + }, chart); -/** - * @param {HTMLCanvasElement} canvas - * @param {{ resize?: any; detach?: MutationObserver; attach?: MutationObserver; }} proxies - * @param {function} listener - */ -function listenForResize(canvas, proxies, listener) { - // Helper for recursing when canvas is detached from it's parent - const detached = () => listenForResize(canvas, proxies, listener); - - // First make sure all observers are removed - unlistenForResize(proxies); - // Then check if we are attached - const container = _getParentNode(canvas); - if (container) { - // The canvas is attached (or was immediately re-attached when called through `detached`) - proxies.resize = watchForResize(container, listener); - proxies.detach = watchForDetachment(canvas, detached); - } else { - // The canvas is detached - proxies.attach = watchForAttachment(canvas, () => { - // The canvas was attached. - removeObserver(proxies, 'attach'); - const parent = _getParentNode(canvas); - proxies.resize = watchForResize(parent, listener); - proxies.detach = watchForDetachment(canvas, detached); - }); - } + addListener(canvas, type, proxy); + + return proxy; } /** @@ -379,22 +342,14 @@ export default class DomPlatform extends BasePlatform { // Can have only one listener per type, so make sure previous is removed this.removeEventListener(chart, type); - const canvas = chart.canvas; const proxies = chart.$proxies || (chart.$proxies = {}); - if (type === 'resize') { - return listenForResize(canvas, proxies, listener); - } - - const proxy = proxies[type] = throttled((event) => { - // This case can occur if the chart is destroyed while waiting - // for the throttled function to occur. We prevent crashes by checking - // for a destroyed chart - if (chart.ctx !== null) { - listener(fromNativeEvent(event, chart)); - } - }, chart); - - addListener(canvas, type, proxy); + const handlers = { + attach: createAttachObserver, + detach: createDetachObserver, + resize: createResizeObserver + }; + const handler = handlers[type] || createProxyAndListen; + proxies[type] = handler(chart, type, listener); } @@ -405,21 +360,32 @@ export default class DomPlatform extends BasePlatform { removeEventListener(chart, type) { const canvas = chart.canvas; const proxies = chart.$proxies || (chart.$proxies = {}); - - if (type === 'resize') { - return unlistenForResize(proxies); - } - const proxy = proxies[type]; + if (!proxy) { return; } - removeListener(canvas, type, proxy); + const handlers = { + attach: releaseObserver, + detach: releaseObserver, + resize: releaseObserver + }; + const handler = handlers[type] || removeListener; + handler(canvas, type, proxy); proxies[type] = undefined; } getDevicePixelRatio() { return window.devicePixelRatio; } + + + /** + * @param {HTMLCanvasElement} canvas + */ + isAttached(canvas) { + const container = _getParentNode(canvas); + return !!(container && _getParentNode(container)); + } }
true
Other
chartjs
Chart.js
cfb5fba527cd93b596329fb05079e320b6586701.json
Delay animations until attached (#7370) * Delay animations until attached * Detect container detachment
test/specs/platform.dom.tests.js
@@ -1,3 +1,5 @@ +import {DomPlatform} from '../../src/platform/platforms'; + describe('Platform.dom', function() { describe('context acquisition', function() { @@ -405,4 +407,24 @@ describe('Platform.dom', function() { }); }); }); + + describe('isAttached', function() { + it('should detect detached when canvas is attached to DOM', function() { + var platform = new DomPlatform(); + var canvas = document.createElement('canvas'); + var div = document.createElement('div'); + + expect(platform.isAttached(canvas)).toEqual(false); + div.appendChild(canvas); + expect(platform.isAttached(canvas)).toEqual(false); + document.body.appendChild(div); + + expect(platform.isAttached(canvas)).toEqual(true); + + div.removeChild(canvas); + expect(platform.isAttached(canvas)).toEqual(false); + document.body.removeChild(div); + expect(platform.isAttached(canvas)).toEqual(false); + }); + }); });
true