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
fb68e91312ad632fcefad0d5883d1d04c13e32ec.json
Fix errors in custom tooltip samples (#7595)
samples/tooltips/custom-points.html
@@ -41,16 +41,18 @@ <div class="chartjs-tooltip" id="tooltip-1"></div> </div> <script> - var customTooltips = function(tooltip) { - $(this._chart.canvas).css('cursor', 'pointer'); + var customTooltips = function(context) { + var chart = context.chart; + $(chart.canvas).css('cursor', 'pointer'); - var positionY = this._chart.canvas.offsetTop; - var positionX = this._chart.canvas.offsetLeft; + var positionY = chart.canvas.offsetTop; + var positionX = chart.canvas.offsetLeft; $('.chartjs-tooltip').css({ opacity: 0, }); + var tooltip = context.tooltip; if (!tooltip || !tooltip.opacity) { return; }
true
Other
chartjs
Chart.js
4cc3079e65c47b3f7eabceec19d652937b4ce7da.json
Add normalized option (#7538) Add normalized option to time scales
docs/docs/axes/cartesian/timeseries.md
@@ -2,7 +2,7 @@ title: Time Series Axis --- -The time series scale extends from the time scale and supports all the same options. However, for the time series scale, each data point is spread equidistant. Also, the data indices are expected to be unique, sorted, and consistent across datasets. +The time series scale extends from the time scale and supports all the same options. However, for the time series scale, each data point is spread equidistant. ## Example
true
Other
chartjs
Chart.js
4cc3079e65c47b3f7eabceec19d652937b4ce7da.json
Add normalized option (#7538) Add normalized option to time scales
docs/docs/general/performance.md
@@ -4,6 +4,24 @@ title: Performance Chart.js charts are rendered on `canvas` elements, which makes rendering quite fast. For large datasets or performance sensitive applications, you may wish to consider the tips below. +## Data structure and format + +### Parsing + +Provide prepared data in the internal format accepted by the dataset and scales and set `parsing: false`. See [Data structures](data-structures.md) for more information. + +### Data normalization + +Chart.js is fastest if you provide data with indices that are unique, sorted, and consistent across datasets and provide the `normalized: true` option to let Chart.js know that you have done so. Even without this option, it can sometimes still be faster to provide sorted data. + +### Decimation + +Decimating your data will achieve the best results. When there is a lot of data to display on the graph, it doesn't make sense to show tens of thousands of data points on a graph that is only a few hundred pixels wide. + +There are many approaches to data decimation and selection of an algorithm will depend on your data and the results you want to achieve. For instance, [min/max](https://digital.ni.com/public.nsf/allkb/F694FFEEA0ACF282862576020075F784) decimation will preserve peaks in your data but could require up to 4 points for each pixel. This type of decimation would work well for a very noisy signal where you need to see data peaks. + +Line charts are able to do [automatic data decimation during draw](#automatic-data-decimation-during-draw), when certain conditions are met. You should still consider decimating data yourself before passing it in for maximum performance since the automatic decimation occurs late in the chart life cycle. + ## Tick Calculation ### Rotation @@ -30,10 +48,6 @@ new Chart(ctx, { }); ``` -## Provide ordered data - -If the data is unordered, Chart.js needs to sort it. This can be slow in some cases, so its always a good idea to provide ordered data. - ## Specify `min` and `max` for scales If you specify the `min` and `max`, the scale does not have to compute the range from the data. @@ -59,19 +73,7 @@ new Chart(ctx, { }); ``` -## Data structure and format - -Provide prepared data in the internal format accepted by the dataset and scales and set `parsing: false`. See [Data structures](data-structures.md) for more information. - -## Data Decimation - -Decimating your data will achieve the best results. When there is a lot of data to display on the graph, it doesn't make sense to show tens of thousands of data points on a graph that is only a few hundred pixels wide. - -There are many approaches to data decimation and selection of an algorithm will depend on your data and the results you want to achieve. For instance, [min/max](https://digital.ni.com/public.nsf/allkb/F694FFEEA0ACF282862576020075F784) decimation will preserve peaks in your data but could require up to 4 points for each pixel. This type of decimation would work well for a very noisy signal where you need to see data peaks. - -Line charts are able to do [automatic data decimation during draw](#automatic-data-decimation-during-draw), when certain conditions are met. You should still consider decimating data yourself before passing it in for maximum performance since the automatic decimation occurs late in the chart life cycle. - -## Render Chart.js in a web worker (Chrome only) +## Parallel rendering with web workers (Chrome only) Chome (in version 69) added the ability to [transfer rendering control of a canvas](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/transferControlToOffscreen) to a web worker. Web workers can use the [OffscreenCanvas API](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) to render from a web worker onto canvases in the DOM. Chart.js is a canvas-based library and supports rendering in a web worker - just pass an OffscreenCanvas into the Chart constructor instead of a Canvas element. Note that as of today, this API is only supported in Chrome. @@ -220,7 +222,7 @@ new Chart(ctx, { }); ``` -### When transpiling with Babel, cosider using `loose` mode +## When transpiling with Babel, cosider using `loose` mode Babel 7.9 changed the way classes are constructed. It is slow, unless used with `loose` mode. [More information](https://github.com/babel/babel/issues/11356)
true
Other
chartjs
Chart.js
4cc3079e65c47b3f7eabceec19d652937b4ce7da.json
Add normalized option (#7538) Add normalized option to time scales
src/controllers/controller.bar.js
@@ -355,7 +355,7 @@ export default class BarController extends DatasetController { let i, ilen; for (i = 0, ilen = meta.data.length; i < ilen; ++i) { - pixels.push(iScale.getPixelForValue(me.getParsed(i)[iScale.axis])); + pixels.push(iScale.getPixelForValue(me.getParsed(i)[iScale.axis], i)); } // Note: a potential optimization would be to skip computing this
true
Other
chartjs
Chart.js
4cc3079e65c47b3f7eabceec19d652937b4ce7da.json
Add normalized option (#7538) Add normalized option to time scales
src/controllers/controller.line.js
@@ -49,8 +49,8 @@ export default class LineController extends DatasetController { const index = start + i; const point = points[i]; const parsed = me.getParsed(index); - const x = xScale.getPixelForValue(parsed.x); - const y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(_stacked ? me.applyStack(yScale, parsed) : parsed.y); + const x = xScale.getPixelForValue(parsed.x, index); + const y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(_stacked ? me.applyStack(yScale, parsed) : parsed.y, index); const properties = { x, y,
true
Other
chartjs
Chart.js
4cc3079e65c47b3f7eabceec19d652937b4ce7da.json
Add normalized option (#7538) Add normalized option to time scales
src/core/core.controller.js
@@ -451,7 +451,7 @@ class Chart { scales[scale.id] = scale; } - scale.init(scaleOptions); + scale.init(scaleOptions, options); // TODO(SB): I think we should be able to remove this custom case (options.scale) // and consider it as a regular scale part of the "scales"" map only! This would
true
Other
chartjs
Chart.js
4cc3079e65c47b3f7eabceec19d652937b4ce7da.json
Add normalized option (#7538) Add normalized option to time scales
src/core/core.scale.js
@@ -938,9 +938,10 @@ export default class Scale extends Element { * Returns the location of the given data point. Value can either be an index or a numerical value * The coordinate (0, 0) is at the upper-left corner of the canvas * @param {*} value + * @param {number} [index] * @return {number} */ - getPixelForValue(value) { // eslint-disable-line no-unused-vars + getPixelForValue(value, index) { // eslint-disable-line no-unused-vars return NaN; }
true
Other
chartjs
Chart.js
4cc3079e65c47b3f7eabceec19d652937b4ce7da.json
Add normalized option (#7538) Add normalized option to time scales
src/scales/scale.time.js
@@ -217,21 +217,23 @@ export default class TimeScale extends Scale { this._unit = 'day'; /** @type {Unit=} */ this._majorUnit = undefined; - /** @type {object} */ this._offsets = {}; + this._normalized = false; } - init(options) { - const time = options.time || (options.time = {}); - const adapter = this._adapter = new adapters._date(options.adapters.date); + init(scaleOpts, opts) { + const time = scaleOpts.time || (scaleOpts.time = {}); + const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date); // Backward compatibility: before introducing adapter, `displayFormats` was // supposed to contain *all* unit/string pairs but this can't be resolved // when loading the scale (adapters are loaded afterward), so let's populate // missing formats on update mergeIf(time.displayFormats, adapter.formats()); - super.init(options); + super.init(scaleOpts); + + this._normalized = opts.normalized; } /** @@ -574,13 +576,15 @@ export default class TimeScale extends Scale { const metas = me.getMatchingVisibleMetas(); + if (me._normalized && metas.length) { + return (me._cache.data = metas[0].controller.getAllParsedValues(me)); + } + for (i = 0, ilen = metas.length; i < ilen; ++i) { timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(me)); } - // We can not assume data is in order or unique - not even for single dataset - // It seems to be somewhat faster to do sorting first - return (me._cache.data = _arrayUnique(timestamps.sort(sorter))); + return (me._cache.data = me.normalize(timestamps)); } /** @@ -600,8 +604,16 @@ export default class TimeScale extends Scale { timestamps.push(parse(me, labels[i])); } - // We could assume labels are in order and unique - but let's not - return (me._cache.labels = _arrayUnique(timestamps.sort(sorter))); + return (me._cache.labels = me._normalized ? timestamps : me.normalize(timestamps)); + } + + /** + * @param {number[]} values + * @protected + */ + normalize(values) { + // It seems to be somewhat faster to do sorting first + return _arrayUnique(values.sort(sorter)); } }
true
Other
chartjs
Chart.js
4cc3079e65c47b3f7eabceec19d652937b4ce7da.json
Add normalized option (#7538) Add normalized option to time scales
src/scales/scale.timeseries.js
@@ -1,37 +1,34 @@ import TimeScale from './scale.time'; -import {_arrayUnique, _lookupByKey} from '../helpers/helpers.collection'; +import {_lookup} from '../helpers/helpers.collection'; +import {isNullOrUndef} from '../helpers/helpers.core'; /** - * Linearly interpolates the given source `value` using the table items `skey` values and - * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos') - * returns the position for a timestamp equal to 42. If value is out of bounds, values at - * index [0, 1] or [n - 1, n] are used for the interpolation. + * Linearly interpolates the given source `val` using the table. If value is out of bounds, values + * at index [0, 1] or [n - 1, n] are used for the interpolation. * @param {object} table - * @param {string} skey - * @param {number} sval - * @param {string} tkey + * @param {number} val + * @param {boolean} [reverse] lookup time based on position instead of vice versa * @return {object} */ -function interpolate(table, skey, sval, tkey) { - const {lo, hi} = _lookupByKey(table, skey, sval); +function interpolate(table, val, reverse) { + let prevSource, nextSource, prevTarget, nextTarget; // Note: the lookup table ALWAYS contains at least 2 items (min and max) - const prev = table[lo]; - const next = table[hi]; - - const span = next[skey] - prev[skey]; - const ratio = span ? (sval - prev[skey]) / span : 0; - const offset = (next[tkey] - prev[tkey]) * ratio; + if (reverse) { + prevSource = Math.floor(val); + nextSource = Math.ceil(val); + prevTarget = table[prevSource]; + nextTarget = table[nextSource]; + } else { + const result = _lookup(table, val); + prevTarget = result.lo; + nextTarget = result.hi; + prevSource = table[prevTarget]; + nextSource = table[nextTarget]; + } - return prev[tkey] + offset; -} - -/** - * @param {number} a - * @param {number} b - */ -function sorter(a, b) { - return a - b; + const span = nextSource - prevSource; + return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget; } class TimeSeriesScale extends TimeScale { @@ -44,6 +41,8 @@ class TimeSeriesScale extends TimeScale { /** @type {object[]} */ this._table = []; + /** @type {number} */ + this._maxIndex = undefined; } /** @@ -53,6 +52,7 @@ class TimeSeriesScale extends TimeScale { const me = this; const timestamps = me._getTimestampsForTable(); me._table = me.buildLookupTable(timestamps); + me._maxIndex = me._table.length - 1; super.initOffsets(timestamps); } @@ -77,9 +77,8 @@ class TimeSeriesScale extends TimeScale { ]; } - const table = []; const items = [min]; - let i, ilen, prev, curr, next; + let i, ilen, curr; for (i = 0, ilen = timestamps.length; i < ilen; ++i) { curr = timestamps[i]; @@ -90,18 +89,7 @@ class TimeSeriesScale extends TimeScale { items.push(max); - for (i = 0, ilen = items.length; i < ilen; ++i) { - next = items[i + 1]; - prev = items[i - 1]; - curr = items[i]; - - // only add points that breaks the scale linearity - if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) { - table.push({time: curr, pos: i / (ilen - 1)}); - } - } - - return table; + return items; } /** @@ -122,7 +110,7 @@ class TimeSeriesScale extends TimeScale { if (data.length && label.length) { // If combining labels and data (data might not contain all labels), // we need to recheck uniqueness and sort - timestamps = _arrayUnique(data.concat(label).sort(sorter)); + timestamps = me.normalize(data.concat(label)); } else { timestamps = data.length ? data : label; } @@ -133,48 +121,23 @@ class TimeSeriesScale extends TimeScale { /** * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC) + * @param {number} [index] * @return {number} */ - getDecimalForValue(value) { - return interpolate(this._table, 'time', value, 'pos'); - } - - /** - * @return {number[]} - * @protected - */ - getDataTimestamps() { + getPixelForValue(value, index) { const me = this; - const timestamps = me._cache.data || []; - - if (timestamps.length) { - return timestamps; - } - - const metas = me.getMatchingVisibleMetas(); - return (me._cache.data = metas.length ? metas[0].controller.getAllParsedValues(me) : []); + const offsets = me._offsets; + const pos = me._normalized && me._maxIndex > 0 && !isNullOrUndef(index) + ? index / me._maxIndex : me.getDecimalForValue(value); + return me.getPixelForDecimal((offsets.start + pos) * offsets.factor); } /** - * @return {number[]} - * @protected + * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC) + * @return {number} */ - getLabelTimestamps() { - const me = this; - const timestamps = me._cache.labels || []; - let i, ilen; - - if (timestamps.length) { - return timestamps; - } - - const labels = me.getLabels(); - for (i = 0, ilen = labels.length; i < ilen; ++i) { - timestamps.push(me.parse(labels[i])); - } - - // We could assume labels are in order and unique - but let's not - return (me._cache.labels = timestamps); + getDecimalForValue(value) { + return interpolate(this._table, value) / this._maxIndex; } /** @@ -184,8 +147,8 @@ class TimeSeriesScale extends TimeScale { getValueForPixel(pixel) { const me = this; const offsets = me._offsets; - const pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end; - return interpolate(me._table, 'pos', pos, 'time'); + const decimal = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end; + return interpolate(me._table, decimal * this._maxIndex, true); } }
true
Other
chartjs
Chart.js
4cc3079e65c47b3f7eabceec19d652937b4ce7da.json
Add normalized option (#7538) Add normalized option to time scales
test/specs/scale.time.tests.js
@@ -712,144 +712,147 @@ describe('Time scale tests', function() { }); }); - describe('when scale type', function() { - describe('is "timeseries"', function() { - beforeEach(function() { - this.chart = window.acquireChart({ - type: 'line', - data: { - labels: ['2017', '2019', '2020', '2025', '2042'], - datasets: [{data: [0, 1, 2, 3, 4, 5]}] - }, - options: { - scales: { - x: { - type: 'timeseries', - time: { - parser: 'YYYY' + [true, false].forEach(function(normalized) { + describe('when normalized is ' + normalized + ' and scale type', function() { + describe('is "timeseries"', function() { + beforeEach(function() { + this.chart = window.acquireChart({ + type: 'line', + data: { + labels: ['2017', '2019', '2020', '2025', '2042'], + datasets: [{data: [0, 1, 2, 3, 4]}] + }, + options: { + normalized, + scales: { + x: { + type: 'timeseries', + time: { + parser: 'YYYY' + }, + ticks: { + source: 'labels' + } }, - ticks: { - source: 'labels' + y: { + display: false } - }, - y: { - display: false } } - } + }); }); - }); - it ('should space data out with the same gap, whatever their time values', function() { - var scale = this.chart.scales.x; - var start = scale.left; - var slice = scale.width / 4; - - expect(scale.getPixelForValue(moment('2017').valueOf())).toBeCloseToPixel(start); - expect(scale.getPixelForValue(moment('2019').valueOf())).toBeCloseToPixel(start + slice); - expect(scale.getPixelForValue(moment('2020').valueOf())).toBeCloseToPixel(start + slice * 2); - expect(scale.getPixelForValue(moment('2025').valueOf())).toBeCloseToPixel(start + slice * 3); - expect(scale.getPixelForValue(moment('2042').valueOf())).toBeCloseToPixel(start + slice * 4); - }); - it ('should add a step before if scale.min is before the first data', function() { - var chart = this.chart; - var scale = chart.scales.x; - var options = chart.options.scales.x; + it ('should space data out with the same gap, whatever their time values', function() { + var scale = this.chart.scales.x; + var start = scale.left; + var slice = scale.width / 4; + + expect(scale.getPixelForValue(moment('2017').valueOf(), 0)).toBeCloseToPixel(start); + expect(scale.getPixelForValue(moment('2019').valueOf(), 1)).toBeCloseToPixel(start + slice); + expect(scale.getPixelForValue(moment('2020').valueOf(), 2)).toBeCloseToPixel(start + slice * 2); + expect(scale.getPixelForValue(moment('2025').valueOf(), 3)).toBeCloseToPixel(start + slice * 3); + expect(scale.getPixelForValue(moment('2042').valueOf(), 4)).toBeCloseToPixel(start + slice * 4); + }); + it ('should add a step before if scale.min is before the first data', function() { + var chart = this.chart; + var scale = chart.scales.x; + var options = chart.options.scales.x; - options.min = '2012'; - chart.update(); + options.min = '2012'; + chart.update(); - var start = scale.left; - var slice = scale.width / 5; + var start = scale.left; + var slice = scale.width / 5; - expect(scale.getPixelForValue(moment('2017').valueOf())).toBeCloseToPixel(start + slice); - expect(scale.getPixelForValue(moment('2042').valueOf())).toBeCloseToPixel(start + slice * 5); - }); - it ('should add a step after if scale.max is after the last data', function() { - var chart = this.chart; - var scale = chart.scales.x; - var options = chart.options.scales.x; + expect(scale.getPixelForValue(moment('2017').valueOf(), 1)).toBeCloseToPixel(start + slice); + expect(scale.getPixelForValue(moment('2042').valueOf(), 5)).toBeCloseToPixel(start + slice * 5); + }); + it ('should add a step after if scale.max is after the last data', function() { + var chart = this.chart; + var scale = chart.scales.x; + var options = chart.options.scales.x; - options.max = '2050'; - chart.update(); + options.max = '2050'; + chart.update(); - var start = scale.left; - var slice = scale.width / 5; + var start = scale.left; + var slice = scale.width / 5; - expect(scale.getPixelForValue(moment('2017').valueOf())).toBeCloseToPixel(start); - expect(scale.getPixelForValue(moment('2042').valueOf())).toBeCloseToPixel(start + slice * 4); - }); - it ('should add steps before and after if scale.min/max are outside the data range', function() { - var chart = this.chart; - var scale = chart.scales.x; - var options = chart.options.scales.x; + expect(scale.getPixelForValue(moment('2017').valueOf(), 0)).toBeCloseToPixel(start); + expect(scale.getPixelForValue(moment('2042').valueOf(), 4)).toBeCloseToPixel(start + slice * 4); + }); + it ('should add steps before and after if scale.min/max are outside the data range', function() { + var chart = this.chart; + var scale = chart.scales.x; + var options = chart.options.scales.x; - options.min = '2012'; - options.max = '2050'; - chart.update(); + options.min = '2012'; + options.max = '2050'; + chart.update(); - var start = scale.left; - var slice = scale.width / 6; + var start = scale.left; + var slice = scale.width / 6; - expect(scale.getPixelForValue(moment('2017').valueOf())).toBeCloseToPixel(start + slice); - expect(scale.getPixelForValue(moment('2042').valueOf())).toBeCloseToPixel(start + slice * 5); + expect(scale.getPixelForValue(moment('2017').valueOf(), 1)).toBeCloseToPixel(start + slice); + expect(scale.getPixelForValue(moment('2042').valueOf(), 5)).toBeCloseToPixel(start + slice * 5); + }); }); - }); - describe('is "time"', function() { - beforeEach(function() { - this.chart = window.acquireChart({ - type: 'line', - data: { - labels: ['2017', '2019', '2020', '2025', '2042'], - datasets: [{data: [0, 1, 2, 3, 4, 5]}] - }, - options: { - scales: { - x: { - type: 'time', - time: { - parser: 'YYYY' + describe('is "time"', function() { + beforeEach(function() { + this.chart = window.acquireChart({ + type: 'line', + data: { + labels: ['2017', '2019', '2020', '2025', '2042'], + datasets: [{data: [0, 1, 2, 3, 4, 5]}] + }, + options: { + scales: { + x: { + type: 'time', + time: { + parser: 'YYYY' + }, + ticks: { + source: 'labels' + } }, - ticks: { - source: 'labels' + y: { + display: false } - }, - y: { - display: false } } - } + }); }); - }); - it ('should space data out with a gap relative to their time values', function() { - var scale = this.chart.scales.x; - var start = scale.left; - var slice = scale.width / (2042 - 2017); - - expect(scale.getPixelForValue(moment('2017').valueOf())).toBeCloseToPixel(start); - expect(scale.getPixelForValue(moment('2019').valueOf())).toBeCloseToPixel(start + slice * (2019 - 2017)); - expect(scale.getPixelForValue(moment('2020').valueOf())).toBeCloseToPixel(start + slice * (2020 - 2017)); - expect(scale.getPixelForValue(moment('2025').valueOf())).toBeCloseToPixel(start + slice * (2025 - 2017)); - expect(scale.getPixelForValue(moment('2042').valueOf())).toBeCloseToPixel(start + slice * (2042 - 2017)); - }); - it ('should take in account scale min and max if outside the ticks range', function() { - var chart = this.chart; - var scale = chart.scales.x; - var options = chart.options.scales.x; + it ('should space data out with a gap relative to their time values', function() { + var scale = this.chart.scales.x; + var start = scale.left; + var slice = scale.width / (2042 - 2017); + + expect(scale.getPixelForValue(moment('2017').valueOf(), 0)).toBeCloseToPixel(start); + expect(scale.getPixelForValue(moment('2019').valueOf(), 1)).toBeCloseToPixel(start + slice * (2019 - 2017)); + expect(scale.getPixelForValue(moment('2020').valueOf(), 2)).toBeCloseToPixel(start + slice * (2020 - 2017)); + expect(scale.getPixelForValue(moment('2025').valueOf(), 3)).toBeCloseToPixel(start + slice * (2025 - 2017)); + expect(scale.getPixelForValue(moment('2042').valueOf(), 4)).toBeCloseToPixel(start + slice * (2042 - 2017)); + }); + it ('should take in account scale min and max if outside the ticks range', function() { + var chart = this.chart; + var scale = chart.scales.x; + var options = chart.options.scales.x; - options.min = '2012'; - options.max = '2050'; - chart.update(); + options.min = '2012'; + options.max = '2050'; + chart.update(); - var start = scale.left; - var slice = scale.width / (2050 - 2012); + var start = scale.left; + var slice = scale.width / (2050 - 2012); - expect(scale.getPixelForValue(moment('2017').valueOf())).toBeCloseToPixel(start + slice * (2017 - 2012)); - expect(scale.getPixelForValue(moment('2019').valueOf())).toBeCloseToPixel(start + slice * (2019 - 2012)); - expect(scale.getPixelForValue(moment('2020').valueOf())).toBeCloseToPixel(start + slice * (2020 - 2012)); - expect(scale.getPixelForValue(moment('2025').valueOf())).toBeCloseToPixel(start + slice * (2025 - 2012)); - expect(scale.getPixelForValue(moment('2042').valueOf())).toBeCloseToPixel(start + slice * (2042 - 2012)); + expect(scale.getPixelForValue(moment('2017').valueOf(), 0)).toBeCloseToPixel(start + slice * (2017 - 2012)); + expect(scale.getPixelForValue(moment('2019').valueOf(), 1)).toBeCloseToPixel(start + slice * (2019 - 2012)); + expect(scale.getPixelForValue(moment('2020').valueOf(), 2)).toBeCloseToPixel(start + slice * (2020 - 2012)); + expect(scale.getPixelForValue(moment('2025').valueOf(), 3)).toBeCloseToPixel(start + slice * (2025 - 2012)); + expect(scale.getPixelForValue(moment('2042').valueOf(), 4)).toBeCloseToPixel(start + slice * (2042 - 2012)); + }); }); }); });
true
Other
chartjs
Chart.js
f544707e2cae2d47bb9a3310a3f74b067cac7c31.json
Remove duplicate tests (#7568)
test/specs/scale.time.tests.js
@@ -187,47 +187,6 @@ describe('Time scale tests', function() { }); }); - describe('when specifying limits in a deprecated fashion', function() { - var mockData = { - labels: ['2015-01-01T20:00:00', '2015-01-02T20:00:00', '2015-01-03T20:00:00'], - }; - - var config; - beforeEach(function() { - config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('time')); - config.ticks.source = 'labels'; - config.time.unit = 'day'; - }); - - it('should use the min option when less than first label for building ticks', function() { - config.min = '2014-12-29T04:00:00'; - - var labels = getLabels(createScale(mockData, config)); - expect(labels[0]).toEqual('Jan 1'); - }); - - it('should use the min option when greater than first label for building ticks', function() { - config.min = '2015-01-02T04:00:00'; - - var labels = getLabels(createScale(mockData, config)); - expect(labels[0]).toEqual('Jan 2'); - }); - - it('should use the max option when greater than last label for building ticks', function() { - config.max = '2015-01-05T06:00:00'; - - var labels = getLabels(createScale(mockData, config)); - expect(labels[labels.length - 1]).toEqual('Jan 3'); - }); - - it('should use the max option when less than last label for building ticks', function() { - config.max = '2015-01-02T23:00:00'; - - var labels = getLabels(createScale(mockData, config)); - expect(labels[labels.length - 1]).toEqual('Jan 2'); - }); - }); - it('should use the isoWeekday option', function() { var mockData = { labels: [
false
Other
chartjs
Chart.js
a33086bfc13d08f6421ea15ef91b56331d2f2551.json
Enable autoSkip for time scale to match others (#7570)
docs/docs/getting-started/v3-migration.md
@@ -156,7 +156,8 @@ options: { } ``` -Also, the time scale option `distribution: 'series'` was removed and a new scale type `timeseries` was introduced in its place. +* The time scale option `distribution: 'series'` was removed and a new scale type `timeseries` was introduced in its place +* In the time scale, `autoSkip` is now enabled by default for consistency with the other scales #### Animations
true
Other
chartjs
Chart.js
a33086bfc13d08f6421ea15ef91b56331d2f2551.json
Enable autoSkip for time scale to match others (#7570)
src/scales/scale.time.js
@@ -219,8 +219,6 @@ const defaultConfig = { displayFormats: {} }, ticks: { - autoSkip: false, - /** * Ticks generation input values: * - 'auto': generates "optimal" ticks based on scale size and time options.
true
Other
chartjs
Chart.js
a33086bfc13d08f6421ea15ef91b56331d2f2551.json
Enable autoSkip for time scale to match others (#7570)
test/specs/scale.time.tests.js
@@ -88,7 +88,7 @@ describe('Time scale tests', function() { padding: 0, display: true, callback: defaultConfig.ticks.callback, // make this nicer, then check explicitly below, - autoSkip: false, + autoSkip: true, autoSkipPadding: 0, labelOffset: 0, minor: {},
true
Other
chartjs
Chart.js
87c59fea73cf55b63fca0d0049c351b2ceb468b8.json
Fix padding for labels (#7572)
src/core/core.scale.js
@@ -779,8 +779,8 @@ export default class Scale extends Element { minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth); - me.paddingTop = firstLabelSize.height / 2; - me.paddingBottom = lastLabelSize.height / 2; + me.paddingTop = lastLabelSize.height / 2; + me.paddingBottom = firstLabelSize.height / 2; } }
false
Other
chartjs
Chart.js
13e7a1163b2aa058906228da853b5cd1f07aff8c.json
Use all timestamps for calculating offsets (#7573)
src/scales/scale.timeseries.js
@@ -46,9 +46,13 @@ class TimeSeriesScale extends TimeScale { this._table = []; } - initOffsets(timestamps) { + /** + * @protected + */ + initOffsets() { const me = this; - me._table = me.buildLookupTable(); + const timestamps = me._getTimestampsForTable(); + me._table = me.buildLookupTable(timestamps); super.initOffsets(timestamps); } @@ -59,14 +63,13 @@ class TimeSeriesScale extends TimeScale { * extremity (left + width or top + height). Note that it would be more optimized to directly * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need * to create the lookup table. The table ALWAYS contains at least two items: min and max. - * + * @param {number[]} timestamps * @return {object[]} * @protected */ - buildLookupTable() { + buildLookupTable(timestamps) { const me = this; const {min, max} = me; - const timestamps = me._getTimestampsForTable(); if (!timestamps.length) { return [ {time: min, pos: 0}, @@ -103,6 +106,7 @@ class TimeSeriesScale extends TimeScale { /** * Returns all timestamps + * @return {number[]} * @private */ _getTimestampsForTable() { @@ -136,6 +140,7 @@ class TimeSeriesScale extends TimeScale { } /** + * @return {number[]} * @protected */ getDataTimestamps() { @@ -151,6 +156,7 @@ class TimeSeriesScale extends TimeScale { } /** + * @return {number[]} * @protected */ getLabelTimestamps() {
true
Other
chartjs
Chart.js
13e7a1163b2aa058906228da853b5cd1f07aff8c.json
Use all timestamps for calculating offsets (#7573)
test/specs/scale.time.tests.js
@@ -1149,6 +1149,41 @@ describe('Time scale tests', function() { }); }); + it ('should handle offset when there are more data points than ticks', function() { + const chart = window.acquireChart({ + type: 'bar', + data: { + datasets: [{ + data: [{x: 631180800000, y: '31.84'}, {x: 631267200000, y: '30.89'}, {x: 631353600000, y: '33.00'}, {x: 631440000000, y: '33.52'}, {x: 631526400000, y: '32.24'}, {x: 631785600000, y: '32.74'}, {x: 631872000000, y: '31.45'}, {x: 631958400000, y: '32.60'}, {x: 632044800000, y: '31.77'}, {x: 632131200000, y: '32.45'}, {x: 632390400000, y: '31.13'}, {x: 632476800000, y: '31.82'}, {x: 632563200000, y: '30.81'}, {x: 632649600000, y: '30.07'}, {x: 632736000000, y: '29.31'}, {x: 632995200000, y: '29.82'}, {x: 633081600000, y: '30.20'}, {x: 633168000000, y: '30.78'}, {x: 633254400000, y: '30.72'}, {x: 633340800000, y: '31.62'}, {x: 633600000000, y: '30.64'}, {x: 633686400000, y: '32.36'}, {x: 633772800000, y: '34.66'}, {x: 633859200000, y: '33.96'}, {x: 633945600000, y: '34.20'}, {x: 634204800000, y: '32.20'}, {x: 634291200000, y: '32.44'}, {x: 634377600000, y: '32.72'}, {x: 634464000000, y: '32.95'}, {x: 634550400000, y: '32.95'}, {x: 634809600000, y: '30.88'}, {x: 634896000000, y: '29.44'}, {x: 634982400000, y: '29.36'}, {x: 635068800000, y: '28.84'}, {x: 635155200000, y: '30.85'}, {x: 635414400000, y: '32.00'}, {x: 635500800000, y: '32.74'}, {x: 635587200000, y: '33.16'}, {x: 635673600000, y: '34.73'}, {x: 635760000000, y: '32.89'}, {x: 636019200000, y: '32.41'}, {x: 636105600000, y: '31.15'}, {x: 636192000000, y: '30.63'}, {x: 636278400000, y: '29.60'}, {x: 636364800000, y: '29.31'}, {x: 636624000000, y: '29.83'}, {x: 636710400000, y: '27.97'}, {x: 636796800000, y: '26.18'}, {x: 636883200000, y: '26.06'}, {x: 636969600000, y: '26.34'}, {x: 637228800000, y: '27.75'}, {x: 637315200000, y: '29.05'}, {x: 637401600000, y: '28.82'}, {x: 637488000000, y: '29.43'}, {x: 637574400000, y: '29.53'}, {x: 637833600000, y: '28.50'}, {x: 637920000000, y: '28.87'}, {x: 638006400000, y: '28.11'}, {x: 638092800000, y: '27.79'}, {x: 638179200000, y: '28.18'}, {x: 638438400000, y: '28.27'}, {x: 638524800000, y: '28.29'}, {x: 638611200000, y: '29.63'}, {x: 638697600000, y: '29.13'}, {x: 638784000000, y: '26.57'}, {x: 639039600000, y: '27.19'}, {x: 639126000000, y: '27.48'}, {x: 639212400000, y: '27.79'}, {x: 639298800000, y: '28.48'}, {x: 639385200000, y: '27.88'}, {x: 639644400000, y: '25.63'}, {x: 639730800000, y: '25.02'}, {x: 639817200000, y: '25.26'}, {x: 639903600000, y: '25.00'}, {x: 639990000000, y: '26.23'}, {x: 640249200000, y: '26.22'}, {x: 640335600000, y: '26.36'}, {x: 640422000000, y: '25.45'}, {x: 640508400000, y: '24.62'}, {x: 640594800000, y: '26.65'}, {x: 640854000000, y: '26.28'}, {x: 640940400000, y: '27.25'}, {x: 641026800000, y: '25.93'}], + backgroundColor: '#ff6666' + }] + }, + options: { + scales: { + x: { + type: 'timeseries', + offset: true, + ticks: { + source: 'data', + autoSkip: true, + maxRotation: 0 + } + }, + y: { + type: 'linear', + gridLines: { + drawBorder: false + } + } + } + }, + legend: false + }); + const scale = chart.scales.x; + expect(scale.getPixelForDecimal(0)).toBeCloseToPixel(29); + expect(scale.getPixelForDecimal(1.0)).toBeCloseToPixel(494); + }); + ['data', 'labels'].forEach(function(source) { ['timeseries', 'time'].forEach(function(type) { describe('when ticks.source is "' + source + '" and scale type is "' + type + '"', function() {
true
Other
chartjs
Chart.js
6c38c31a0a29a36ec2a4f31cd8cac5aa16b79c86.json
Pass context parameter to custom tooltip (#7579)
docs/docs/configuration/tooltip.md
@@ -194,7 +194,7 @@ The tooltip items passed to the tooltip callbacks implement the following interf ## External (Custom) Tooltips -Custom tooltips allow you to hook into the tooltip rendering process so that you can render the tooltip in your own custom way. Generally this is used to create an HTML tooltip instead of an oncanvas one. You can enable custom tooltips in the global or chart configuration like so: +Custom tooltips allow you to hook into the tooltip rendering process so that you can render the tooltip in your own custom way. Generally this is used to create an HTML tooltip instead of an on-canvas tooltip. The `custom` option takes a function which is passed a context parameter containing the `chart` and `tooltip`. You can enable custom tooltips in the global or chart configuration like so: ```javascript var myPieChart = new Chart(ctx, { @@ -205,7 +205,7 @@ var myPieChart = new Chart(ctx, { // Disable the on-canvas tooltip enabled: false, - custom: function(tooltipModel) { + custom: function(context) { // Tooltip Element var tooltipEl = document.getElementById('chartjs-tooltip'); @@ -218,6 +218,7 @@ var myPieChart = new Chart(ctx, { } // Hide if no tooltip + var tooltipModel = context.tooltip; if (tooltipModel.opacity === 0) { tooltipEl.style.opacity = 0; return;
true
Other
chartjs
Chart.js
6c38c31a0a29a36ec2a4f31cd8cac5aa16b79c86.json
Pass context parameter to custom tooltip (#7579)
docs/docs/getting-started/v3-migration.md
@@ -186,6 +186,7 @@ Animation system was completely rewritten in Chart.js v3. Each property can now * `xLabel` and `yLabel` were removed. Please use `index` and `value` * The `filter` option will now be passed additional parameters when called and should have the method signature `function(tooltipItem, index, tooltipItems, data)` +* The `custom` callback now takes a context object that has `tooltip` and `chart` properties ## Developer migration
true
Other
chartjs
Chart.js
6c38c31a0a29a36ec2a4f31cd8cac5aa16b79c86.json
Pass context parameter to custom tooltip (#7579)
src/plugins/plugin.tooltip.js
@@ -669,7 +669,7 @@ export class Tooltip extends Element { } if (changed && options.custom) { - options.custom.call(me, [me]); + options.custom.call(me, {chart: me._chart, tooltip: me}); } }
true
Other
chartjs
Chart.js
2ca155cce16b9bdc327030e169f8e69f3f5b627a.json
Add parameters to tooltip filter option (#7556)
docs/docs/configuration/tooltip.md
@@ -93,7 +93,7 @@ Allows sorting of [tooltip items](#tooltip-item-interface). Must implement at mi ### Filter Callback -Allows filtering of [tooltip items](#tooltip-item-interface). Must implement at minimum a function that can be passed to [Array.prototype.filter](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). This function can also accept a second parameter that is the data object passed to the chart. +Allows filtering of [tooltip items](#tooltip-item-interface). Must implement at minimum a function that can be passed to [Array.prototype.filter](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). This function can also accept a fourth parameter that is the data object passed to the chart. ## Tooltip Callbacks
true
Other
chartjs
Chart.js
2ca155cce16b9bdc327030e169f8e69f3f5b627a.json
Add parameters to tooltip filter option (#7556)
docs/docs/getting-started/v3-migration.md
@@ -185,6 +185,7 @@ Animation system was completely rewritten in Chart.js v3. Each property can now #### Tooltip * `xLabel` and `yLabel` were removed. Please use `index` and `value` +* The `filter` option will now be passed additional parameters when called and should have the method signature `function(tooltipItem, index, tooltipItems, data)` ## Developer migration
true
Other
chartjs
Chart.js
2ca155cce16b9bdc327030e169f8e69f3f5b627a.json
Add parameters to tooltip filter option (#7556)
src/plugins/plugin.tooltip.js
@@ -602,7 +602,7 @@ export class Tooltip extends Element { // If the user provided a filter function, use it to modify the tooltip items if (options.filter) { - tooltipItems = tooltipItems.filter((a) => options.filter(a, data)); + tooltipItems = tooltipItems.filter((element, index, array) => options.filter(element, index, array, data)); } // If the user provided a sorting function, use it to modify the tooltip items
true
Other
chartjs
Chart.js
2ca155cce16b9bdc327030e169f8e69f3f5b627a.json
Add parameters to tooltip filter option (#7556)
test/specs/plugin.tooltip.tests.js
@@ -706,7 +706,7 @@ describe('Core.Tooltip', function() { options: { tooltips: { mode: 'index', - filter: function(tooltipItem, data) { + filter: function(tooltipItem, index, tooltipItems, data) { // For testing purposes remove the first dataset that has a tooltipHidden property return !data.datasets[tooltipItem.datasetIndex].tooltipHidden; }
true
Other
chartjs
Chart.js
faa218dbbdd21b43e6cf8c16792ffcafbc75caf5.json
Fix financial sample (#7552) * Fix financial sample * Fix major unit determination by copying code from chartjs-chart-financial
samples/scales/financial.html
@@ -4,8 +4,8 @@ <head> <title>Line Chart</title> <script src="../../dist/chart.min.js"></script> - <script src="https://cdn.jsdelivr.net/npm/luxon@1.15.0"></script> - <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@0.2.0"></script> + <script src="https://cdn.jsdelivr.net/npm/luxon@1.24.1"></script> + <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@0.2.1"></script> <script src="../utils.js"></script> <style> canvas { @@ -39,17 +39,6 @@ </select> <button id="update">update</button> <script> - function isFirstUnitOfPeriod(date, unit, period) { - let first = date.startOf(period); - while (first.weekday > 5) { - first = first.plus({day: 1}); - } - if (unit === 'second' || unit === 'minute' || unit === 'hour') { - first = first.set({hour: 9, minute: 30}); - } - return date === first; - } - // Generate data between the stock market hours of 9:30am - 5pm. // This method is slow and unoptimized, but in real life we'd be fetching it from the server. function generateData() { @@ -138,15 +127,14 @@ }, scales: { x: { - type: 'time', - distribution: 'series', + type: 'timeseries', offset: true, ticks: { major: { enabled: true, }, font: function(context) { - return context.tick.major ? {style: 'bold'} : undefined; + return context.tick && context.tick.major ? {style: 'bold'} : undefined; }, source: 'data', autoSkip: true, @@ -157,17 +145,28 @@ // Custom logic that chooses major ticks by first timestamp in time period // E.g. if March 1 & 2 are missing from dataset because they're weekends, we pick March 3 to be beginning of month afterBuildTicks: function(scale) { - const units = ['second', 'minute', 'hour', 'day', 'month', 'year']; - const unit = document.getElementById('unit').value; - let majorUnit; - if (units.indexOf(unit) !== units.length - 1) { - majorUnit = units[units.indexOf(unit) + 1]; - } - - // major ticks + const majorUnit = scale._majorUnit; const ticks = scale.ticks; - for (let i = 0; i < ticks.length; i++) { - ticks[i].major = !majorUnit || isFirstUnitOfPeriod(luxon.DateTime.fromMillis(ticks[i].value), unit, majorUnit); + const firstTick = ticks[0]; + + let val = luxon.DateTime.fromMillis(ticks[0].value); + if ((majorUnit === 'minute' && val.second === 0) + || (majorUnit === 'hour' && val.minute === 0) + || (majorUnit === 'day' && val.hour === 9) + || (majorUnit === 'month' && val.day <= 3 && val.weekday === 1) + || (majorUnit === 'year' && val.month === 1)) { + firstTick.major = true; + } else { + firstTick.major = false; + } + let lastMajor = val.get(majorUnit); + + for (let i = 1; i < ticks.length; i++) { + const tick = ticks[i]; + val = luxon.DateTime.fromMillis(tick.value); + const currMajor = val.get(majorUnit); + tick.major = currMajor !== lastMajor; + lastMajor = currMajor; } scale.ticks = ticks; }
false
Other
chartjs
Chart.js
9ea8292b6e4840772b06ef33c6b330f34caeb7c2.json
Fix typo in sample (#7557)
samples/tooltips/custom-pie.html
@@ -43,7 +43,7 @@ </div> <script> - Chart.default.tooltips.custom = function(tooltip) { + Chart.defaults.tooltips.custom = function(tooltip) { // Tooltip Element var tooltipEl = document.getElementById('chartjs-tooltip');
false
Other
chartjs
Chart.js
1c2a03225ed761e75709a9184c184a697e2ce3cf.json
Remove lookup table from TimeScale (#7532) * Add getDecimalForValue * Move interpolate to timeseries scale * Remove getTimestampsForTable from time scale * Remove parameters from buildLookupTable * Restore getValueForPixel * Remove table from time scale
src/scales/scale.time.js
@@ -2,7 +2,7 @@ import adapters from '../core/core.adapters'; import {isFinite, isNullOrUndef, mergeIf, valueOrDefault} from '../helpers/helpers.core'; import {toRadians} from '../helpers/helpers.math'; import Scale from '../core/core.scale'; -import {_arrayUnique, _filterBetween, _lookup, _lookupByKey} from '../helpers/helpers.collection'; +import {_arrayUnique, _filterBetween, _lookup} from '../helpers/helpers.collection'; /** * @typedef { import("../core/core.adapters").Unit } Unit @@ -79,31 +79,6 @@ function parse(scale, input) { return +value; } -/** - * Linearly interpolates the given source `value` using the table items `skey` values and - * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos') - * returns the position for a timestamp equal to 42. If value is out of bounds, values at - * index [0, 1] or [n - 1, n] are used for the interpolation. - * @param {object} table - * @param {string} skey - * @param {number} sval - * @param {string} tkey - * @return {object} - */ -function interpolate(table, skey, sval, tkey) { - const {lo, hi} = _lookupByKey(table, skey, sval); - - // Note: the lookup table ALWAYS contains at least 2 items (min and max) - const prev = table[lo]; - const next = table[hi]; - - const span = next[skey] - prev[skey]; - const ratio = span ? (sval - prev[skey]) / span : 0; - const offset = (next[tkey] - prev[tkey]) * ratio; - - return prev[tkey] + offset; -} - /** * Figures out what unit results in an appropriate number of auto-generated ticks * @param {Unit} minUnit @@ -173,41 +148,6 @@ function addTick(timestamps, ticks, time) { ticks[timestamp] = true; } -/** - * Returns the start and end offsets from edges in the form of {start, end} - * where each value is a relative width to the scale and ranges between 0 and 1. - * They add extra margins on the both sides by scaling down the original scale. - * Offsets are added when the `offset` option is true. - * @param {object} table - * @param {number[]} timestamps - * @param {number} min - * @param {number} max - * @param {object} options - * @return {object} - */ -function computeOffsets(table, timestamps, min, max, options) { - let start = 0; - let end = 0; - let first, last; - - if (options.offset && timestamps.length) { - first = interpolate(table, 'time', timestamps[0], 'pos'); - if (timestamps.length === 1) { - start = 1 - first; - } else { - start = (interpolate(table, 'time', timestamps[1], 'pos') - first) / 2; - } - last = interpolate(table, 'time', timestamps[timestamps.length - 1], 'pos'); - if (timestamps.length === 1) { - end = last; - } else { - end = (last - interpolate(table, 'time', timestamps[timestamps.length - 2], 'pos')) / 2; - } - } - - return {start, end, factor: 1 / (start + 1 + end)}; -} - /** * @param {TimeScale} scale * @param {object[]} ticks @@ -318,8 +258,6 @@ class TimeScale extends Scale { this._majorUnit = undefined; /** @type {object} */ this._offsets = {}; - /** @type {object[]} */ - this._table = []; } init(options) { @@ -355,13 +293,6 @@ class TimeScale extends Scale { }; } - /** - * @protected - */ - getTimestampsForTable() { - return [this.min, this.max]; - } - determineDataLimits() { const me = this; const options = me.options; @@ -397,7 +328,7 @@ class TimeScale extends Scale { min = isFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit); max = isFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1; - // Make sure that max is strictly higher than min (required by the lookup table) + // Make sure that max is strictly higher than min (required by the timeseries lookup table) me.min = Math.min(min, max); me.max = Math.max(min + 1, max); } @@ -445,8 +376,7 @@ class TimeScale extends Scale { : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max)); me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined : determineMajorUnit(me._unit); - me._table = me.buildLookupTable(me.getTimestampsForTable(), min, max); - me._offsets = computeOffsets(me._table, timestamps, min, max, options); + me.initOffsets(timestamps); if (options.reverse) { ticks.reverse(); @@ -455,6 +385,39 @@ class TimeScale extends Scale { return ticksFromTimestamps(me, ticks, me._majorUnit); } + /** + * Returns the start and end offsets from edges in the form of {start, end} + * where each value is a relative width to the scale and ranges between 0 and 1. + * They add extra margins on the both sides by scaling down the original scale. + * Offsets are added when the `offset` option is true. + * @param {number[]} timestamps + * @return {object} + * @protected + */ + initOffsets(timestamps) { + const me = this; + let start = 0; + let end = 0; + let first, last; + + if (me.options.offset && timestamps.length) { + first = me.getDecimalForValue(timestamps[0]); + if (timestamps.length === 1) { + start = 1 - first; + } else { + start = (me.getDecimalForValue(timestamps[1]) - first) / 2; + } + last = me.getDecimalForValue(timestamps[timestamps.length - 1]); + if (timestamps.length === 1) { + end = last; + } else { + end = (last - me.getDecimalForValue(timestamps[timestamps.length - 2])) / 2; + } + } + + me._offsets = {start, end, factor: 1 / (start + 1 + end)}; + } + /** * Generates a maximum of `capacity` timestamps between min and max, rounded to the * `minor` unit using the given scale time `options`. @@ -514,27 +477,6 @@ class TimeScale extends Scale { return Object.keys(ticks).map(x => +x); } - /** - * Returns an array of {time, pos} objects used to interpolate a specific `time` or position - * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is - * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other - * extremity (left + width or top + height). Note that it would be more optimized to directly - * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need - * to create the lookup table. The table ALWAYS contains at least two items: min and max. - * - * @param {number[]} timestamps - timestamps sorted from lowest to highest. - * @param {number} min - * @param {number} max - * @return {object[]} - * @protected - */ - buildLookupTable(timestamps, min, max) { - return [ - {time: min, pos: 0}, - {time: max, pos: 1} - ]; - } - /** * @param {number} value * @return {string} @@ -586,14 +528,23 @@ class TimeScale extends Scale { } } + /** + * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC) + * @return {number} + */ + getDecimalForValue(value) { + const me = this; + return (value - me.min) / (me.max - me.min); + } + /** * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC) * @return {number} */ getPixelForValue(value) { const me = this; const offsets = me._offsets; - const pos = interpolate(me._table, 'time', value, 'pos'); + const pos = me.getDecimalForValue(value); return me.getPixelForDecimal((offsets.start + pos) * offsets.factor); } @@ -605,7 +556,7 @@ class TimeScale extends Scale { const me = this; const offsets = me._offsets; const pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end; - return interpolate(me._table, 'pos', pos, 'time'); + return me.min + pos * (me.max - me.min); } /**
true
Other
chartjs
Chart.js
1c2a03225ed761e75709a9184c184a697e2ce3cf.json
Remove lookup table from TimeScale (#7532) * Add getDecimalForValue * Move interpolate to timeseries scale * Remove getTimestampsForTable from time scale * Remove parameters from buildLookupTable * Restore getValueForPixel * Remove table from time scale
src/scales/scale.timeseries.js
@@ -1,5 +1,30 @@ import TimeScale from './scale.time'; -import {_arrayUnique} from '../helpers/helpers.collection'; +import {_arrayUnique, _lookupByKey} from '../helpers/helpers.collection'; + +/** + * Linearly interpolates the given source `value` using the table items `skey` values and + * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos') + * returns the position for a timestamp equal to 42. If value is out of bounds, values at + * index [0, 1] or [n - 1, n] are used for the interpolation. + * @param {object} table + * @param {string} skey + * @param {number} sval + * @param {string} tkey + * @return {object} + */ +function interpolate(table, skey, sval, tkey) { + const {lo, hi} = _lookupByKey(table, skey, sval); + + // Note: the lookup table ALWAYS contains at least 2 items (min and max) + const prev = table[lo]; + const next = table[hi]; + + const span = next[skey] - prev[skey]; + const ratio = span ? (sval - prev[skey]) / span : 0; + const offset = (next[tkey] - prev[tkey]) * ratio; + + return prev[tkey] + offset; +} /** * @param {number} a @@ -12,29 +37,19 @@ function sorter(a, b) { class TimeSeriesScale extends TimeScale { /** - * Returns all timestamps - * @protected + * @param {object} props */ - getTimestampsForTable() { - const me = this; - let timestamps = me._cache.all || []; - - if (timestamps.length) { - return timestamps; - } + constructor(props) { + super(props); - const data = me.getDataTimestamps(); - const label = me.getLabelTimestamps(); - if (data.length && label.length) { - // If combining labels and data (data might not contain all labels), - // we need to recheck uniqueness and sort - timestamps = _arrayUnique(data.concat(label).sort(sorter)); - } else { - timestamps = data.length ? data : label; - } - timestamps = me._cache.all = timestamps; + /** @type {object[]} */ + this._table = []; + } - return timestamps; + initOffsets(timestamps) { + const me = this; + me._table = me.buildLookupTable(); + super.initOffsets(timestamps); } /** @@ -45,13 +60,13 @@ class TimeSeriesScale extends TimeScale { * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need * to create the lookup table. The table ALWAYS contains at least two items: min and max. * - * @param {number[]} timestamps - timestamps sorted from lowest to highest. - * @param {number} min - * @param {number} max * @return {object[]} * @protected */ - buildLookupTable(timestamps, min, max) { + buildLookupTable() { + const me = this; + const {min, max} = me; + const timestamps = me._getTimestampsForTable(); if (!timestamps.length) { return [ {time: min, pos: 0}, @@ -86,6 +101,40 @@ class TimeSeriesScale extends TimeScale { return table; } + /** + * Returns all timestamps + * @private + */ + _getTimestampsForTable() { + const me = this; + let timestamps = me._cache.all || []; + + if (timestamps.length) { + return timestamps; + } + + const data = me.getDataTimestamps(); + const label = me.getLabelTimestamps(); + if (data.length && label.length) { + // If combining labels and data (data might not contain all labels), + // we need to recheck uniqueness and sort + timestamps = _arrayUnique(data.concat(label).sort(sorter)); + } else { + timestamps = data.length ? data : label; + } + timestamps = me._cache.all = timestamps; + + return timestamps; + } + + /** + * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC) + * @return {number} + */ + getDecimalForValue(value) { + return interpolate(this._table, 'time', value, 'pos'); + } + /** * @protected */ @@ -121,6 +170,17 @@ class TimeSeriesScale extends TimeScale { // We could assume labels are in order and unique - but let's not return (me._cache.labels = timestamps); } + + /** + * @param {number} pixel + * @return {number} + */ + getValueForPixel(pixel) { + const me = this; + const offsets = me._offsets; + const pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end; + return interpolate(me._table, 'pos', pos, 'time'); + } } TimeSeriesScale.id = 'timeseries';
true
Other
chartjs
Chart.js
537cd749192a211225414804ba0f38a2c6f1811c.json
Update the legend object during beforeUpdate (#7528) * Update the legend object during beforeUpdate When the legend is updated in afterUpdate, the position is not updated before the layout system runs. When the event that the legend position was changed, the legend would not move to the new position in the layout system. This causes the chart to render incorrectly because the layout system handled the layout as if the legend was still at the original position. The update is split into two passes to ensure that labels still update correctly after datasets (#6968)
src/plugins/plugin.legend.js
@@ -728,7 +728,10 @@ export default { } }, - afterUpdate(chart) { + // During the beforeUpdate step, the layout configuration needs to run + // This ensures that if the legend position changes (via an option update) + // the layout system respects the change. See https://github.com/chartjs/Chart.js/issues/7527 + beforeUpdate(chart) { const legendOpts = chart.options.legend; const legend = chart.legend; @@ -738,7 +741,6 @@ export default { if (legend) { layouts.configure(chart, legend, legendOpts); legend.options = legendOpts; - legend.buildLabels(); } else { createNewLegendAndAttach(chart, legendOpts); } @@ -748,6 +750,15 @@ 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) { + if (chart.legend) { + chart.legend.buildLabels(); + } + }, + + afterEvent(chart, e) { const legend = chart.legend; if (legend) {
false
Other
chartjs
Chart.js
99580664af941cf4caf19e2dd5f802689a96d1b8.json
Remove babel from tests (#7521) * Remove babel from tests * Remove unused require
karma.conf.js
@@ -1,6 +1,5 @@ /* eslint-disable import/no-commonjs */ -const babel = require('rollup-plugin-babel'); const commonjs = require('@rollup/plugin-commonjs'); const json = require('@rollup/plugin-json'); const resolve = require('@rollup/plugin-node-resolve').default; @@ -81,7 +80,6 @@ module.exports = function(karma) { plugins: [ json(), resolve(), - babel({exclude: 'node_modules/**'}), // use babel since we have ES proposal features commonjs({exclude: ['src/**', 'test/**']}), webWorkerLoader() ],
false
Other
chartjs
Chart.js
2e4d623bf3b2974b3873584fb85cf97d9ffb6721.json
Tooltip: Provide argument for custom callback (#7522)
src/plugins/plugin.tooltip.js
@@ -669,7 +669,7 @@ export class Tooltip extends Element { } if (changed && options.custom) { - options.custom.call(me); + options.custom.call(me, [me]); } }
false
Other
chartjs
Chart.js
c439d816fac9625cde848300f745d29acdfaf469.json
Fix initial animations (#7511) * Fix initial animations * CC
src/core/core.controller.js
@@ -229,7 +229,7 @@ class Chart { this.$plugins = undefined; this.$proxies = {}; this._hiddenIndices = {}; - this.attached = true; + this.attached = false; // Add the chart instance to the global namespace Chart.instances[me.id] = me; @@ -333,16 +333,13 @@ class Chart { retinaScale(me, newRatio); if (!silent) { - // Notify any plugins about the resize plugins.notify(me, 'resize', [newSize]); - // Notify of resize - if (options.onResize) { - options.onResize(me, newSize); - } + callCallback(options.onResize, [newSize], me); - // Only apply 'resize' mode if we are attached, else do a regular update. - me.update(me.attached && 'resize'); + if (me.attached) { + me.update('resize'); + } } }
false
Other
chartjs
Chart.js
988464323f2bc3d60e608676eefef3526e61a58c.json
Remove lineHeight property from LegendTitlt (#7508) The updates * removes `lineHeight` property from LegendTitle because already defined into Font. * changes the link tp `Fonts.md` because it was wrong.
docs/docs/configuration/legend.md
@@ -50,7 +50,7 @@ The legend label configuration is nested below the legend configuration using th | ---- | ---- | ------- | ----------- | `boxWidth` | `number` | `40` | Width of coloured box. | `boxHeight` | `number` | fontSize | Height of the coloured box. -| `font` | `Font` | `defaults.font` | See [Fonts](fonts.md) +| `font` | `Font` | `defaults.font` | See [Fonts](../general/fonts.md) | `padding` | `number` | `10` | Padding between rows of colored boxes. | `generateLabels` | `function` | | Generates legend items for each thing in the legend. Default implementation returns the text + styling for the color box. See [Legend Item](#legend-item-interface) for details. | `filter` | `function` | `null` | Filters legend items out of the legend. Receives 2 parameters, a [Legend Item](#legend-item-interface) and the chart data. @@ -63,8 +63,7 @@ The legend title configuration is nested below the legend configuration using th | Name | Type | Default | Description | ---- | ---- | ------- | ----------- | `display` | `boolean` | `false` | Is the legend title displayed. -| `font` | `Font` | `defaults.font` | See [Fonts](fonts.md) -| `lineHeight` | `number` | | Line height of the text. If unset, is computed from the font size. +| `font` | `Font` | `defaults.font` | See [Fonts](../general/fonts.md) | `padding` | <code>number&#124;object</code> | `0` | Padding around the title. If specified as a number, it applies evenly to all sides. | `text` | `string` | | The string title.
false
Other
chartjs
Chart.js
1bfd1daa75481968b4fa58cb88b46c2db8fa05f3.json
Relocate array utils to helpers.collection (#7498)
src/core/core.datasetController.js
@@ -1,5 +1,6 @@ import Animations from './core.animations'; import {isObject, merge, _merger, isArray, valueOrDefault, mergeIf} from '../helpers/helpers.core'; +import {listenArrayEvents, unlistenArrayEvents} from '../helpers/helpers.collection'; import {resolve} from '../helpers/helpers.options'; import {getHoverColor} from '../helpers/helpers.color'; import {sign} from '../helpers/helpers.math'; @@ -9,49 +10,6 @@ import {sign} from '../helpers/helpers.math'; * @typedef { import("./core.scale").default } Scale */ -const arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift']; - -/** - * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice', - * 'unshift') and notify the listener AFTER the array has been altered. Listeners are - * called on the '_onData*' callbacks (e.g. _onDataPush, etc.) with same arguments. - */ -function listenArrayEvents(array, listener) { - if (array._chartjs) { - array._chartjs.listeners.push(listener); - return; - } - - Object.defineProperty(array, '_chartjs', { - configurable: true, - enumerable: false, - value: { - listeners: [listener] - } - }); - - arrayEvents.forEach((key) => { - const method = '_onData' + key.charAt(0).toUpperCase() + key.slice(1); - const base = array[key]; - - Object.defineProperty(array, key, { - configurable: true, - enumerable: false, - value(...args) { - const res = base.apply(this, args); - - array._chartjs.listeners.forEach((object) => { - if (typeof object[method] === 'function') { - object[method](...args); - } - }); - - return res; - } - }); - }); -} - function scaleClip(scale, allowedOverflow) { const opts = scale && scale.options || {}; const reverse = opts.reverse; @@ -98,33 +56,6 @@ function toClip(value) { }; } -/** - * Removes the given array event listener and cleanup extra attached properties (such as - * the _chartjs stub and overridden methods) if array doesn't have any more listeners. - */ -function unlistenArrayEvents(array, listener) { - const stub = array._chartjs; - if (!stub) { - return; - } - - const listeners = stub.listeners; - const index = listeners.indexOf(listener); - if (index !== -1) { - listeners.splice(index, 1); - } - - if (listeners.length > 0) { - return; - } - - arrayEvents.forEach((key) => { - delete array[key]; - }); - - delete array._chartjs; -} - function getSortedDatasetIndices(chart, filterVisible) { const keys = []; const metasets = chart._getSortedDatasetMetas(filterVisible);
true
Other
chartjs
Chart.js
1bfd1daa75481968b4fa58cb88b46c2db8fa05f3.json
Relocate array utils to helpers.collection (#7498)
src/helpers/helpers.collection.js
@@ -91,3 +91,74 @@ export function _filterBetween(values, min, max) { ? values.slice(start, end) : values; } + +const arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift']; + +/** + * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice', + * 'unshift') and notify the listener AFTER the array has been altered. Listeners are + * called on the '_onData*' callbacks (e.g. _onDataPush, etc.) with same arguments. + */ +export function listenArrayEvents(array, listener) { + if (array._chartjs) { + array._chartjs.listeners.push(listener); + return; + } + + Object.defineProperty(array, '_chartjs', { + configurable: true, + enumerable: false, + value: { + listeners: [listener] + } + }); + + arrayEvents.forEach((key) => { + const method = '_onData' + key.charAt(0).toUpperCase() + key.slice(1); + const base = array[key]; + + Object.defineProperty(array, key, { + configurable: true, + enumerable: false, + value(...args) { + const res = base.apply(this, args); + + array._chartjs.listeners.forEach((object) => { + if (typeof object[method] === 'function') { + object[method](...args); + } + }); + + return res; + } + }); + }); +} + + +/** + * Removes the given array event listener and cleanup extra attached properties (such as + * the _chartjs stub and overridden methods) if array doesn't have any more listeners. + */ +export function unlistenArrayEvents(array, listener) { + const stub = array._chartjs; + if (!stub) { + return; + } + + const listeners = stub.listeners; + const index = listeners.indexOf(listener); + if (index !== -1) { + listeners.splice(index, 1); + } + + if (listeners.length > 0) { + return; + } + + arrayEvents.forEach((key) => { + delete array[key]; + }); + + delete array._chartjs; +}
true
Other
chartjs
Chart.js
fc65679a07d2d0ab20e252cee292c671569e9aab.json
Use consistent option context for scales (#7499)
src/core/core.scale.js
@@ -1119,8 +1119,10 @@ export default class Scale extends Element { const items = []; let context = { + chart, scale: me, tick: ticks[0], + index: 0, }; const axisWidth = gridLines.drawBorder ? resolve([gridLines.borderWidth, gridLines.lineWidth, 0], context, 0) : 0; const axisHalfWidth = axisWidth / 2; @@ -1187,8 +1189,10 @@ export default class Scale extends Element { const tick = ticks[i] || {}; context = { + chart, scale: me, tick, + index: i, }; const lineWidth = resolve([gridLines.lineWidth], context, i); @@ -1328,8 +1332,10 @@ export default class Scale extends Element { const ctx = me.ctx; const chart = me.chart; let context = { + chart, scale: me, tick: me.ticks[0], + index: 0, }; const axisWidth = gridLines.drawBorder ? resolve([gridLines.borderWidth, gridLines.lineWidth, 0], context, 0) : 0; const items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea)); @@ -1372,8 +1378,10 @@ export default class Scale extends Element { // Draw the line at the edge of the axis const firstLineWidth = axisWidth; context = { + chart, scale: me, tick: me.ticks[me._ticksLength - 1], + index: me._ticksLength - 1, }; const lastLineWidth = resolve([gridLines.lineWidth, 1], context, me._ticksLength - 1); const borderValue = me._borderValue;
false
Other
chartjs
Chart.js
41f0f12af8c1693c0cbe6772715e6000352b6e0a.json
Remove unused _scaleStacked cache (#7494)
src/core/core.datasetController.js
@@ -234,7 +234,6 @@ export default class DatasetController { this._parsing = false; this._data = undefined; this._objectData = undefined; - this._scaleStacked = {}; this.initialize(); } @@ -661,21 +660,6 @@ export default class DatasetController { return values; } - /** - * @private - */ - _cacheScaleStackStatus() { - const me = this; - const meta = me._cachedMeta; - const iScale = meta.iScale; - const vScale = meta.vScale; - const cache = me._scaleStacked = {}; - if (iScale && vScale) { - cache[iScale.id] = iScale.options.stacked; - cache[vScale.id] = vScale.options.stacked; - } - } - /** * @return {number|boolean} * @protected @@ -710,7 +694,6 @@ export default class DatasetController { me._cachedDataOpts = {}; me.update(mode); meta._clip = toClip(valueOrDefault(me._config.clip, defaultClip(meta.xScale, meta.yScale, me.getMaxOverflow()))); - me._cacheScaleStackStatus(); } /**
false
Other
chartjs
Chart.js
ac8142b4dc37154ee266f44dc541932a87c34fac.json
Fix link to animations docs (#7484)
docs/docs/developers/api.md
@@ -30,7 +30,7 @@ myLineChart.update(); // Calling update now animates the position of March from > **Note:** replacing the data reference (e.g. `myLineChart.data = {datasets: [...]}` only works starting **version 2.6**. Prior that, replacing the entire data object could be achieved with the following workaround: `myLineChart.config.data = {datasets: [...]}`. -A `mode` string can be provided to indicate what should be updated and what animation configuration should be used. Core calls this method using any of `'active'`, `'hide'`, `'reset'`, `'resize'`, `'show'` or `undefined`. `'none'` is also a supported mode for skipping animations for single update. Please see [animations](../configuration/animations.md) docs for more details. +A `mode` string can be provided to indicate what should be updated and what animation configuration should be used. Core calls this method using any of `'active'`, `'hide'`, `'reset'`, `'resize'`, `'show'` or `undefined`. `'none'` is also a supported mode for skipping animations for single update. Please see [animations](../configuration/animations.mdx) docs for more details. Example: @@ -178,15 +178,15 @@ var visible = chart.getDataVisibility(2); ## hide(datasetIndex) -Sets the visibility for the given dataset to false. Updates the chart and animates the dataset with `'hide'` mode. This animation can be configured under the `hide` key in animation options. Please see [animations](../configuration/animations.md) docs for more details. +Sets the visibility for the given dataset to false. Updates the chart and animates the dataset with `'hide'` mode. This animation can be configured under the `hide` key in animation options. Please see [animations](../configuration/animations.mdx) docs for more details. ```javascript chart.hide(1); // hides dataset at index 1 and does 'hide' animation. ``` ## show(datasetIndex) -Sets the visibility for the given dataset to true. Updates the chart and animates the dataset with `'show'` mode. This animation can be configured under the `show` key in animation options. Please see [animations](../configuration/animations.md) docs for more details. +Sets the visibility for the given dataset to true. Updates the chart and animates the dataset with `'show'` mode. This animation can be configured under the `show` key in animation options. Please see [animations](../configuration/animations.mdx) docs for more details. ```javascript chart.show(1); // shows dataset at index 1 and does 'show' animation.
true
Other
chartjs
Chart.js
ac8142b4dc37154ee266f44dc541932a87c34fac.json
Fix link to animations docs (#7484)
docs/docs/getting-started/v3-migration.md
@@ -151,7 +151,7 @@ options: { #### Animations -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. +Animation system was completely rewritten in Chart.js v3. Each property can now be animated separately. Please see [animations](../configuration/animations.mdx) docs for details. #### Customizability
true
Other
chartjs
Chart.js
6e02f3025207abe00e425506aa2ceda019069c1d.json
Remove unused parameter (#7480)
src/scales/scale.linearbase.js
@@ -6,22 +6,12 @@ import Scale from '../core/core.scale'; * Implementation of the nice number algorithm used in determining where axis labels will go * @return {number} */ -function niceNum(range, round) { +function niceNum(range) { const exponent = Math.floor(log10(range)); const fraction = range / Math.pow(10, exponent); let niceFraction; - if (round) { - if (fraction < 1.5) { - niceFraction = 1; - } else if (fraction < 3) { - niceFraction = 2; - } else if (fraction < 7) { - niceFraction = 5; - } else { - niceFraction = 10; - } - } else if (fraction <= 1.0) { + if (fraction <= 1.0) { niceFraction = 1; } else if (fraction <= 2) { niceFraction = 2;
false
Other
chartjs
Chart.js
8e7bde25c46c3c76c9c10119e93d2ea744e13f70.json
Remove data checks and always re-parse data (#7458) * Remove data checks and always re-parse data * Fix removed helper namespace
docs/docs/getting-started/v3-migration.md
@@ -250,6 +250,7 @@ The following properties and methods were removed: * `helpers.addEvent` * `helpers.aliasPixel` +* `helpers.arrayEquals` * `helpers.configMerge` * `helpers.findIndex` * `helpers.findNextWhere`
true
Other
chartjs
Chart.js
8e7bde25c46c3c76c9c10119e93d2ea744e13f70.json
Remove data checks and always re-parse data (#7458) * Remove data checks and always re-parse data * Fix removed helper namespace
src/core/core.datasetController.js
@@ -1,5 +1,5 @@ import Animations from './core.animations'; -import {isObject, merge, _merger, isArray, valueOrDefault, mergeIf, arrayEquals} from '../helpers/helpers.core'; +import {isObject, merge, _merger, isArray, valueOrDefault, mergeIf} from '../helpers/helpers.core'; import {resolve} from '../helpers/helpers.options'; import {getHoverColor} from '../helpers/helpers.color'; import {sign} from '../helpers/helpers.math'; @@ -233,10 +233,7 @@ export default class DatasetController { this._config = undefined; this._parsing = false; this._data = undefined; - this._dataCopy = undefined; - this._dataModified = false; this._objectData = undefined; - this._labels = undefined; this._scaleStacked = {}; this.initialize(); @@ -339,7 +336,6 @@ export default class DatasetController { } /** - * @return {boolean} whether the data was modified * @private */ _dataCheck() { @@ -352,50 +348,17 @@ export default class DatasetController { // the internal meta data accordingly. if (isObject(data)) { - // Object data is currently monitored for replacement only - if (me._objectData === data) { - return false; - } me._data = convertObjectDataToArray(data); - me._objectData = data; - } else { - if (me._data === data && !me._dataModified && arrayEquals(data, me._dataCopy)) { - return false; - } - + } else if (me._data !== data) { if (me._data) { // This case happens when the user replaced the data array instance. unlistenArrayEvents(me._data, me); } - - // Store a copy to detect direct modifications. - // Note: This is suboptimal, but better than always parsing the data - me._dataCopy = data.slice(0); - - me._dataModified = false; - if (data && Object.isExtensible(data)) { listenArrayEvents(data, me); } me._data = data; } - return true; - } - - /** - * @private - */ - _labelCheck() { - const me = this; - const iScale = me._cachedMeta.iScale; - const labels = iScale ? iScale.getLabels() : me.chart.data.labels; - - if (me._labels === labels) { - return false; - } - - me._labels = labels; - return true; } addElements() { @@ -418,13 +381,12 @@ export default class DatasetController { buildOrUpdateElements() { const me = this; - const dataChanged = me._dataCheck(); - const labelsChanged = me._labelCheck(); - const scaleChanged = me._scaleCheck(); const meta = me._cachedMeta; const dataset = me.getDataset(); let stackChanged = false; + me._dataCheck(); + // make sure cached _stacked status is current meta._stacked = isStacked(meta.vScale, meta); @@ -440,7 +402,7 @@ export default class DatasetController { // Re-sync meta data in case the user replaced the data array or if we missed // any updates and so make sure that we handle number of datapoints changing. - me._resyncElements(dataChanged || labelsChanged || scaleChanged || stackChanged); + me._resyncElements(); // if stack changed, update stack values for the whole dataset if (stackChanged) { @@ -708,22 +670,6 @@ export default class DatasetController { } } - /** - * @private - */ - _scaleCheck() { - const me = this; - const meta = me._cachedMeta; - const iScale = meta.iScale; - const vScale = meta.vScale; - const cache = me._scaleStacked; - return !cache || - !iScale || - !vScale || - cache[iScale.id] !== iScale.options.stacked || - cache[vScale.id] !== vScale.options.stacked; - } - /** * @return {number|boolean} * @protected @@ -1049,25 +995,20 @@ export default class DatasetController { /** * @private */ - _resyncElements(changed) { + _resyncElements() { const me = this; const meta = me._cachedMeta; const numMeta = meta.data.length; const numData = me._data.length; if (numData > numMeta) { me._insertElements(numMeta, numData - numMeta); - if (changed && numMeta) { - // _insertElements parses the new elements. The old ones might need parsing too. - me.parse(0, numMeta); - } } else if (numData < numMeta) { meta.data.splice(numData, numMeta - numData); meta._parsed.splice(numData, numMeta - numData); - me.parse(0, numData); - } else if (changed) { - me.parse(0, numData); } + // Re-parse the old elements (new elements are parsed in _insertElements) + me.parse(0, Math.min(numData, numMeta)); } /** @@ -1113,23 +1054,20 @@ export default class DatasetController { _onDataPush() { const count = arguments.length; this._insertElements(this.getDataset().data.length - count, count); - this._dataModified = true; } /** * @private */ _onDataPop() { this._removeElements(this._cachedMeta.data.length - 1, 1); - this._dataModified = true; } /** * @private */ _onDataShift() { this._removeElements(0, 1); - this._dataModified = true; } /** @@ -1138,15 +1076,13 @@ export default class DatasetController { _onDataSplice(start, count) { this._removeElements(start, count); this._insertElements(start, arguments.length - 2); - this._dataModified = true; } /** * @private */ _onDataUnshift() { this._insertElements(0, arguments.length); - this._dataModified = true; } }
true
Other
chartjs
Chart.js
8e7bde25c46c3c76c9c10119e93d2ea744e13f70.json
Remove data checks and always re-parse data (#7458) * Remove data checks and always re-parse data * Fix removed helper namespace
src/helpers/helpers.core.js
@@ -131,37 +131,6 @@ export function each(loopable, fn, thisArg, reverse) { } } -/** - * Returns true if the `a0` and `a1` arrays have the same content, else returns false. - * @see https://stackoverflow.com/a/14853974 - * @param {Array} a0 - The array to compare - * @param {Array} a1 - The array to compare - * @returns {boolean} - */ -export function arrayEquals(a0, a1) { - let i, ilen, v0, v1; - - if (!a0 || !a1 || a0.length !== a1.length) { - return false; - } - - for (i = 0, ilen = a0.length; i < ilen; ++i) { - v0 = a0[i]; - v1 = a1[i]; - - if (v0 instanceof Array && v1 instanceof Array) { - if (!arrayEquals(v0, v1)) { - return false; - } - } else if (v0 !== v1) { - // NOTE: two different object instances will never be equal: {x:20} != {x:20} - return false; - } - } - - return true; -} - /** * Returns true if the `a0` and `a1` arrays have the same content, else returns false. * @param {Array} a0 - The array to compare
true
Other
chartjs
Chart.js
8e7bde25c46c3c76c9c10119e93d2ea744e13f70.json
Remove data checks and always re-parse data (#7458) * Remove data checks and always re-parse data * Fix removed helper namespace
test/specs/core.datasetController.tests.js
@@ -369,6 +369,30 @@ describe('Chart.DatasetController', function() { expect(meta.data[0].x).toEqual(firstX); }); + // https://github.com/chartjs/Chart.js/issues/7445 + it('should re-synchronize metadata when data is objects and directly altered', function() { + var data = [{x: 'a', y: 1}, {x: 'b', y: 2}, {x: 'c', y: 3}]; + var chart = acquireChart({ + type: 'line', + data: { + labels: ['a', 'b', 'c'], + datasets: [{ + data, + fill: true + }] + } + }); + + var meta = chart.getDatasetMeta(0); + + expect(meta.data.length).toBe(3); + const y3 = meta.data[2].y; + + data[0].y = 3; + chart.update(); + expect(meta.data[0].y).toEqual(y3); + }); + it('should re-synchronize metadata when scaleID changes', function() { var chart = acquireChart({ type: 'line',
true
Other
chartjs
Chart.js
8e7bde25c46c3c76c9c10119e93d2ea744e13f70.json
Remove data checks and always re-parse data (#7458) * Remove data checks and always re-parse data * Fix removed helper namespace
test/specs/helpers.core.tests.js
@@ -241,29 +241,6 @@ describe('Chart.helpers.core', function() { }); }); - describe('arrayEquals', function() { - it('should return false if arrays are not the same', function() { - expect(helpers.arrayEquals([], [42])).toBeFalsy(); - expect(helpers.arrayEquals([42], ['42'])).toBeFalsy(); - expect(helpers.arrayEquals([1, 2, 3], [1, 2, 3, 4])).toBeFalsy(); - expect(helpers.arrayEquals(['foo', 'bar'], ['bar', 'foo'])).toBeFalsy(); - expect(helpers.arrayEquals([1, 2, 3], [1, 2, 'foo'])).toBeFalsy(); - expect(helpers.arrayEquals([1, 2, [3, 4]], [1, 2, [3, 'foo']])).toBeFalsy(); - expect(helpers.arrayEquals([{a: 42}], [{a: 42}])).toBeFalsy(); - }); - it('should return false if arrays are not the same', function() { - var o0 = {}; - var o1 = {}; - var o2 = {}; - - expect(helpers.arrayEquals([], [])).toBeTruthy(); - expect(helpers.arrayEquals([1, 2, 3], [1, 2, 3])).toBeTruthy(); - expect(helpers.arrayEquals(['foo', 'bar'], ['foo', 'bar'])).toBeTruthy(); - expect(helpers.arrayEquals([true, false, true], [true, false, true])).toBeTruthy(); - expect(helpers.arrayEquals([o0, o1, o2], [o0, o1, o2])).toBeTruthy(); - }); - }); - describe('_elementsEqual', function() { it('should return true if arrays are the same', function() { expect(helpers._elementsEqual(
true
Other
chartjs
Chart.js
f3cfeb84205385655e8d492f3e6ceb4c24026874.json
Implement routing of defaults (#7453) Implement routing of defaults
docs/docs/configuration/elements.md
@@ -21,11 +21,11 @@ Global point options: `Chart.defaults.elements.point`. | Name | Type | Default | Description | ---- | ---- | ------- | ----------- | `radius` | `number` | `3` | Point radius. -| [`pointStyle`](#point-styles) | <code>string&#124;Image</code> | `'circle'` | Point style. +| [`pointStyle`](#point-styles) | `string`\|`Image` | `'circle'` | Point style. | `rotation` | `number` | `0` | Point rotation (in degrees). -| `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Point fill color. +| `backgroundColor` | `Color` | `Chart.defaults.color` | Point fill color. | `borderWidth` | `number` | `1` | Point stroke width. -| `borderColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Point stroke color. +| `borderColor` | `Color` | `Chart.defaults.color` | Point stroke color. | `hitRadius` | `number` | `1` | Extra radius added to point radius for hit detection. | `hoverRadius` | `number` | `4` | Point radius when hovered. | `hoverBorderWidth` | `number` | `1` | Stroke width when hovered. @@ -56,16 +56,16 @@ Global line options: `Chart.defaults.elements.line`. | Name | Type | Default | Description | ---- | ---- | ------- | ----------- | `tension` | `number` | `0.4` | Bézier curve tension (`0` for no Bézier curves). -| `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Line fill color. +| `backgroundColor` | `Color` | `Chart.defaults.color` | Line fill color. | `borderWidth` | `number` | `3` | Line stroke width. -| `borderColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Line stroke color. +| `borderColor` | `Color` | `Chart.defaults.color` | Line stroke color. | `borderCapStyle` | `string` | `'butt'` | Line cap style. See [MDN](https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap). | `borderDash` | `number[]` | `[]` | Line dash. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash). | `borderDashOffset` | `number` | `0.0` | Line dash offset. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset). | `borderJoinStyle` | `string` | `'miter'` | Line join style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin). | `capBezierPoints` | `boolean` | `true` | `true` to keep Bézier control inside the chart, `false` for no restriction. | `cubicInterpolationMode` | `string` | `'default'` | Interpolation mode to apply. [See more...](../charts/line.md#cubicinterpolationmode) -| `fill` | <code>boolean&#124;string</code> | `true` | How to fill the area under the line. See [area charts](../charts/area.md#filling-modes). +| `fill` | `boolean`\|`string` | `true` | How to fill the area under the line. See [area charts](../charts/area.md#filling-modes). | `stepped` | `boolean` | `false` | `true` to show the line as a stepped line (`tension` will be ignored). ## Rectangle Configuration @@ -76,9 +76,9 @@ Global rectangle options: `Chart.defaults.elements.rectangle`. | Name | Type | Default | Description | ---- | ---- | ------- | ----------- -| `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Bar fill color. +| `backgroundColor` | `Color` | `Chart.defaults.color` | Bar fill color. | `borderWidth` | `number` | `0` | Bar stroke width. -| `borderColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Bar stroke color. +| `borderColor` | `Color` | `Chart.defaults.color` | Bar stroke color. | `borderSkipped` | `string` | `'bottom'` | Skipped (excluded) border: `'bottom'`, `'left'`, `'top'` or `'right'`. ## Arc Configuration @@ -90,7 +90,7 @@ Global arc options: `Chart.defaults.elements.arc`. | Name | Type | Default | Description | ---- | ---- | ------- | ----------- | `angle` - for polar only | `number` | `circumference / (arc count)` | Arc angle to cover. -| `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Arc fill color. +| `backgroundColor` | `Color` | `Chart.defaults.color` | Arc fill color. | `borderAlign` | `string` | `'center'` | Arc stroke alignment. | `borderColor` | `Color` | `'#fff'` | Arc stroke color. | `borderWidth`| `number` | `2` | Arc stroke width.
true
Other
chartjs
Chart.js
f3cfeb84205385655e8d492f3e6ceb4c24026874.json
Implement routing of defaults (#7453) Implement routing of defaults
src/core/core.defaults.js
@@ -1,7 +1,25 @@ -import {merge} from '../helpers/helpers.core'; +import {merge, isArray, valueOrDefault} from '../helpers/helpers.core'; + +/** + * @param {object} node + * @param {string} key + * @return {object} + */ +function getScope(node, key) { + if (!key) { + return node; + } + const keys = key.split('.'); + for (let i = 0, n = keys.length; i < n; ++i) { + const k = keys[i]; + node = node[k] || (node[k] = {}); + } + return node; +} /** * Please use the module's default export which provides a singleton instance + * Note: class is exported for typedoc */ export class Defaults { constructor() { @@ -39,13 +57,63 @@ export class Defaults { this.title = undefined; this.tooltips = undefined; this.doughnut = undefined; + this._routes = {}; } /** * @param {string} scope * @param {*} values */ set(scope, values) { - return merge(this[scope] || (this[scope] = {}), values); + return merge(getScope(this, scope), values); + } + + /** + * Routes the named defaults to fallback to another scope/name. + * This routing is useful when those target values, like defaults.color, are changed runtime. + * If the values would be copied, the runtime change would not take effect. By routing, the + * fallback is evaluated at each access, so its always up to date. + * + * Examples: + * + * defaults.route('elements.arc', 'backgroundColor', '', 'color') + * - reads the backgroundColor from defaults.color when undefined locally + * + * defaults.route('elements.line', ['backgroundColor', 'borderColor'], '', 'color') + * - reads the backgroundColor and borderColor from defaults.color when undefined locally + * + * defaults.route('elements.customLine', ['borderWidth', 'tension'], 'elements.line', ['borderWidth', 'tension']) + * - reads the borderWidth and tension from elements.line when those are not defined in elements.customLine + * + * @param {string} scope Scope this route applies to. + * @param {string[]} names Names of the properties that should be routed to different namespace when not defined here. + * @param {string} targetScope The namespace where those properties should be routed to. Empty string ('') is the root of defaults. + * @param {string|string[]} targetNames The target name/names in the target scope the properties should be routed to. + */ + route(scope, names, targetScope, targetNames) { + const scopeObject = getScope(this, scope); + const targetScopeObject = getScope(this, targetScope); + const targetNamesIsArray = isArray(targetNames); + names.forEach((name, index) => { + const privateName = '_' + name; + const targetName = targetNamesIsArray ? targetNames[index] : targetNames; + Object.defineProperties(scopeObject, { + // A private property is defined to hold the actual value, when this property is set in its scope (set in the setter) + [privateName]: { + writable: true + }, + // The actual property is defined as getter/setter so we can do the routing when value is not locally set. + [name]: { + enumerable: true, + get() { + // @ts-ignore + return valueOrDefault(this[privateName], targetScopeObject[targetName]); + }, + set(value) { + this[privateName] = value; + } + } + }); + }); } }
true
Other
chartjs
Chart.js
f3cfeb84205385655e8d492f3e6ceb4c24026874.json
Implement routing of defaults (#7453) Implement routing of defaults
src/elements/element.arc.js
@@ -3,15 +3,15 @@ import Element from '../core/core.element'; import {_angleBetween, getAngleFromPoint} from '../helpers/helpers.math'; const TAU = Math.PI * 2; -defaults.set('elements', { - arc: { - backgroundColor: defaults.color, - borderAlign: 'center', - borderColor: '#fff', - borderWidth: 2 - } +const scope = 'elements.arc'; +defaults.set(scope, { + borderAlign: 'center', + borderColor: '#fff', + borderWidth: 2 }); +defaults.route(scope, ['backgroundColor'], '', ['color']); + function clipArc(ctx, model) { const {startAngle, endAngle, pixelMargin, x, y} = model; let angleMargin = pixelMargin / model.outerRadius;
true
Other
chartjs
Chart.js
f3cfeb84205385655e8d492f3e6ceb4c24026874.json
Implement routing of defaults (#7453) Implement routing of defaults
src/elements/element.line.js
@@ -9,23 +9,20 @@ import {_updateBezierControlPoints} from '../helpers/helpers.curve'; * @typedef { import("./element.point").default } Point */ -const defaultColor = defaults.color; - -defaults.set('elements', { - line: { - backgroundColor: defaultColor, - borderCapStyle: 'butt', - borderColor: defaultColor, - borderDash: [], - borderDashOffset: 0, - borderJoinStyle: 'miter', - borderWidth: 3, - capBezierPoints: true, - fill: true, - tension: 0.4 - } +const scope = 'elements.line'; +defaults.set(scope, { + borderCapStyle: 'butt', + borderDash: [], + borderDashOffset: 0, + borderJoinStyle: 'miter', + borderWidth: 3, + capBezierPoints: true, + fill: true, + tension: 0.4 }); +defaults.route(scope, ['backgroundColor', 'borderColor'], '', 'color'); + function setStyle(ctx, vm) { ctx.lineCap = vm.borderCapStyle; ctx.setLineDash(vm.borderDash);
true
Other
chartjs
Chart.js
f3cfeb84205385655e8d492f3e6ceb4c24026874.json
Implement routing of defaults (#7453) Implement routing of defaults
src/elements/element.point.js
@@ -2,21 +2,18 @@ import defaults from '../core/core.defaults'; import Element from '../core/core.element'; import {_isPointInArea, drawPoint} from '../helpers/helpers.canvas'; -const defaultColor = defaults.color; - -defaults.set('elements', { - point: { - backgroundColor: defaultColor, - borderColor: defaultColor, - borderWidth: 1, - hitRadius: 1, - hoverBorderWidth: 1, - hoverRadius: 4, - pointStyle: 'circle', - radius: 3 - } +const scope = 'elements.point'; +defaults.set(scope, { + borderWidth: 1, + hitRadius: 1, + hoverBorderWidth: 1, + hoverRadius: 4, + pointStyle: 'circle', + radius: 3 }); +defaults.route(scope, ['backgroundColor', 'borderColor'], '', 'color'); + class Point extends Element { constructor(cfg) {
true
Other
chartjs
Chart.js
f3cfeb84205385655e8d492f3e6ceb4c24026874.json
Implement routing of defaults (#7453) Implement routing of defaults
src/elements/element.rectangle.js
@@ -2,17 +2,14 @@ import defaults from '../core/core.defaults'; import Element from '../core/core.element'; import {isObject} from '../helpers/helpers.core'; -const defaultColor = defaults.color; - -defaults.set('elements', { - rectangle: { - backgroundColor: defaultColor, - borderColor: defaultColor, - borderSkipped: 'bottom', - borderWidth: 0 - } +const scope = 'elements.rectangle'; +defaults.set(scope, { + borderSkipped: 'bottom', + borderWidth: 0 }); +defaults.route(scope, ['backgroundColor', 'borderColor'], '', 'color'); + /** * Helper function to get the bounds of the bar regardless of the orientation * @param {Rectangle} bar the bar
true
Other
chartjs
Chart.js
f3cfeb84205385655e8d492f3e6ceb4c24026874.json
Implement routing of defaults (#7453) Implement routing of defaults
test/specs/core.datasetController.tests.js
@@ -502,4 +502,25 @@ describe('Chart.DatasetController', function() { expect(data1[hook]).toBe(Array.prototype[hook]); }); }); + + it('should resolve data element options to the default color', function() { + var data0 = [0, 1, 2, 3, 4, 5]; + var oldColor = Chart.defaults.color; + Chart.defaults.color = 'red'; + var chart = acquireChart({ + type: 'line', + data: { + datasets: [{ + data: data0 + }] + } + }); + + var meta = chart.getDatasetMeta(0); + expect(meta.dataset.options.borderColor).toBe('red'); + expect(meta.data[0].options.borderColor).toBe('red'); + + // Reset old shared state + Chart.defaults.color = oldColor; + }); });
true
Other
chartjs
Chart.js
2a8962c32559f82bab932b78bb1669f16dffda59.json
Document the context properties for ticks (#7399) Document the context properties for ticks
docs/docs/axes/cartesian/category.md
@@ -39,7 +39,7 @@ let chart = new Chart(ctx, { ## Tick Configuration Options -The category scale provides the following options for configuring tick marks. They are nested in the `ticks` sub object. These options extend the [common tick configuration](README.md#tick-configuration). +The category scale provides the following options for configuring tick marks. They are nested in the `ticks` sub object. These options extend the [common tick configuration](index.md#tick-configuration). | Name | Type | Default | Description | ---- | ---- | ------- | -----------
true
Other
chartjs
Chart.js
2a8962c32559f82bab932b78bb1669f16dffda59.json
Document the context properties for ticks (#7399) Document the context properties for ticks
docs/docs/axes/cartesian/index.md
@@ -11,15 +11,14 @@ Axes that follow a cartesian grid are known as 'Cartesian Axes'. Cartesian axes ## Common Configuration -All of the included cartesian axes support a number of common options. +All of the included cartesian axes support a number of common options. These options extend the [common configuration available to all types of axes](../index.md#common-configuration). | Name | Type | Default | Description | ---- | ---- | ------- | ----------- | `type` | `string` | | Type of scale being employed. Custom scales can be created and registered with a string key. This allows changing the type of an axis for a chart. | `position` | `string` | | Position of the axis. [more...](#axis-position) | `axis` | `string` | | Which type of axis this is. Possible values are: `'x'`, `'y'`. If not set, this is inferred from the first character of the ID which should be `'x'` or `'y'`. | `offset` | `boolean` | `false` | If true, extra space is added to the both edges and the axis is scaled to fit into the chart area. This is set to `true` for a bar chart by default. -| `id` | `string` | | The ID is used to link datasets and scale axes together. [more...](#axis-id) | `gridLines` | `object` | | Grid line configuration. [more...](../styling.md#grid-line-configuration) | `scaleLabel` | `object` | | Scale title configuration. [more...](../labelling.md#scale-title-configuration) | `ticks` | `object` | | Tick configuration. [more...](#tick-configuration) @@ -30,7 +29,7 @@ An axis can either be positioned at the edge of the chart, at the center of the To position the axis at the edge of the chart, set the `position` option to one of: `'top'`, `'left'`, `'bottom'`, `'right'`. To position the axis at the center of the chart area, set the `position` option to `'center'`. In this mode, either the `axis` option is specified or the axis ID starts with the letter 'x' or 'y'. -To position the axis with respect to a data value, set the `position` option to an object such as: +To position the axis with respect to a data value, set the `position` option to an object such as: ```javascript { @@ -41,6 +40,7 @@ To position the axis with respect to a data value, set the `position` option to This will position the axis at a value of -20 on the axis with ID "x". For cartesian axes, only 1 axis may be specified. ### Tick Configuration + The following options are common to all cartesian axes but do not apply to other axes. | Name | Type | Default | Description
true
Other
chartjs
Chart.js
2a8962c32559f82bab932b78bb1669f16dffda59.json
Document the context properties for ticks (#7399) Document the context properties for ticks
docs/docs/axes/cartesian/linear.md
@@ -6,6 +6,8 @@ The linear scale is use to chart numerical data. It can be placed on either the ## Configuration Options +These options extend the [common configuration for all cartesian axes](index.md#configuration-options). + | Name | Type | Description | ---- | ---- | ----------- | `beginAtZero` | `boolean` | if true, scale will include 0 if it is not already included. @@ -14,7 +16,7 @@ The linear scale is use to chart numerical data. It can be placed on either the ## Tick Configuration Options -The following options are provided by the linear scale. They are all located in the `ticks` sub options. These options extend the [common tick configuration](README.md#tick-configuration). +The following tick options are provided by the linear scale. They are all located in the `ticks` sub options. These options extend the [common tick configuration](index.md#tick-configuration). | Name | Type | Default | Description | ---- | ---- | ------- | -----------
true
Other
chartjs
Chart.js
2a8962c32559f82bab932b78bb1669f16dffda59.json
Document the context properties for ticks (#7399) Document the context properties for ticks
docs/docs/axes/cartesian/logarithmic.md
@@ -6,7 +6,7 @@ The logarithmic scale is use to chart numerical data. It can be placed on either ## Tick Configuration Options -The following options are provided by the linear scale. They are all located in the `ticks` sub options. These options extend the [common tick configuration](README.md#tick-configuration). +The following options are provided by the logarithmic scale. They are all located in the `ticks` sub options. These options extend the [common tick configuration](index.md#tick-configuration). | Name | Type | Default | Description | ---- | ---- | ------- | -----------
true
Other
chartjs
Chart.js
2a8962c32559f82bab932b78bb1669f16dffda59.json
Document the context properties for ticks (#7399) Document the context properties for ticks
docs/docs/axes/cartesian/time.md
@@ -30,7 +30,7 @@ When providing data for the time scale, Chart.js supports all of the formats tha ## Configuration Options -The following options are provided by the time scale. You may also set options provided by the [common tick configuration](README.md#tick-configuration). +The following options are provided by the time scale. You may also set options provided by the [common tick configuration](index.md#tick-configuration). | Name | Type | Default | Description | ---- | ---- | ------- | -----------
true
Other
chartjs
Chart.js
2a8962c32559f82bab932b78bb1669f16dffda59.json
Document the context properties for ticks (#7399) Document the context properties for ticks
docs/docs/axes/index.md
@@ -2,9 +2,9 @@ title: Axes --- -Axes are an integral part of a chart. They are used to determine how data maps to a pixel value on the chart. In a cartesian chart, there is 1 or more X axis and 1 or more Y axis to map points onto the 2 dimensional canvas. These axes are known as ['cartesian axes'](./cartesian/README.md#cartesian-axes). +Axes are an integral part of a chart. They are used to determine how data maps to a pixel value on the chart. In a cartesian chart, there is 1 or more X axis and 1 or more Y axis to map points onto the 2 dimensional canvas. These axes are known as ['cartesian axes'](./cartesian/index.md#cartesian-axes). -In a radial chart, such as a radar chart or a polar area chart, there is a single axis that maps points in the angular and radial directions. These are known as ['radial axes'](./radial/README.md#radial-axes). +In a radial chart, such as a radar chart or a polar area chart, there is a single axis that maps points in the angular and radial directions. These are known as ['radial axes'](./radial/index.md#radial-axes). Scales in Chart.js >v2.0 are significantly more powerful, but also different than those of v1.0. @@ -15,11 +15,11 @@ Scales in Chart.js >v2.0 are significantly more powerful, but also different tha ## Common Configuration -The following properties are common to all axes provided by Chart.js. +The following options are common to all axes provided by Chart.js. | Name | Type | Default | Description | ---- | ---- | ------- | ----------- -| `display` | <code>boolean&#124;string</code> | `true` | Controls the axis global visibility (visible when `true`, hidden when `false`). When `display: 'auto'`, the axis is visible only if at least one associated dataset is visible. +| `display` | `boolean`\|`string` | `true` | Controls the axis global visibility (visible when `true`, hidden when `false`). When `display: 'auto'`, the axis is visible only if at least one associated dataset is visible. | `weight` | `number` | `0` | The weight used to sort the axis. Higher weights are further away from the chart area. ### Callbacks
true
Other
chartjs
Chart.js
2a8962c32559f82bab932b78bb1669f16dffda59.json
Document the context properties for ticks (#7399) Document the context properties for ticks
docs/docs/axes/labelling.md
@@ -14,7 +14,7 @@ The scale label configuration is nested under the scale configuration in the `sc | `align` | `string` | `'center'` | Alignment of the axis title. Possible options are `'start'`, `'center'` and `'end'` | `labelString` | `string` | `''` | The text for the title. (i.e. "# of People" or "Response Choices"). | `font` | `Font` | `defaults.font` | See [Fonts](fonts.md) -| `padding` | <code>number&#124;object</code> | `4` | Padding to apply around scale labels. Only `top` and `bottom` are implemented. +| `padding` | `number`\|`object` | `4` | Padding to apply around scale labels. Only `top` and `bottom` are implemented. ## Creating Custom Tick Formats
true
Other
chartjs
Chart.js
2a8962c32559f82bab932b78bb1669f16dffda59.json
Document the context properties for ticks (#7399) Document the context properties for ticks
docs/docs/axes/radial/index.md
@@ -4,4 +4,4 @@ title: Radial Axes Radial axes are used specifically for the radar and polar area chart types. These axes overlay the chart area, rather than being positioned on one of the edges. One radial axis is included by default in Chart.js. -* [linear](./linear.md#linear-radial-axis) +* [radialLinear](./linear.md#linear-radial-axis)
true
Other
chartjs
Chart.js
2a8962c32559f82bab932b78bb1669f16dffda59.json
Document the context properties for ticks (#7399) Document the context properties for ticks
docs/docs/axes/styling.md
@@ -8,50 +8,55 @@ There are a number of options to allow styling an axis. There are settings to co The grid line configuration is nested under the scale configuration in the `gridLines` key. It defines options for the grid lines that run perpendicular to the axis. -| Name | Type | Default | Description -| ---- | ---- | ------- | ----------- -| `display` | `boolean` | `true` | If false, do not display grid lines for this axis. -| `borderColor` | `Color` | | If set, used as the color of the border line. If unset, the first `color` option is resolved and used. -| `borderWidth` | `number` | | If set, used as the width of the border line. If unset, the first `lineWidth` option is resolved and used. -| `circular` | `boolean` | `false` | If true, gridlines are circular (on radar chart only). -| `color` | <code>Color&#124;Color[]&#124;function</code> | `'rgba(0, 0, 0, 0.1)'` | The color of the grid lines. If specified as an array, the first color applies to the first grid line, the second to the second grid line and so on. -| `borderDash` | `number[]` | `[]` | Length and spacing of dashes on grid lines. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash). -| `borderDashOffset` | <code>number&#124;function</code> | `0.0` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset). -| `lineWidth` | <code>number&#124;number[]&#124;function</code> | `1` | Stroke width of grid lines. -| `drawBorder` | `boolean` | `true` | If true, draw border at the edge between the axis and the chart area. -| `drawOnChartArea` | `boolean` | `true` | If true, draw lines on the chart area inside the axis lines. This is useful when there are multiple axes and you need to control which grid lines are drawn. -| `drawTicks` | `boolean` | `true` | If true, draw lines beside the ticks in the axis area beside the chart. -| `tickMarkLength` | `number` | `10` | Length in pixels that the grid lines will draw into the axis area. -| `offsetGridLines` | `boolean` | `false` | If true, grid lines will be shifted to be between labels. This is set to `true` for a bar chart by default. -| `z` | `number` | `0` | z-index of gridline layer. Values &lt;= 0 are drawn under datasets, &gt; 0 on top. - -For function arguments, the function is passed a context object that is of the form: - -```javscript +| Name | Type | Scriptable | Indexable | Default | Description +| ---- | ---- | :-------------------------------: | :-----------------------------: | ------- | ----------- +| `display` | `boolean` | | | `true` | If false, do not display grid lines for this axis. +| `borderColor` | [`Color`](../general/colors.md) | | | | If set, used as the color of the border line. If unset, the first `color` option is resolved and used. +| `borderWidth` | `number` | | | | If set, used as the width of the border line. If unset, the first `lineWidth` option is resolved and used. +| `circular` | `boolean` | | | `false` | If true, gridlines are circular (on radar chart only). +| `color` | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'` | The color of the grid lines. If specified as an array, the first color applies to the first grid line, the second to the second grid line and so on. +| `borderDash` | `number[]` | | | `[]` | Length and spacing of dashes on grid lines. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash). +| `borderDashOffset` | `number` | Yes | | `0.0` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset). +| `lineWidth` | `number` | Yes | Yes | `1` | Stroke width of grid lines. +| `drawBorder` | `boolean` | | | `true` | If true, draw border at the edge between the axis and the chart area. +| `drawOnChartArea` | `boolean` | | | `true` | If true, draw lines on the chart area inside the axis lines. This is useful when there are multiple axes and you need to control which grid lines are drawn. +| `drawTicks` | `boolean` | | | `true` | If true, draw lines beside the ticks in the axis area beside the chart. +| `tickMarkLength` | `number` | | | `10` | Length in pixels that the grid lines will draw into the axis area. +| `offsetGridLines` | `boolean` | | | `false` | If true, grid lines will be shifted to be between labels. This is set to `true` for a bar chart by default. +| `z` | `number` | | | `0` | z-index of gridline layer. Values &lt;= 0 are drawn under datasets, &gt; 0 on top. + +The scriptable context has the following form: + +```javascript { - scale: // Scale object - tick: // Tick object + chart, + scale, + index, + tick } ``` ## Tick Configuration The tick configuration is nested under the scale configuration in the `ticks` key. It defines options for the tick marks that are generated by the axis. -| Name | Type | [Scriptable](../general/options.md#scriptable-options) | Default | Description -| ---- | ---- | ------- | ----------- +| Name | Type | Scriptable | Default | Description +| ---- | ---- | :-------------------------------: | ------- | ----------- | `callback` | `function` | | | Returns the string representation of the tick value as it should be displayed on the chart. See [callback](../axes/labelling.md#creating-custom-tick-formats). | `display` | `boolean` | | `true` | If true, show tick labels. | `font` | `Font` | Yes | `defaults.font` | See [Fonts](fonts.md) -| `major` | `object` | | `{}` | Major ticks configuration. +| `major` | `object` | | `{}` | [Major ticks configuration](#major-tick-configuration). | `padding` | `number` | | `0` | Sets the offset of the tick labels from the axis | `reverse` | `boolean` | | `false` | Reverses order of tick labels. | `z` | `number` | | `0` | z-index of tick layer. Useful when ticks are drawn on chart area. Values &lt;= 0 are drawn under datasets, &gt; 0 on top. +The scriptable context is the same as for the [Grid Line Configuration](#grid-line-configuration). + ## Major Tick Configuration The majorTick configuration is nested under the ticks configuration in the `major` key. It defines options for the major tick marks that are generated by the axis. | Name | Type | Default | Description | ---- | ---- | ------- | ----------- | `enabled` | `boolean` | `false` | If true, major ticks are generated. A major tick will affect autoskipping and `major` will be defined on ticks in the scriptable options context. +
true
Other
chartjs
Chart.js
2a8962c32559f82bab932b78bb1669f16dffda59.json
Document the context properties for ticks (#7399) Document the context properties for ticks
docs/docs/general/options.md
@@ -20,7 +20,7 @@ color: function(context) { ## Indexable Options -Indexable options also accept an array in which each item corresponds to the element at the same index. Note that this method requires to provide as many items as data, so, in most cases, using a [function](#scriptable-options) is more appropriated if supported. +Indexable options also accept an array in which each item corresponds to the element at the same index. Note that if there are less items than data, the items are looped over. In many cases, using a [function](#scriptable-options) is more appropriate if supported. Example: @@ -46,4 +46,4 @@ The context object contains the following properties: - `datasetIndex`: index of the current dataset - `active`: true if element is active (hovered) -**Important**: since the context can represent different types of entities (dataset, data, etc.), some properties may be `undefined` so be sure to test any context property before using it. +**Important**: since the context can represent different types of entities (dataset, data, ticks, etc.), some properties may be `undefined` so be sure to test any context property before using it.
true
Other
chartjs
Chart.js
2a8962c32559f82bab932b78bb1669f16dffda59.json
Document the context properties for ticks (#7399) Document the context properties for ticks
docs/docs/general/performance.md
@@ -8,11 +8,11 @@ Chart.js charts are rendered on `canvas` elements, which makes rendering quite f ### Rotation -[Specify a rotation value](https://www.chartjs.org/docs/latest/axes/cartesian/#tick-configuration) by setting `minRotation` and `maxRotation` to the same value, which avoids the chart from having to automatically determine a value to use. +[Specify a rotation value](../axes/cartesian/index.md#tick-configuration) by setting `minRotation` and `maxRotation` to the same value, which avoids the chart from having to automatically determine a value to use. ### Sampling -Set the [`ticks.sampleSize`](../axes/cartesian/README.md#tick-configuration) option. This will determine how large your labels are by looking at only a subset of them in order to render axes more quickly. This works best if there is not a large variance in the size of your labels. +Set the [`ticks.sampleSize`](../axes/cartesian/index.md#tick-configuration) option. This will determine how large your labels are by looking at only a subset of them in order to render axes more quickly. This works best if there is not a large variance in the size of your labels. ## Disable Animations
true
Other
chartjs
Chart.js
2a8962c32559f82bab932b78bb1669f16dffda59.json
Document the context properties for ticks (#7399) Document the context properties for ticks
docs/src/css/custom.css
@@ -15,6 +15,10 @@ --ifm-color-primary-lighter: rgb(102, 212, 189); --ifm-color-primary-lightest: rgb(146, 224, 208); --ifm-code-font-size: 95%; + --ifm-code-color: #2472C8; + --ifm-code-background: transparent; + --ifm-code-padding-vertical: 1px; + --ifm-code-padding-horizontal: 3px; } .docusaurus-highlight-code-line {
true
Other
chartjs
Chart.js
09a12f8bffe5da968183e10ddb7c9b0fa5db4e21.json
Remove lineHeight property from ScaleTitle (#7477) `lineHeight` it should not be used anymore because inside the `Font` object
docs/docs/axes/labelling.md
@@ -13,7 +13,6 @@ The scale label configuration is nested under the scale configuration in the `sc | `display` | `boolean` | `false` | If true, display the axis title. | `align` | `string` | `'center'` | Alignment of the axis title. Possible options are `'start'`, `'center'` and `'end'` | `labelString` | `string` | `''` | The text for the title. (i.e. "# of People" or "Response Choices"). -| `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)). | `font` | `Font` | `defaults.font` | See [Fonts](fonts.md) | `padding` | <code>number&#124;object</code> | `4` | Padding to apply around scale labels. Only `top` and `bottom` are implemented.
false
Other
chartjs
Chart.js
614fa07c997ef606a984449ca0756a9197eeaa41.json
Use verbose build in dev mode (#7455) * Use verbose build in dev mode * Update comment
karma.conf.js
@@ -17,11 +17,11 @@ module.exports = function(karma) { const grep = args.grep === true ? '' : args.grep; const specPattern = 'test/specs/**/*' + grep + '*.js'; - // Use the same rollup config as our dist files: when debugging (--watch), + // Use the same rollup config as our dist files: when debugging (npm run dev), // we will prefer the unminified build which is easier to browse and works // better with source mapping. In other cases, pick the minified build to // make sure that the minification process (terser) doesn't break anything. - const regex = args.watch ? /chart\.js$/ : /chart\.min\.js$/; + const regex = karma.autoWatch ? /chart\.js$/ : /chart\.min\.js$/; const build = builds.filter(v => v.output.file.match(regex))[0]; karma.set({
false
Other
chartjs
Chart.js
17e27e16cc52a7df3e87df8251f040d7cd394dab.json
Limit pixel values to 32bit integer range (#7800)
src/core/core.scale.js
@@ -2,7 +2,7 @@ import defaults from './core.defaults'; import Element from './core.element'; import {_alignPixel, _measureText} from '../helpers/helpers.canvas'; import {callback as call, each, isArray, isFinite, isNullOrUndef, isObject, valueOrDefault} from '../helpers/helpers.core'; -import {_factorize, toDegrees, toRadians} from '../helpers/helpers.math'; +import {_factorize, toDegrees, toRadians, _int32Range} from '../helpers/helpers.math'; import {toFont, resolve, toPadding} from '../helpers/helpers.options'; import Ticks from './core.ticks'; @@ -981,7 +981,7 @@ export default class Scale extends Element { decimal = 1 - decimal; } - return me._startPixel + decimal * me._length; + return _int32Range(me._startPixel + decimal * me._length); } /**
true
Other
chartjs
Chart.js
17e27e16cc52a7df3e87df8251f040d7cd394dab.json
Limit pixel values to 32bit integer range (#7800)
src/helpers/helpers.math.js
@@ -172,3 +172,7 @@ export function _angleBetween(angle, start, end) { export function _limitValue(value, min, max) { return Math.max(min, Math.min(max, value)); } + +export function _int32Range(value) { + return _limitValue(value, -2147483648, 2147483647); +}
true
Other
chartjs
Chart.js
2c5db2c35023985ace1505840d3c7302d53b6655.json
Fix some CC issues (#7796) * Fix some CC issues * Merge _lookup, _lookupByKey, _rlookupByKey * Remove TODO from types * Merge TRBL logics * Merge getMaximumWidth and getMaximumHeight
src/elements/element.rectangle.js
@@ -1,5 +1,5 @@ import Element from '../core/core.element'; -import {isObject} from '../helpers/helpers.core'; +import {toTRBL} from '../helpers/helpers.options'; /** * Helper function to get the bounds of the bar regardless of the orientation @@ -71,22 +71,13 @@ function skipOrLimit(skip, value, min, max) { function parseBorderWidth(bar, maxW, maxH) { const value = bar.options.borderWidth; const skip = parseBorderSkipped(bar); - let t, r, b, l; - - if (isObject(value)) { - t = +value.top || 0; - r = +value.right || 0; - b = +value.bottom || 0; - l = +value.left || 0; - } else { - t = r = b = l = +value || 0; - } + const o = toTRBL(value); return { - t: skipOrLimit(skip.top, t, 0, maxH), - r: skipOrLimit(skip.right, r, 0, maxW), - b: skipOrLimit(skip.bottom, b, 0, maxH), - l: skipOrLimit(skip.left, l, 0, maxW) + t: skipOrLimit(skip.top, o.top, 0, maxH), + r: skipOrLimit(skip.right, o.right, 0, maxW), + b: skipOrLimit(skip.bottom, o.bottom, 0, maxH), + l: skipOrLimit(skip.left, o.left, 0, maxW) }; } @@ -115,7 +106,8 @@ function boundingRects(bar) { function inRange(bar, x, y, useFinalPosition) { const skipX = x === null; const skipY = y === null; - const bounds = !bar || (skipX && skipY) ? false : getBarBounds(bar, useFinalPosition); + const skipBoth = skipX && skipY; + const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition); return bounds && (skipX || x >= bounds.left && x <= bounds.right)
true
Other
chartjs
Chart.js
2c5db2c35023985ace1505840d3c7302d53b6655.json
Fix some CC issues (#7796) * Fix some CC issues * Merge _lookup, _lookupByKey, _rlookupByKey * Remove TODO from types * Merge TRBL logics * Merge getMaximumWidth and getMaximumHeight
src/helpers/helpers.collection.js
@@ -4,16 +4,18 @@ import {_capitalize} from './helpers.core'; * Binary search * @param {array} table - the table search. must be sorted! * @param {number} value - value to find + * @param {function} [cmp] * @private */ -export function _lookup(table, value) { +export function _lookup(table, value, cmp) { + cmp = cmp || ((index) => table[index] < value); let hi = table.length - 1; let lo = 0; let mid; while (hi - lo > 1) { mid = (lo + hi) >> 1; - if (table[mid] < value) { + if (cmp(mid)) { lo = mid; } else { hi = mid; @@ -30,22 +32,8 @@ export function _lookup(table, value) { * @param {number} value - value to find * @private */ -export function _lookupByKey(table, key, value) { - let hi = table.length - 1; - let lo = 0; - let mid; - - while (hi - lo > 1) { - mid = (lo + hi) >> 1; - if (table[mid][key] < value) { - lo = mid; - } else { - hi = mid; - } - } - - return {lo, hi}; -} +export const _lookupByKey = (table, key, value) => + _lookup(table, value, index => table[index][key] < value); /** * Reverse binary search @@ -54,22 +42,8 @@ export function _lookupByKey(table, key, value) { * @param {number} value - value to find * @private */ -export function _rlookupByKey(table, key, value) { - let hi = table.length - 1; - let lo = 0; - let mid; - - while (hi - lo > 1) { - mid = (lo + hi) >> 1; - if (table[mid][key] < value) { - hi = mid; - } else { - lo = mid; - } - } - - return {lo, hi}; -} +export const _rlookupByKey = (table, key, value) => + _lookup(table, value, index => table[index][key] >= value); /** * Return subset of `values` between `min` and `max` inclusive.
true
Other
chartjs
Chart.js
2c5db2c35023985ace1505840d3c7302d53b6655.json
Fix some CC issues (#7796) * Fix some CC issues * Merge _lookup, _lookupByKey, _rlookupByKey * Remove TODO from types * Merge TRBL logics * Merge getMaximumWidth and getMaximumHeight
src/helpers/helpers.dom.js
@@ -64,16 +64,6 @@ export function getStyle(el, property) { document.defaultView.getComputedStyle(el, null).getPropertyValue(property); } -/** @return {number=} number or undefined if no constraint */ -function getConstraintWidth(domNode) { - return getConstraintDimension(domNode, 'max-width', 'clientWidth'); -} - -/** @return {number=} number or undefined if no constraint */ -function getConstraintHeight(domNode) { - return getConstraintDimension(domNode, 'max-height', 'clientHeight'); -} - /** * @private */ @@ -133,35 +123,22 @@ function fallbackIfNotValid(measure, fallback) { return typeof measure === 'number' ? measure : fallback; } -export function getMaximumWidth(domNode) { +function getMax(domNode, prop, fallback, paddings) { const container = _getParentNode(domNode); if (!container) { - return fallbackIfNotValid(domNode.clientWidth, domNode.width); + return fallbackIfNotValid(domNode[prop], domNode[fallback]); } - const clientWidth = container.clientWidth; - const paddingLeft = _calculatePadding(container, 'padding-left', clientWidth); - const paddingRight = _calculatePadding(container, 'padding-right', clientWidth); + const value = container[prop]; + const padding = paddings.reduce((acc, cur) => acc + _calculatePadding(container, 'padding-' + cur, value), 0); - const w = clientWidth - paddingLeft - paddingRight; - const cw = getConstraintWidth(domNode); - return isNaN(cw) ? w : Math.min(w, cw); + const v = value - padding; + const cv = getConstraintDimension(domNode, 'max-' + fallback, prop); + return isNaN(cv) ? v : Math.min(v, cv); } -export function getMaximumHeight(domNode) { - const container = _getParentNode(domNode); - if (!container) { - return fallbackIfNotValid(domNode.clientHeight, domNode.height); - } - - const clientHeight = container.clientHeight; - const paddingTop = _calculatePadding(container, 'padding-top', clientHeight); - const paddingBottom = _calculatePadding(container, 'padding-bottom', clientHeight); - - const h = clientHeight - paddingTop - paddingBottom; - const ch = getConstraintHeight(domNode); - return isNaN(ch) ? h : Math.min(h, ch); -} +export const getMaximumWidth = (domNode) => getMax(domNode, 'clientWidth', 'width', ['left', 'right']); +export const getMaximumHeight = (domNode) => getMax(domNode, 'clientHeight', 'height', ['top', 'bottom']); export function retinaScale(chart, forceRatio) { const pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
true
Other
chartjs
Chart.js
2c5db2c35023985ace1505840d3c7302d53b6655.json
Fix some CC issues (#7796) * Fix some CC issues * Merge _lookup, _lookupByKey, _rlookupByKey * Remove TODO from types * Merge TRBL logics * Merge getMaximumWidth and getMaximumHeight
src/helpers/helpers.options.js
@@ -35,35 +35,51 @@ export function toLineHeight(value, size) { return size * value; } +const numberOrZero = v => +v || 0; + /** - * Converts the given value into a padding object with pre-computed width/height. + * Converts the given value into a TRBL object. * @param {number|object} value - If a number, set the value to all TRBL component, * else, if an object, use defined properties and sets undefined ones to 0. - * @returns {object} The padding values (top, right, bottom, left, width, height) - * @since 2.7.0 + * @returns {object} The padding values (top, right, bottom, left) + * @since 3.0.0 */ -export function toPadding(value) { +export function toTRBL(value) { let t, r, b, l; if (isObject(value)) { - t = +value.top || 0; - r = +value.right || 0; - b = +value.bottom || 0; - l = +value.left || 0; + t = numberOrZero(value.top); + r = numberOrZero(value.right); + b = numberOrZero(value.bottom); + l = numberOrZero(value.left); } else { - t = r = b = l = +value || 0; + t = r = b = l = numberOrZero(value); } return { top: t, right: r, bottom: b, - left: l, - height: t + b, - width: l + r + left: l }; } +/** + * Converts the given value into a padding object with pre-computed width/height. + * @param {number|object} value - If a number, set the value to all TRBL component, + * else, if an object, use defined properties and sets undefined ones to 0. + * @returns {object} The padding values (top, right, bottom, left, width, height) + * @since 2.7.0 + */ +export function toPadding(value) { + const obj = toTRBL(value); + + obj.width = obj.left + obj.right; + obj.height = obj.top + obj.bottom; + + return obj; +} + /** * Parses font options and returns the font object. * @param {object} options - A object that contains font options to be parsed.
true
Other
chartjs
Chart.js
2c5db2c35023985ace1505840d3c7302d53b6655.json
Fix some CC issues (#7796) * Fix some CC issues * Merge _lookup, _lookupByKey, _rlookupByKey * Remove TODO from types * Merge TRBL logics * Merge getMaximumWidth and getMaximumHeight
types/elements/index.d.ts
@@ -91,7 +91,7 @@ export interface ILineOptions extends ICommonOptions { cubicInterpolationMode: 'default' | 'monotone'; /** * Bézier curve tension (0 for no Bézier curves). - * @default 0.4 or 0 // TODO + * @default 0 */ tension: number; /**
true
Other
chartjs
Chart.js
9b00ff3e1eed0ef0a4a47fad1b798f810fe5eb2e.json
interfaces.d: fix a wrong place of Option infer (#7770) Co-authored-by: Sergey Khomushin <sergey@placer.io>
types/interfaces.d.ts
@@ -153,10 +153,10 @@ export type IRadarControllerConfiguration<T = number, L = string> = IChartConfig IRadarControllerChartOptions >; -export type ConfigurationOptions<O> = O extends IChartConfiguration<IChartType, unknown, unknown, infer O> ? O : never; -export type ConfigurationData<O> = O extends IChartConfiguration<IChartType, infer T, infer L, infer DS, unknown> +export type ConfigurationOptions<O> = O extends IChartConfiguration<IChartType, infer T, infer L, infer DS, infer O> ? O : never; +export type ConfigurationData<O> = O extends IChartConfiguration<IChartType, infer T, infer L, infer DS, infer O> ? IChartData<T, L, DS> : never; -export type ConfigurationDataset<O> = O extends IChartConfiguration<IChartType, unknown, unknown, infer DS, unknown> +export type ConfigurationDataset<O> = O extends IChartConfiguration<IChartType, infer T, infer L, infer DS, infer O> ? DS : never;
false
Other
chartjs
Chart.js
d5eaa12d96bc059eae7d7768f5b4f4ee45fa42ca.json
Fix: update chart when attached (#7758)
src/core/core.controller.js
@@ -1010,8 +1010,8 @@ class Chart { const attached = () => { _remove('attach', attached); - me.resize(); me.attached = true; + me.resize(); _add('resize', listener); _add('detach', detached);
true
Other
chartjs
Chart.js
d5eaa12d96bc059eae7d7768f5b4f4ee45fa42ca.json
Fix: update chart when attached (#7758)
test/specs/core.controller.tests.js
@@ -637,13 +637,16 @@ describe('Chart', function() { dw: 0, dh: 0, rw: 0, rh: 0, }); + expect(chart.chartArea).toBeUndefined(); waitForResize(chart, function() { expect(chart).toBeChartOfSize({ dw: 455, dh: 355, rw: 455, rh: 355, }); + expect(chart.chartArea).not.toBeUndefined(); + body.removeChild(wrapper); chart.destroy(); done();
true
Other
chartjs
Chart.js
c749fbdf5f8ec08df0261fd8600684ce000a9cf0.json
Fix the parameter order of before/afterEvent (#7757)
src/core/core.plugins.js
@@ -289,17 +289,17 @@ function createDescriptors(plugins, options) { * the event will be discarded. * @param {Chart} chart - The chart instance. * @param {IEvent} event - The event object. - * @param {object} options - The plugin options. * @param {boolean} replay - True if this event is replayed from `Chart.update` + * @param {object} options - The plugin options. */ /** * @method IPlugin#afterEvent * @desc Called after the `event` has been consumed. Note that this hook * will not be called if the `event` has been previously discarded. * @param {Chart} chart - The chart instance. * @param {IEvent} event - The event object. - * @param {object} options - The plugin options. * @param {boolean} replay - True if this event is replayed from `Chart.update` + * @param {object} options - The plugin options. */ /** * @method IPlugin#resize
false
Other
chartjs
Chart.js
4fa2c408f02c723bd7389a705d9aebd42429f8da.json
Remove duplicate code, clearer parameter names (#7756)
src/core/core.controller.js
@@ -177,18 +177,18 @@ function compare2Level(l1, l2) { }; } -function onAnimationsComplete(ctx) { - const chart = ctx.chart; +function onAnimationsComplete(context) { + const chart = context.chart; const animationOptions = chart.options.animation; chart._plugins.notify(chart, 'afterRender'); - callCallback(animationOptions && animationOptions.onComplete, [ctx], chart); + callCallback(animationOptions && animationOptions.onComplete, [context], chart); } -function onAnimationProgress(ctx) { - const chart = ctx.chart; +function onAnimationProgress(context) { + const chart = context.chart; const animationOptions = chart.options.animation; - callCallback(animationOptions && animationOptions.onProgress, [ctx], chart); + callCallback(animationOptions && animationOptions.onProgress, [context], chart); } function isDomSupported() { @@ -701,22 +701,17 @@ class Chart { render() { const me = this; - const animationOptions = me.options.animation; if (me._plugins.notify(me, 'beforeRender') === false) { return; } - const onComplete = function() { - me._plugins.notify(me, 'afterRender'); - callCallback(animationOptions && animationOptions.onComplete, [], me); - }; if (animator.has(me)) { if (me.attached && !animator.running(me)) { animator.start(me); } } else { me.draw(); - onComplete(); + onAnimationsComplete({chart: me}); } }
false
Other
chartjs
Chart.js
4a827db5ffdbbd5df4da982f4fb96248e1a0b800.json
Fix Invalid Typescript Types (#7748)
types/core/index.d.ts
@@ -346,7 +346,7 @@ export class DatasetController<E extends Element = Element, DSE extends Element * Utility for checking if the options are shared and should be animated separately. * @protected */ - protected getSharedOptions(options: any): undefined | { any }; + protected getSharedOptions(options: any): undefined | any; /** * Utility for determining if `options` should be included in the updated properties * @protected @@ -823,7 +823,7 @@ export interface IPlugin<O = {}> { destroy?(chart: Chart, options: O): void; } -declare type IChartComponentLike = IChartComponent | IChartComponent[] | { [key: string]: IChartComponent }; +export declare type IChartComponentLike = IChartComponent | IChartComponent[] | { [key: string]: IChartComponent }; /** * Please use the module's default export which provides a singleton instance
false
Other
chartjs
Chart.js
a32e672fb2a0fc6d2d451a7fcd73cad62da4d584.json
Color the scales of multi-axis scatter sample (#7741)
samples/charts/scatter/multi-axis.html
@@ -101,15 +101,26 @@ y: { type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance display: true, - position: 'left' + position: 'left', + + ticks: { + font: { + color: window.chartColors.red + } + } }, y2: { type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance display: true, position: 'right', reverse: true, - // grid line settings + ticks: { + font: { + color: window.chartColors.blue + } + }, + gridLines: { drawOnChartArea: false, // only want the grid lines for one axis to show up }
false
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
package-lock.json
@@ -6965,6 +6965,12 @@ "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", "dev": true }, + "promise-polyfill": { + "version": "8.1.3", + "resolved": "https://registry.npmjs.org/promise-polyfill/-/promise-polyfill-8.1.3.tgz", + "integrity": "sha512-MG5r82wBzh7pSKDRa9y+vllNHz3e3d4CNj1PQE4BQYxLme0gKYYBm9YENq+UkEikyZ0XbiGWxYlVw3Rl9O/U8g==", + "dev": true + }, "psl": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz",
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
package.json
@@ -74,6 +74,7 @@ "karma-safari-private-launcher": "^1.0.0", "moment": "^2.27.0", "pixelmatch": "^5.2.1", + "promise-polyfill": "^8.1.3", "resize-observer-polyfill": "^1.5.1", "rollup": "^2.25.0", "rollup-plugin-babel": "^4.4.0",
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
rollup.config.js
@@ -40,7 +40,8 @@ module.exports = [ input, plugins: [ inject({ - ResizeObserver: 'resize-observer-polyfill' + ResizeObserver: 'resize-observer-polyfill', + Promise: 'promise-polyfill' }), json(), resolve(), @@ -61,7 +62,8 @@ module.exports = [ input, plugins: [ inject({ - ResizeObserver: 'resize-observer-polyfill' + ResizeObserver: 'resize-observer-polyfill', + Promise: 'promise-polyfill' }), json(), resolve(),
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
src/controllers/controller.bar.js
@@ -219,6 +219,7 @@ export default class BarController extends DatasetController { initialize() { const me = this; + me.enableOptionSharing = true; super.initialize(); @@ -241,14 +242,14 @@ export default class BarController extends DatasetController { const horizontal = vscale.isHorizontal(); const ruler = me._getRuler(); const firstOpts = me.resolveDataElementOptions(start, mode); - const sharedOptions = me.getSharedOptions(mode, rectangles[start], firstOpts); + const sharedOptions = me.getSharedOptions(firstOpts); const includeOptions = me.includeOptions(mode, sharedOptions); - let i; + me.updateSharedOptions(sharedOptions, mode, firstOpts); - for (i = 0; i < rectangles.length; i++) { + for (let i = 0; i < rectangles.length; i++) { const index = start + i; - const options = me.resolveDataElementOptions(index, mode); + const options = sharedOptions || me.resolveDataElementOptions(index, mode); const vpixels = me._calculateBarValuePixels(index, options); const ipixels = me._calculateBarIndexPixels(index, ruler, options); @@ -261,19 +262,11 @@ export default class BarController extends DatasetController { width: horizontal ? undefined : ipixels.size }; - // all borders are drawn for floating bar - /* TODO: float bars border skipping magic - if (me.getParsed(i)._custom) { - model.borderSkipped = null; - } - */ if (includeOptions) { properties.options = options; } me.updateElement(rectangles[i], index, properties, mode); } - - me.updateSharedOptions(sharedOptions, mode); } /**
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
src/controllers/controller.bubble.js
@@ -3,6 +3,10 @@ import {resolve} from '../helpers/helpers.options'; import {resolveObjectKey} from '../helpers/helpers.core'; export default class BubbleController extends DatasetController { + initialize() { + this.enableOptionSharing = true; + super.initialize(); + } /** * Parse array of objects @@ -69,7 +73,7 @@ export default class BubbleController extends DatasetController { const reset = mode === 'reset'; const {xScale, yScale} = me._cachedMeta; const firstOpts = me.resolveDataElementOptions(start, mode); - const sharedOptions = me.getSharedOptions(mode, points[start], firstOpts); + const sharedOptions = me.getSharedOptions(firstOpts); const includeOptions = me.includeOptions(mode, sharedOptions); for (let i = 0; i < points.length; i++) { @@ -95,7 +99,7 @@ export default class BubbleController extends DatasetController { me.updateElement(point, index, properties, mode); } - me.updateSharedOptions(sharedOptions, mode); + me.updateSharedOptions(sharedOptions, mode, firstOpts); } /**
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
src/controllers/controller.doughnut.js
@@ -44,6 +44,7 @@ export default class DoughnutController extends DatasetController { constructor(chart, datasetIndex) { super(chart, datasetIndex); + this.enableOptionSharing = true; this.innerRadius = undefined; this.outerRadius = undefined; this.offsetX = undefined; @@ -129,7 +130,7 @@ export default class DoughnutController extends DatasetController { const innerRadius = animateScale ? 0 : me.innerRadius; const outerRadius = animateScale ? 0 : me.outerRadius; const firstOpts = me.resolveDataElementOptions(start, mode); - const sharedOptions = me.getSharedOptions(mode, arcs[start], firstOpts); + const sharedOptions = me.getSharedOptions(firstOpts); const includeOptions = me.includeOptions(mode, sharedOptions); let startAngle = opts.rotation; let i; @@ -152,13 +153,13 @@ export default class DoughnutController extends DatasetController { innerRadius }; if (includeOptions) { - properties.options = me.resolveDataElementOptions(index, mode); + properties.options = sharedOptions || me.resolveDataElementOptions(index, mode); } startAngle += circumference; me.updateElement(arc, index, properties, mode); } - me.updateSharedOptions(sharedOptions, mode); + me.updateSharedOptions(sharedOptions, mode, firstOpts); } calculateTotal() {
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
src/controllers/controller.line.js
@@ -5,6 +5,11 @@ import {resolve} from '../helpers/helpers.options'; export default class LineController extends DatasetController { + initialize() { + this.enableOptionSharing = true; + super.initialize(); + } + update(mode) { const me = this; const meta = me._cachedMeta; @@ -31,7 +36,7 @@ export default class LineController extends DatasetController { const reset = mode === 'reset'; const {xScale, yScale, _stacked} = me._cachedMeta; const firstOpts = me.resolveDataElementOptions(start, mode); - const sharedOptions = me.getSharedOptions(mode, points[start], firstOpts); + const sharedOptions = me.getSharedOptions(firstOpts); const includeOptions = me.includeOptions(mode, sharedOptions); const spanGaps = valueOrDefault(me._config.spanGaps, me.chart.options.spanGaps); const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY; @@ -51,15 +56,15 @@ export default class LineController extends DatasetController { }; if (includeOptions) { - properties.options = me.resolveDataElementOptions(index, mode); + properties.options = sharedOptions || me.resolveDataElementOptions(index, mode); } me.updateElement(point, index, properties, mode); prevParsed = parsed; } - me.updateSharedOptions(sharedOptions, mode); + me.updateSharedOptions(sharedOptions, mode, firstOpts); } /**
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
src/core/core.animation.js
@@ -36,6 +36,7 @@ export default class Animation { this._prop = prop; this._from = from; this._to = to; + this._promises = undefined; } active() { @@ -62,6 +63,7 @@ export default class Animation { // update current evaluated value, for smoother animations me.tick(Date.now()); me._active = false; + me._notify(false); } } @@ -79,6 +81,7 @@ export default class Animation { if (!me._active) { me._target[prop] = to; + me._notify(true); return; } @@ -93,4 +96,19 @@ export default class Animation { me._target[prop] = me._fn(from, to, factor); } + + wait() { + const promises = this._promises || (this._promises = []); + return new Promise((res, rej) => { + promises.push({res, rej}); + }); + } + + _notify(resolved) { + const method = resolved ? 'res' : 'rej'; + const promises = this._promises || []; + for (let i = 0; i < promises.length; i++) { + promises[i][method](); + } + } }
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
src/core/core.animations.js
@@ -57,10 +57,10 @@ defaults.set('animation', { function copyOptions(target, values) { const oldOpts = target.options; const newOpts = values.options; - if (!oldOpts || !newOpts || newOpts.$shared) { + if (!oldOpts || !newOpts) { return; } - if (oldOpts.$shared) { + if (oldOpts.$shared && !newOpts.$shared) { target.options = Object.assign({}, oldOpts, newOpts, {$shared: false}); } else { Object.assign(oldOpts, newOpts); @@ -115,29 +115,25 @@ export default class Animations { /** * Utility to handle animation of `options`. - * This should not be called, when animating $shared options to $shared new options. * @private - * @todo if new options are $shared, target.options should be replaced with those new shared - * options after all animations have completed */ _animateOptions(target, values) { const newOptions = values.options; - let animations = []; - - if (!newOptions) { - return animations; + const options = resolveTargetOptions(target, newOptions); + if (!options) { + return []; } - let options = target.options; - if (options) { - if (options.$shared) { - // If the current / old options are $shared, meaning other elements are - // using the same options, we need to clone to become unique. - target.options = options = Object.assign({}, options, {$shared: false, $animations: {}}); - } - animations = this._createAnimations(options, newOptions); - } else { - target.options = newOptions; + + const animations = this._createAnimations(options, newOptions); + if (newOptions.$shared && !options.$shared) { + // Going from distinct options to shared options: + // After all animations are done, assing the shared options object to the element + // So any new updates to the shared options are observed + awaitAll(target.$animations, newOptions).then(() => { + target.options = newOptions; + }); } + return animations; } @@ -214,3 +210,32 @@ export default class Animations { } } +function awaitAll(animations, properties) { + const running = []; + const keys = Object.keys(properties); + for (let i = 0; i < keys.length; i++) { + const anim = animations[keys[i]]; + if (anim && anim.active()) { + running.push(anim.wait()); + } + } + // @ts-ignore + return Promise.all(running); +} + +function resolveTargetOptions(target, newOptions) { + if (!newOptions) { + return; + } + let options = target.options; + if (!options) { + target.options = newOptions; + return; + } + if (options.$shared && !newOptions.$shared) { + // Going from shared options to distinct one: + // Create new options object containing the old shared values and start updating that. + target.options = options = Object.assign({}, options, {$shared: false, $animations: {}}); + } + return options; +}
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
src/core/core.animator.js
@@ -1,6 +1,7 @@ import {requestAnimFrame} from '../helpers/helpers.extras'; /** + * @typedef { import("./core.animation").default } Animation * @typedef { import("./core.controller").default } Chart */
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
src/core/core.controller.js
@@ -608,11 +608,9 @@ class Chart { me._updateLayout(); // Can only reset the new controllers after the scales have been updated - if (me.options.animation) { - each(newControllers, (controller) => { - controller.reset(); - }); - } + each(newControllers, (controller) => { + controller.reset(); + }); me._updateDatasets(mode);
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
src/core/core.datasetController.js
@@ -155,6 +155,10 @@ function optionKey(key, active) { return active ? 'hover' + _capitalize(key) : key; } +function isDirectUpdateMode(mode) { + return mode === 'reset' || mode === 'none'; +} + export default class DatasetController { /** @@ -174,6 +178,8 @@ export default class DatasetController { this._parsing = false; this._data = undefined; this._objectData = undefined; + this._sharedOptions = undefined; + this.enableOptionSharing = false; this.initialize(); } @@ -610,7 +616,7 @@ export default class DatasetController { me.configure(); me._cachedAnimations = {}; me._cachedDataOpts = {}; - me.update(mode); + me.update(mode || 'default'); meta._clip = toClip(valueOrDefault(me._config.clip, defaultClip(meta.xScale, meta.yScale, me.getMaxOverflow()))); } @@ -684,6 +690,7 @@ export default class DatasetController { if (active) { me._addAutomaticHoverColors(index, options); } + return options; } @@ -718,9 +725,11 @@ export default class DatasetController { * @protected */ resolveDataElementOptions(index, mode) { + mode = mode || 'default'; const me = this; const active = mode === 'active'; const cached = me._cachedDataOpts; + const sharing = me.enableOptionSharing; if (cached[mode]) { return cached[mode]; } @@ -736,12 +745,12 @@ export default class DatasetController { if (info.cacheable) { // `$shared` indicades this set of options can be shared between multiple elements. // Sharing is used to reduce number of properties to change during animation. - values.$shared = true; + values.$shared = sharing; // We cache options by `mode`, which can be 'active' for example. This enables us // to have the 'active' element options and 'default' options to switch between // when interacting. - cached[mode] = values; + cached[mode] = sharing ? Object.freeze(values) : values; } return values; @@ -809,36 +818,30 @@ export default class DatasetController { } /** - * Utility for checking if the options are shared and should be animated separately. + * Utility for getting the options object shared between elements * @protected */ - getSharedOptions(mode, el, options) { - if (!mode) { - // store element option sharing status for usage in interactions - this._sharedOptions = options && options.$shared; - } - if (mode !== 'reset' && options && options.$shared && el && el.options && el.options.$shared) { - return {target: el.options, options}; + getSharedOptions(options) { + if (!options.$shared) { + return; } + return this._sharedOptions || (this._sharedOptions = Object.assign({}, options)); } /** * Utility for determining if `options` should be included in the updated properties * @protected */ includeOptions(mode, sharedOptions) { - if (mode === 'hide' || mode === 'show') { - return true; - } - return mode !== 'resize' && !sharedOptions; + return !sharedOptions || isDirectUpdateMode(mode); } /** * Utility for updating an element with new properties, using animations when appropriate. * @protected */ updateElement(element, index, properties, mode) { - if (mode === 'reset' || mode === 'none') { + if (isDirectUpdateMode(mode)) { Object.assign(element, properties); } else { this._resolveAnimations(index, mode).update(element, properties); @@ -849,9 +852,9 @@ export default class DatasetController { * Utility to animate the shared options, that are potentially affecting multiple elements. * @protected */ - updateSharedOptions(sharedOptions, mode) { + updateSharedOptions(sharedOptions, mode, newOptions) { if (sharedOptions) { - this._resolveAnimations(undefined, mode).update(sharedOptions.target, sharedOptions.options); + this._resolveAnimations(undefined, mode).update({options: sharedOptions}, {options: newOptions}); } } @@ -860,7 +863,8 @@ export default class DatasetController { */ _setStyle(element, index, mode, active) { element.active = active; - this._resolveAnimations(index, mode, active).update(element, {options: this.getStyle(index, active)}); + const options = this.getStyle(index, active); + this._resolveAnimations(index, mode, active).update(element, {options: this.getSharedOptions(options) || options}); } removeHoverStyle(element, datasetIndex, index) {
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
test/specs/core.animations.tests.js
@@ -43,4 +43,40 @@ describe('Chart.animations', function() { options: undefined })).toBeUndefined(); }); + + it('should assign shared options to target after animations complete', function(done) { + const chart = { + draw: function() {}, + options: { + animation: { + debug: false + } + } + }; + const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}}); + + const target = { + value: 1, + options: { + option: 2 + } + }; + const sharedOpts = {option: 10, $shared: true}; + + expect(anims.update(target, { + options: sharedOpts + })).toBeTrue(); + + expect(target.options !== sharedOpts).toBeTrue(); + + Chart.animator.start(chart); + + setTimeout(function() { + expect(Chart.animator.running(chart)).toBeFalse(); + expect(target.options === sharedOpts).toBeTrue(); + + Chart.animator.remove(chart); + done(); + }, 300); + }); });
true
Other
chartjs
Chart.js
da33b1bb273ac008811521f837ded10891b30a9e.json
Fix shared option handling (#7731) Fix shared option handling
types/core/index.d.ts
@@ -320,6 +320,7 @@ export class DatasetController<E extends Element = Element, DSE extends Element readonly chart: Chart; readonly index: number; readonly _cachedMeta: IChartMeta<E, DSE>; + enableOptionSharing: boolean; linkScales(): void; getAllParsedValues(scale: Scale): number[]; @@ -345,7 +346,7 @@ export class DatasetController<E extends Element = Element, DSE extends Element * Utility for checking if the options are shared and should be animated separately. * @protected */ - protected getSharedOptions(mode: UpdateMode, el: E, options: any): undefined | { target: any; options: any }; + protected getSharedOptions(options: any): undefined | { any }; /** * Utility for determining if `options` should be included in the updated properties * @protected @@ -362,7 +363,7 @@ export class DatasetController<E extends Element = Element, DSE extends Element * @protected */ - protected updateSharedOptions(sharedOptions: any, mode: UpdateMode): void; + protected updateSharedOptions(sharedOptions: any, mode: UpdateMode, newOptions: any): void; removeHoverStyle(element: E, datasetIndex: number, index: number): void; setHoverStyle(element: E, datasetIndex: number, index: number): void;
true
Other
chartjs
Chart.js
f5b4a0fa3c933ac443b66cfa3e0198f4f342a410.json
Improve test coverage and fix minor issues found (#7713) * Registry * Element * Animation * Animations * Animator
src/core/core.animations.js
@@ -105,7 +105,9 @@ export default class Animations { animatedProps.set(prop, Object.assign({}, animDefaults, cfg)); } else if (prop === key) { // Single property targetting config wins over multi-targetting. - animatedProps.set(prop, Object.assign({}, animatedProps.get(prop), cfg)); + // eslint-disable-next-line no-unused-vars + const {properties, ...inherited} = animatedProps.get(prop); + animatedProps.set(prop, Object.assign({}, inherited, cfg)); } }); });
true
Other
chartjs
Chart.js
f5b4a0fa3c933ac443b66cfa3e0198f4f342a410.json
Improve test coverage and fix minor issues found (#7713) * Registry * Element * Animation * Animations * Animator
src/core/core.registry.js
@@ -90,14 +90,42 @@ export class Registry { return this._get(id, this.scales, 'scale'); } + /** + * @param {...typeof DatasetController} args + */ + removeControllers(...args) { + this._each('unregister', args, this.controllers); + } + + /** + * @param {...typeof Element} args + */ + removeElements(...args) { + this._each('unregister', args, this.elements); + } + + /** + * @param {...any} args + */ + removePlugins(...args) { + this._each('unregister', args, this.plugins); + } + + /** + * @param {...typeof Scale} args + */ + removeScales(...args) { + this._each('unregister', args, this.scales); + } + /** * @private */ _each(method, args, typedRegistry) { const me = this; [...args].forEach(arg => { const reg = typedRegistry || me._getRegistryForType(arg); - if (reg.isForType(arg) || (reg === me.plugins && arg.id)) { + if (typedRegistry || reg.isForType(arg) || (reg === me.plugins && arg.id)) { me._exec(method, reg, arg); } else { // Handle loopable args
true
Other
chartjs
Chart.js
f5b4a0fa3c933ac443b66cfa3e0198f4f342a410.json
Improve test coverage and fix minor issues found (#7713) * Registry * Element * Animation * Animations * Animator
src/core/core.typedRegistry.js
@@ -42,6 +42,10 @@ export default class TypedRegistry { return scope; } + if (Object.keys(defaults.get(scope)).length) { + throw new Error('Can not register "' + id + '", because "defaults.' + scope + '" would collide with existing defaults'); + } + items[id] = item; registerDefaults(item, scope, parentScope);
true
Other
chartjs
Chart.js
f5b4a0fa3c933ac443b66cfa3e0198f4f342a410.json
Improve test coverage and fix minor issues found (#7713) * Registry * Element * Animation * Animations * Animator
test/specs/core.animation.tests.js
@@ -0,0 +1,86 @@ +describe('Chart.Animation', function() { + it('should animate boolean', function() { + const target = {prop: false}; + const anim = new Chart.Animation({duration: 1000}, target, 'prop', true); + expect(anim.active()).toBeTrue(); + + anim.tick(anim._start + 500); + expect(anim.active()).toBeTrue(); + expect(target.prop).toBeFalse(); + + anim.tick(anim._start + 501); + expect(anim.active()).toBeTrue(); + expect(target.prop).toBeTrue(); + + anim.tick(anim._start - 100); + expect(anim.active()).toBeTrue(); + expect(target.prop).toBeFalse(); + + anim.tick(anim._start + 1000); + expect(anim.active()).toBeFalse(); + expect(target.prop).toBeTrue(); + }); + + describe('color', function() { + it('should fall back to transparent', function() { + const target = {}; + const anim = new Chart.Animation({duration: 1000, type: 'color'}, target, 'color', 'red'); + anim._from = undefined; + anim.tick(anim._start + 500); + expect(target.color).toEqual('#FF000080'); + + anim._from = 'blue'; + anim._to = undefined; + anim.tick(anim._start + 500); + expect(target.color).toEqual('#0000FF80'); + }); + + it('should not try to mix invalid color', function() { + const target = {color: 'blue'}; + const anim = new Chart.Animation({duration: 1000, type: 'color'}, target, 'color', 'invalid'); + anim.tick(anim._start + 500); + expect(target.color).toEqual('invalid'); + }); + }); + + it('should loop', function() { + const target = {value: 0}; + const anim = new Chart.Animation({duration: 100, loop: true}, target, 'value', 10); + anim.tick(anim._start + 50); + expect(target.value).toEqual(5); + anim.tick(anim._start + 100); + expect(target.value).toEqual(10); + anim.tick(anim._start + 150); + expect(target.value).toEqual(5); + anim.tick(anim._start + 400); + expect(target.value).toEqual(0); + }); + + it('should update', function() { + const target = {testColor: 'transparent'}; + const anim = new Chart.Animation({duration: 100, type: 'color'}, target, 'testColor', 'red'); + + anim.tick(anim._start + 50); + expect(target.testColor).toEqual('#FF000080'); + + anim.update({duration: 500}, 'blue', Date.now()); + anim.tick(anim._start + 250); + expect(target.testColor).toEqual('#4000BFBF'); + + anim.tick(anim._start + 500); + expect(target.testColor).toEqual('blue'); + }); + + it('should not update when finished', function() { + const target = {testColor: 'transparent'}; + const anim = new Chart.Animation({duration: 100, type: 'color'}, target, 'testColor', 'red'); + + anim.tick(anim._start + 100); + expect(target.testColor).toEqual('red'); + expect(anim.active()).toBeFalse(); + + anim.update({duration: 500}, 'blue', Date.now()); + expect(anim._duration).toEqual(100); + expect(anim._to).toEqual('red'); + }); +});
true
Other
chartjs
Chart.js
f5b4a0fa3c933ac443b66cfa3e0198f4f342a410.json
Improve test coverage and fix minor issues found (#7713) * Registry * Element * Animation * Animations * Animator
test/specs/core.animations.tests.js
@@ -0,0 +1,46 @@ +describe('Chart.animations', function() { + it('should override property collection with property', function() { + const chart = {}; + const anims = new Chart.Animations(chart, { + collection1: { + properties: ['property1', 'property2'], + duration: 1000 + }, + property2: { + duration: 2000 + } + }); + expect(anims._properties.get('property1')).toEqual(jasmine.objectContaining({duration: 1000})); + expect(anims._properties.get('property2')).toEqual({duration: 2000}); + }); + + it('should ignore duplicate definitions from collections', function() { + const chart = {}; + const anims = new Chart.Animations(chart, { + collection1: { + properties: ['property1'], + duration: 1000 + }, + collection2: { + properties: ['property1', 'property2'], + duration: 2000 + } + }); + expect(anims._properties.get('property1')).toEqual(jasmine.objectContaining({duration: 1000})); + expect(anims._properties.get('property2')).toEqual(jasmine.objectContaining({duration: 2000})); + }); + + it('should not animate undefined options key', function() { + const chart = {}; + const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}}); + const target = { + value: 1, + options: { + option: 2 + } + }; + expect(anims.update(target, { + options: undefined + })).toBeUndefined(); + }); +});
true
Other
chartjs
Chart.js
f5b4a0fa3c933ac443b66cfa3e0198f4f342a410.json
Improve test coverage and fix minor issues found (#7713) * Registry * Element * Animation * Animations * Animator
test/specs/core.animator.tests.js
@@ -37,4 +37,12 @@ describe('Chart.animator', function() { }, }); }); + + it('should not fail when adding no items', function() { + const chart = {}; + Chart.animator.add(chart, undefined); + Chart.animator.add(chart, []); + Chart.animator.start(chart); + expect(Chart.animator.running(chart)).toBeFalse(); + }); });
true