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 | fe3931b0775a91b1661df8ca708c572d571f4b73.json | Reduce scope of imports (#7000) | src/controllers/controller.line.js | @@ -2,7 +2,8 @@
import DatasetController from '../core/core.datasetController';
import defaults from '../core/core.defaults';
-import elements from '../elements';
+import Line from '../elements/element.line';
+import Point from '../elements/element.point';
import helpers from '../helpers';
const valueOrDefault = helpers.valueOrDefault;
@@ -28,9 +29,9 @@ defaults._set('line', {
export default DatasetController.extend({
- datasetElementType: elements.Line,
+ datasetElementType: Line,
- dataElementType: elements.Point,
+ dataElementType: Point,
/**
* @private | true |
Other | chartjs | Chart.js | fe3931b0775a91b1661df8ca708c572d571f4b73.json | Reduce scope of imports (#7000) | src/controllers/controller.polarArea.js | @@ -2,7 +2,7 @@
import DatasetController from '../core/core.datasetController';
import defaults from '../core/core.defaults';
-import elements from '../elements';
+import Arc from '../elements/element.arc';
import helpers from '../helpers';
const resolve = helpers.options.resolve;
@@ -93,7 +93,7 @@ function getStartAngleRadians(deg) {
export default DatasetController.extend({
- dataElementType: elements.Arc,
+ dataElementType: Arc,
/**
* @private | true |
Other | chartjs | Chart.js | fe3931b0775a91b1661df8ca708c572d571f4b73.json | Reduce scope of imports (#7000) | src/controllers/controller.radar.js | @@ -2,7 +2,8 @@
import DatasetController from '../core/core.datasetController';
import defaults from '../core/core.defaults';
-import elements from '../elements';
+import Line from '../elements/element.line';
+import Point from '../elements/element.point';
import helpers from '../helpers';
const valueOrDefault = helpers.valueOrDefault;
@@ -22,9 +23,9 @@ defaults._set('radar', {
});
export default DatasetController.extend({
- datasetElementType: elements.Line,
+ datasetElementType: Line,
- dataElementType: elements.Point,
+ dataElementType: Point,
/**
* @private | true |
Other | chartjs | Chart.js | fe3931b0775a91b1661df8ca708c572d571f4b73.json | Reduce scope of imports (#7000) | src/core/core.plugins.js | @@ -1,7 +1,7 @@
'use strict';
import defaults from './core.defaults';
-import helpers from '../helpers/';
+import {clone} from '../helpers/helpers.core';
defaults._set('plugins', {});
@@ -142,7 +142,7 @@ export default {
}
if (opts === true) {
- opts = helpers.clone(defaults.plugins[id]);
+ opts = clone(defaults.plugins[id]);
}
plugins.push(plugin); | true |
Other | chartjs | Chart.js | fe3931b0775a91b1661df8ca708c572d571f4b73.json | Reduce scope of imports (#7000) | src/core/core.scaleService.js | @@ -1,7 +1,7 @@
'use strict';
import defaults from './core.defaults';
-import helpers from '../helpers';
+import {clone, each, extend, merge} from '../helpers/helpers.core';
import layouts from './core.layouts';
export default {
@@ -15,24 +15,24 @@ export default {
defaults: {},
registerScaleType: function(type, scaleConstructor, scaleDefaults) {
this.constructors[type] = scaleConstructor;
- this.defaults[type] = helpers.clone(scaleDefaults);
+ this.defaults[type] = clone(scaleDefaults);
},
getScaleConstructor: function(type) {
return Object.prototype.hasOwnProperty.call(this.constructors, type) ? this.constructors[type] : undefined;
},
getScaleDefaults: function(type) {
// Return the scale defaults merged with the global settings so that we always use the latest ones
- return Object.prototype.hasOwnProperty.call(this.defaults, type) ? helpers.merge({}, [defaults.scale, this.defaults[type]]) : {};
+ return Object.prototype.hasOwnProperty.call(this.defaults, type) ? merge({}, [defaults.scale, this.defaults[type]]) : {};
},
updateScaleDefaults: function(type, additions) {
var me = this;
if (Object.prototype.hasOwnProperty.call(me.defaults, type)) {
- me.defaults[type] = helpers.extend(me.defaults[type], additions);
+ me.defaults[type] = extend(me.defaults[type], additions);
}
},
addScalesToLayout: function(chart) {
// Adds each scale to the chart.boxes array to be sized accordingly
- helpers.each(chart.scales, function(scale) {
+ each(chart.scales, function(scale) {
// Set ILayoutItem parameters for backwards compatibility
scale.fullWidth = scale.options.fullWidth;
scale.position = scale.options.position; | true |
Other | chartjs | Chart.js | 7eb0c2ca684b9ee32d2e6a826abf9bb3fc771b96.json | Allow specifying spanGaps as number (max distance) (#6993) | docs/charts/line.md | @@ -77,7 +77,7 @@ The line chart allows a number of properties to be specified for each dataset. T
| [`pointRotation`](#point-styling) | `number` | Yes | Yes | `0`
| [`pointStyle`](#point-styling) | <code>string|Image</code> | Yes | Yes | `'circle'`
| [`showLine`](#line-styling) | `boolean` | - | - | `undefined`
-| [`spanGaps`](#line-styling) | `boolean` | - | - | `undefined`
+| [`spanGaps`](#line-styling) | <code>boolean|number</code> | - | - | `undefined`
| [`steppedLine`](#stepped-line) | <code>boolean|string</code> | - | - | `false`
| [`xAxisID`](#general) | `string` | - | - | first x axis
| [`yAxisID`](#general) | `string` | - | - | first y axis
@@ -124,7 +124,7 @@ The style of the line can be controlled with the following properties:
| `fill` | How to fill the area under the line. See [area charts](area.md).
| `lineTension` | Bezier curve tension of the line. Set to 0 to draw straightlines. This option is ignored if monotone cubic interpolation is used.
| `showLine` | If false, the line is not drawn for this dataset.
-| `spanGaps` | If true, lines will be drawn between points with no or null data. If false, points with `NaN` data will create a break in the line.
+| `spanGaps` | If true, lines will be drawn between points with no or null data. If false, points with `NaN` data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used.
If the value is `undefined`, `showLine` and `spanGaps` fallback to the associated [chart configuration options](#configuration-options). The rest of the values fallback to the associated [`elements.line.*`](../configuration/elements.md#line-configuration) options.
| true |
Other | chartjs | Chart.js | 7eb0c2ca684b9ee32d2e6a826abf9bb3fc771b96.json | Allow specifying spanGaps as number (max distance) (#6993) | samples/samples.js | @@ -121,6 +121,9 @@
}, {
title: 'Line (point data)',
path: 'scales/time/line-point-data.html'
+ }, {
+ title: 'Line (break on 2 day gap)',
+ path: 'scales/time/line-max-span.html'
}, {
title: 'Time Series',
path: 'scales/time/financial.html' | true |
Other | chartjs | Chart.js | 7eb0c2ca684b9ee32d2e6a826abf9bb3fc771b96.json | Allow specifying spanGaps as number (max distance) (#6993) | samples/scales/time/line-max-span.html | @@ -0,0 +1,150 @@
+<!doctype html>
+<html>
+
+<head>
+ <title>Time Scale Point Data</title>
+ <script src="https://cdn.jsdelivr.net/npm/moment@2.24.0/moment.min.js"></script>
+ <script src="../../../dist/Chart.min.js"></script>
+ <script src="../../utils.js"></script>
+ <style>
+ canvas {
+ -moz-user-select: none;
+ -webkit-user-select: none;
+ -ms-user-select: none;
+ }
+ </style>
+</head>
+
+<body>
+ <div style="width:75%;">
+ <canvas id="canvas"></canvas>
+ </div>
+ <br>
+ <br>
+ <button id="randomizeData">Randomize Data</button>
+ <button id="addData">Add Data</button>
+ <button id="removeData">Remove Data</button>
+ <script>
+ function newDate(days) {
+ return moment().add(days, 'd').toDate();
+ }
+
+ function newDateString(days) {
+ return moment().add(days, 'd').format();
+ }
+
+ var color = Chart.helpers.color;
+ var config = {
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset with string point data',
+ backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
+ borderColor: window.chartColors.red,
+ fill: false,
+ data: [{
+ x: newDateString(0),
+ y: randomScalingFactor()
+ }, {
+ x: newDateString(2),
+ y: randomScalingFactor()
+ }, {
+ x: newDateString(4),
+ y: randomScalingFactor()
+ }, {
+ x: newDateString(6),
+ y: randomScalingFactor()
+ }],
+ }, {
+ label: 'Dataset with date object point data',
+ backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
+ borderColor: window.chartColors.blue,
+ fill: false,
+ data: [{
+ x: newDate(0),
+ y: randomScalingFactor()
+ }, {
+ x: newDate(2),
+ y: randomScalingFactor()
+ }, {
+ x: newDate(5),
+ y: randomScalingFactor()
+ }, {
+ x: newDate(6),
+ y: randomScalingFactor()
+ }]
+ }]
+ },
+ options: {
+ spanGaps: 1000 * 60 * 60 * 24 * 2, // 2 days
+ responsive: true,
+ title: {
+ display: true,
+ text: 'Chart.js Time - spanGaps: 172800000 (2 days in ms)'
+ },
+ scales: {
+ x: {
+ type: 'time',
+ display: true,
+ scaleLabel: {
+ display: true,
+ labelString: 'Date'
+ },
+ ticks: {
+ major: {
+ fontStyle: 'bold',
+ fontColor: '#FF0000'
+ }
+ }
+ },
+ y: {
+ display: true,
+ scaleLabel: {
+ display: true,
+ labelString: 'value'
+ }
+ }
+ }
+ }
+ };
+
+ window.onload = function() {
+ var ctx = document.getElementById('canvas').getContext('2d');
+ window.myLine = new Chart(ctx, config);
+ };
+
+ document.getElementById('randomizeData').addEventListener('click', function() {
+ config.data.datasets.forEach(function(dataset) {
+ dataset.data.forEach(function(dataObj) {
+ dataObj.y = randomScalingFactor();
+ });
+ });
+
+ window.myLine.update();
+ });
+ document.getElementById('addData').addEventListener('click', function() {
+ if (config.data.datasets.length > 0) {
+ config.data.datasets[0].data.push({
+ x: newDateString(config.data.datasets[0].data.length + 2),
+ y: randomScalingFactor()
+ });
+ config.data.datasets[1].data.push({
+ x: newDate(config.data.datasets[1].data.length + 2),
+ y: randomScalingFactor()
+ });
+
+ window.myLine.update();
+ }
+ });
+
+ document.getElementById('removeData').addEventListener('click', function() {
+ config.data.datasets.forEach(function(dataset) {
+ dataset.data.pop();
+ });
+
+ window.myLine.update();
+ });
+ </script>
+</body>
+
+</html> | true |
Other | chartjs | Chart.js | 7eb0c2ca684b9ee32d2e6a826abf9bb3fc771b96.json | Allow specifying spanGaps as number (max distance) (#6993) | src/controllers/controller.line.js | @@ -98,6 +98,9 @@ export default DatasetController.extend({
const firstOpts = me._resolveDataElementOptions(start, mode);
const sharedOptions = me._getSharedOptions(mode, points[start], firstOpts);
const includeOptions = me._includeOptions(mode, sharedOptions);
+ const spanGaps = valueOrDefault(me._config.spanGaps, me.chart.options.spanGaps);
+ const maxGapLength = helpers.math.isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
+ let prevParsed;
for (let i = 0; i < points.length; ++i) {
const index = start + i;
@@ -108,14 +111,17 @@ export default DatasetController.extend({
const properties = {
x,
y,
- skip: isNaN(x) || isNaN(y)
+ skip: isNaN(x) || isNaN(y),
+ stop: i > 0 && (parsed.x - prevParsed.x) > maxGapLength
};
if (includeOptions) {
properties.options = me._resolveDataElementOptions(index, mode);
}
me._updateElement(point, index, properties, mode);
+
+ prevParsed = parsed;
}
me._updateSharedOptions(sharedOptions, mode); | true |
Other | chartjs | Chart.js | 7eb0c2ca684b9ee32d2e6a826abf9bb3fc771b96.json | Allow specifying spanGaps as number (max distance) (#6993) | src/helpers/helpers.segment.js | @@ -179,11 +179,11 @@ function solidSegments(points, start, max, loop) {
for (end = start + 1; end <= max; ++end) {
const cur = points[end % count];
- if (cur.skip) {
+ if (cur.skip || cur.stop) {
if (!prev.skip) {
loop = false;
result.push({start: start % count, end: (end - 1) % count, loop});
- start = last = null;
+ start = last = cur.stop ? end : null;
}
} else {
last = end;
@@ -218,7 +218,7 @@ export function _computeSegments(line) {
const loop = !!line._loop;
const {start, end} = findStartAndEnd(points, count, loop, spanGaps);
- if (spanGaps) {
+ if (spanGaps === true) {
return [{start, end, loop}];
}
| true |
Other | chartjs | Chart.js | 9fda5ec667848f12d732a4ca1e89088ac30f2a69.json | Use binary search for interpolations (#6958) | src/core/core.datasetController.js | @@ -980,6 +980,10 @@ helpers.extend(DatasetController.prototype, {
* @private
*/
_getSharedOptions: function(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};
} | true |
Other | chartjs | Chart.js | 9fda5ec667848f12d732a4ca1e89088ac30f2a69.json | Use binary search for interpolations (#6958) | src/core/core.interaction.js | @@ -1,8 +1,8 @@
'use strict';
import helpers from '../helpers/index';
-import {isNumber} from '../helpers/helpers.math';
import {_isPointInArea} from '../helpers/helpers.canvas';
+import {_lookup, _rlookup} from '../helpers/helpers.collection';
/**
* Helper function to get relative position for an event
@@ -42,38 +42,58 @@ function evaluateAllVisibleItems(chart, handler) {
}
/**
- * Helper function to check the items at the hovered index on the index scale
+ * Helper function to do binary search when possible
+ * @param {object} metaset - the dataset meta
+ * @param {string} axis - the axis mide. x|y|xy
+ * @param {number} value - the value to find
+ * @param {boolean} intersect - should the element intersect
+ * @returns {lo, hi} indices to search data array between
+ */
+function binarySearch(metaset, axis, value, intersect) {
+ const {controller, data, _sorted} = metaset;
+ const iScale = controller._cachedMeta.iScale;
+ if (iScale && axis === iScale.axis && _sorted) {
+ const lookupMethod = iScale._reversePixels ? _rlookup : _lookup;
+ if (!intersect) {
+ return lookupMethod(data, axis, value);
+ } else if (controller._sharedOptions) {
+ // _sharedOptions indicates that each element has equal options -> equal proportions
+ // So we can do a ranged binary search based on the range of first element and
+ // be confident to get the full range of indices that can intersect with the value.
+ const el = data[0];
+ const range = typeof el.getRange === 'function' && el.getRange(axis);
+ if (range) {
+ const start = lookupMethod(data, axis, value - range);
+ const end = lookupMethod(data, axis, value + range);
+ return {lo: start.lo, hi: end.hi};
+ }
+ }
+ }
+ // Default to all elements, when binary search can not be used.
+ return {lo: 0, hi: data.length - 1};
+}
+
+/**
+ * Helper function to get items using binary search, when the data is sorted.
* @param {Chart} chart - the chart
* @param {string} axis - the axis mode. x|y|xy
* @param {object} position - the point to be nearest to
* @param {function} handler - the callback to execute for each visible item
- * @return whether all scales were of a suitable type
+ * @param {boolean} intersect - consider intersecting items
*/
-function evaluateItemsAtIndex(chart, axis, position, handler) {
+function optimizedEvaluateItems(chart, axis, position, handler, intersect) {
const metasets = chart._getSortedVisibleDatasetMetas();
- const indices = [];
- for (let i = 0, ilen = metasets.length; i < ilen; ++i) {
- const metaset = metasets[i];
- const iScale = metaset.controller._cachedMeta.iScale;
- if (!iScale || axis !== iScale.axis || !iScale.getIndexForPixel) {
- return false;
- }
- const index = iScale.getIndexForPixel(position[axis]);
- if (!isNumber(index)) {
- return false;
- }
- indices.push(index);
- }
- // do this only after checking whether all scales are of a suitable type
+ const value = position[axis];
for (let i = 0, ilen = metasets.length; i < ilen; ++i) {
- const metaset = metasets[i];
- const index = indices[i];
- const element = metaset.data[index];
- if (!element.skip) {
- handler(element, metaset.index, index);
+ const {index, data} = metasets[i];
+ let {lo, hi} = binarySearch(metasets[i], axis, value, intersect);
+ for (let j = lo; j <= hi; ++j) {
+ const element = data[j];
+ if (!element.skip) {
+ handler(element, index, j);
+ }
}
}
- return true;
}
/**
@@ -112,12 +132,7 @@ function getIntersectItems(chart, position, axis) {
}
};
- const optimized = evaluateItemsAtIndex(chart, axis, position, evaluationFunc);
- if (optimized) {
- return items;
- }
-
- evaluateAllVisibleItems(chart, evaluationFunc);
+ optimizedEvaluateItems(chart, axis, position, evaluationFunc, true);
return items;
}
@@ -154,12 +169,7 @@ function getNearestItems(chart, position, axis, intersect) {
}
};
- const optimized = evaluateItemsAtIndex(chart, axis, position, evaluationFunc);
- if (optimized) {
- return items;
- }
-
- evaluateAllVisibleItems(chart, evaluationFunc);
+ optimizedEvaluateItems(chart, axis, position, evaluationFunc);
return items;
}
| true |
Other | chartjs | Chart.js | 9fda5ec667848f12d732a4ca1e89088ac30f2a69.json | Use binary search for interpolations (#6958) | src/elements/element.point.js | @@ -77,6 +77,11 @@ class Point extends Element {
helpers.canvas.drawPoint(ctx, options, me.x, me.y);
}
}
+
+ getRange() {
+ const options = this.options || {};
+ return options.radius + options.hitRadius;
+ }
}
Point.prototype._type = 'point'; | true |
Other | chartjs | Chart.js | 9fda5ec667848f12d732a4ca1e89088ac30f2a69.json | Use binary search for interpolations (#6958) | src/elements/element.rectangle.js | @@ -181,6 +181,10 @@ class Rectangle extends Element {
y: this.y
};
}
+
+ getRange(axis) {
+ return axis === 'x' ? this.width / 2 : this.height / 2;
+ }
}
Rectangle.prototype._type = 'rectangle'; | true |
Other | chartjs | Chart.js | 9fda5ec667848f12d732a4ca1e89088ac30f2a69.json | Use binary search for interpolations (#6958) | src/helpers/helpers.collection.js | @@ -0,0 +1,49 @@
+'use strict';
+
+/**
+ * Binary search
+ * @param {array} table - the table search. must be sorted!
+ * @param {string} key - property name for the value in each entry
+ * @param {number} value - value to find
+ * @private
+ */
+export function _lookup(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};
+}
+
+/**
+ * Reverse binary search
+ * @param {array} table - the table search. must be sorted!
+ * @param {string} key - property name for the value in each entry
+ * @param {number} value - value to find
+ * @private
+ */
+export function _rlookup(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};
+} | true |
Other | chartjs | Chart.js | 9fda5ec667848f12d732a4ca1e89088ac30f2a69.json | Use binary search for interpolations (#6958) | src/scales/scale.time.js | @@ -5,6 +5,7 @@ import defaults from '../core/core.defaults';
import helpers from '../helpers/index';
import {toRadians} from '../helpers/helpers.math';
import Scale from '../core/core.scale';
+import {_lookup} from '../helpers/helpers.collection';
const resolve = helpers.options.resolve;
const valueOrDefault = helpers.valueOrDefault;
@@ -130,45 +131,18 @@ function buildLookupTable(timestamps, min, max, distribution) {
return table;
}
-// @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
-function lookup(table, key, value) {
- let lo = 0;
- let hi = table.length - 1;
- let mid, i0, i1;
-
- while (lo >= 0 && lo <= hi) {
- mid = (lo + hi) >> 1;
- i0 = mid > 0 && table[mid - 1] || null;
- i1 = table[mid];
-
- if (!i0) {
- // given value is outside table (before first item)
- return {lo: null, hi: i1};
- } else if (i1[key] < value) {
- lo = mid + 1;
- } else if (i0[key] > value) {
- hi = mid - 1;
- } else {
- return {lo: i0, hi: i1};
- }
- }
-
- // given value is outside table (after last item)
- return {lo: i1, hi: null};
-}
-
/**
* 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.
*/
function interpolate(table, skey, sval, tkey) {
- const range = lookup(table, skey, sval);
+ const {lo, hi} = _lookup(table, skey, sval);
// Note: the lookup table ALWAYS contains at least 2 items (min and max)
- const prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
- const next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
+ const prev = table[lo];
+ const next = table[hi];
const span = next[skey] - prev[skey];
const ratio = span ? (sval - prev[skey]) / span : 0;
@@ -716,15 +690,6 @@ class TimeScale extends Scale {
return interpolate(me._table, 'pos', pos, 'time');
}
- getIndexForPixel(pixel) {
- const me = this;
- if (me.options.distribution !== 'series') {
- return null; // not implemented
- }
- const index = Math.round(me._numIndices * me.getDecimalForPixel(pixel));
- return index < 0 || index >= me.numIndices ? null : index;
- }
-
/**
* @private
*/ | true |
Other | chartjs | Chart.js | 14df2c6722ea521a57ceceadb75dade7d100ae34.json | Enable imports for tests (#6997) | karma.conf.js | @@ -59,6 +59,7 @@ module.exports = function(karma) {
].concat((args.inputs || 'test/specs/**/*.js').split(';')),
preprocessors: {
+ 'test/specs/**/*.js': ['rollup'],
'test/index.js': ['rollup'],
'src/index.js': ['sources']
}, | true |
Other | chartjs | Chart.js | 14df2c6722ea521a57ceceadb75dade7d100ae34.json | Enable imports for tests (#6997) | test/specs/helpers.math.tests.js | @@ -1,8 +1,8 @@
'use strict';
+import * as math from '../../src/helpers/helpers.math';
describe('Chart.helpers.math', function() {
- var math = Chart.helpers.math;
var factorize = math._factorize;
var decimalPlaces = math._decimalPlaces;
| true |
Other | chartjs | Chart.js | fd7cf48806a55f79a56f9613db6ab4e87c8241bb.json | Update version in package-lock (#6994) | package-lock.json | @@ -1,6 +1,6 @@
{
"name": "chart.js",
- "version": "2.9.1",
+ "version": "3.0.0-dev",
"lockfileVersion": 1,
"requires": true,
"dependencies": { | false |
Other | chartjs | Chart.js | fb19b77e4bc0e3f097386caf21aed6fa2fd2b03d.json | Fix tooltip for 'dataset' mode (#6961) | src/core/core.controller.js | @@ -888,10 +888,6 @@ class Chart {
if (mode === 'dataset') {
meta = this.getDatasetMeta(items[0].datasetIndex);
meta.controller['_' + prefix + 'DatasetHoverStyle']();
- for (i = 0, ilen = meta.data.length; i < ilen; ++i) {
- meta.controller[prefix + 'HoverStyle'](meta.data[i], items[0].datasetIndex, i);
- }
- return;
}
for (i = 0, ilen = items.length; i < ilen; ++i) { | true |
Other | chartjs | Chart.js | fb19b77e4bc0e3f097386caf21aed6fa2fd2b03d.json | Fix tooltip for 'dataset' mode (#6961) | src/core/core.interaction.js | @@ -228,7 +228,12 @@ export default {
let items = options.intersect ? getIntersectItems(chart, position, axis) : getNearestItems(chart, position, axis);
if (items.length > 0) {
- items = [{datasetIndex: items[0].datasetIndex}]; // when mode: 'dataset' we only need to return datasetIndex
+ const datasetIndex = items[0].datasetIndex;
+ const data = chart.getDatasetMeta(datasetIndex).data;
+ items = [];
+ for (let i = 0; i < data.length; ++i) {
+ items.push({element: data[i], datasetIndex, index: i});
+ }
}
return items; | true |
Other | chartjs | Chart.js | fb19b77e4bc0e3f097386caf21aed6fa2fd2b03d.json | Fix tooltip for 'dataset' mode (#6961) | test/specs/core.interaction.tests.js | @@ -227,8 +227,8 @@ describe('Core.Interaction', function() {
y: point.y
};
- var elements = Chart.Interaction.modes.dataset(chart, evt, {intersect: true});
- expect(elements).toEqual([{datasetIndex: 0}]);
+ var elements = Chart.Interaction.modes.dataset(chart, evt, {intersect: true}).map(item => item.element);
+ expect(elements).toEqual(meta.data);
});
it ('should return an empty array if nothing found', function() {
@@ -283,8 +283,8 @@ describe('Core.Interaction', function() {
y: chart.chartArea.top
};
- var elements = Chart.Interaction.modes.dataset(chart, evt, {axis: 'x', intersect: false});
- expect(elements).toEqual([{datasetIndex: 0}]);
+ var elements = Chart.Interaction.modes.dataset(chart, evt, {axis: 'x', intersect: false}).map(item => item.element);
+ expect(elements).toEqual(chart.getDatasetMeta(0).data);
});
it ('axis: y gets correct items', function() {
@@ -297,8 +297,8 @@ describe('Core.Interaction', function() {
y: chart.chartArea.top
};
- var elements = Chart.Interaction.modes.dataset(chart, evt, {axis: 'y', intersect: false});
- expect(elements).toEqual([{datasetIndex: 1}]);
+ var elements = Chart.Interaction.modes.dataset(chart, evt, {axis: 'y', intersect: false}).map(item => item.element);
+ expect(elements).toEqual(chart.getDatasetMeta(1).data);
});
it ('axis: xy gets correct items', function() {
@@ -311,8 +311,8 @@ describe('Core.Interaction', function() {
y: chart.chartArea.top
};
- var elements = Chart.Interaction.modes.dataset(chart, evt, {intersect: false});
- expect(elements).toEqual([{datasetIndex: 1}]);
+ var elements = Chart.Interaction.modes.dataset(chart, evt, {intersect: false}).map(item => item.element);
+ expect(elements).toEqual(chart.getDatasetMeta(1).data);
});
});
}); | true |
Other | chartjs | Chart.js | 5aaff3a1aa38ad8f807d676d26dbac933c8f2d6e.json | Convert Tooltip to a plugin (#6990)
* Convert Tooltip to a plugin
* code review feedback
* Update docs. Convert positioners map to be on the plugin directly | docs/configuration/tooltip.md | @@ -61,13 +61,14 @@ Example:
```javascript
/**
* Custom positioner
- * @function Chart.Tooltip.positioners.custom
+ * @function Tooltip.positioners.custom
* @param elements {Chart.Element[]} the tooltip elements
* @param eventPosition {Point} the position of the event in canvas coordinates
* @returns {Point} the tooltip position
*/
-Chart.Tooltip.positioners.custom = function(elements, eventPosition) {
- /** @type {Chart.Tooltip} */
+const tooltipPlugin = Chart.plugins.getAll().find(p => p.id === 'tooltip');
+tooltipPlugin.positioners.custom = function(elements, eventPosition) {
+ /** @type {Tooltip} */
var tooltip = this;
/* ... */
@@ -99,7 +100,7 @@ Allows filtering of [tooltip items](#tooltip-item-interface). Must implement at
## Tooltip Callbacks
-The tooltip label configuration is nested below the tooltip configuration using the `callbacks` key. The tooltip has the following callbacks for providing text. For all functions, `this` will be the tooltip object created from the `Chart.Tooltip` constructor.
+The tooltip label configuration is nested below the tooltip configuration using the `callbacks` key. The tooltip has the following callbacks for providing text. For all functions, `this` will be the tooltip object created from the `Tooltip` constructor.
All functions are called with the same arguments: a [tooltip item](#tooltip-item-interface) and the `data` object passed to the chart. All functions must return either a string or an array of strings. Arrays of strings are treated as multiple lines of text.
| true |
Other | chartjs | Chart.js | 5aaff3a1aa38ad8f807d676d26dbac933c8f2d6e.json | Convert Tooltip to a plugin (#6990)
* Convert Tooltip to a plugin
* code review feedback
* Update docs. Convert positioners map to be on the plugin directly | docs/getting-started/v3-migration.md | @@ -79,6 +79,7 @@ Animation system was completely rewritten in Chart.js v3. Each property can now
* `Chart.Controller`
* `Chart.prototype.generateLegend`
* `Chart.types`
+* `Chart.Tooltip` is now provided by the tooltip plugin. The positioners can be accessed from `tooltipPlugin.positioners`
* `DatasetController.addElementAndReset`
* `DatasetController.createMetaData`
* `DatasetController.createMetaDataset` | true |
Other | chartjs | Chart.js | 5aaff3a1aa38ad8f807d676d26dbac933c8f2d6e.json | Convert Tooltip to a plugin (#6990)
* Convert Tooltip to a plugin
* code review feedback
* Update docs. Convert positioners map to be on the plugin directly | src/core/core.controller.js | @@ -9,7 +9,6 @@ import layouts from './core.layouts';
import platform from '../platforms/platform';
import plugins from './core.plugins';
import scaleService from '../core/core.scaleService';
-import Tooltip from './core.tooltip';
const valueOrDefault = helpers.valueOrDefault;
@@ -117,8 +116,6 @@ function updateConfig(chart) {
chart._animationsDisabled = isAnimationDisabled(newOptions);
chart.ensureScalesHaveIDs();
chart.buildOrUpdateScales();
-
- chart.tooltip.initialize();
}
const KNOWN_POSITIONS = new Set(['top', 'bottom', 'left', 'right', 'chartArea']);
@@ -218,8 +215,6 @@ class Chart {
me.resize(true);
}
- me.initToolTip();
-
// After init plugin notification
plugins.notify(me, 'afterInit');
@@ -466,7 +461,7 @@ class Chart {
*/
reset() {
this.resetElements();
- this.tooltip.initialize();
+ plugins.notify(this, 'reset');
}
update(mode) {
@@ -638,8 +633,6 @@ class Chart {
layers[i].draw(me.chartArea);
}
- me._drawTooltip();
-
plugins.notify(me, 'afterDraw');
}
@@ -723,27 +716,6 @@ class Chart {
plugins.notify(me, 'afterDatasetDraw', [args]);
}
- /**
- * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
- * hook, in which case, plugins will not be called on `afterTooltipDraw`.
- * @private
- */
- _drawTooltip() {
- const me = this;
- const tooltip = me.tooltip;
- const args = {
- tooltip: tooltip
- };
-
- if (plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
- return;
- }
-
- tooltip.draw(me.ctx);
-
- plugins.notify(me, 'afterTooltipDraw', [args]);
- }
-
/**
* Get the single element that was clicked on
* @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
@@ -866,10 +838,6 @@ class Chart {
return this.canvas.toDataURL.apply(this.canvas, arguments);
}
- initToolTip() {
- this.tooltip = new Tooltip({_chart: this});
- }
-
/**
* @private
*/
@@ -958,18 +926,13 @@ class Chart {
*/
eventHandler(e) {
const me = this;
- const tooltip = me.tooltip;
if (plugins.notify(me, 'beforeEvent', [e]) === false) {
return;
}
me.handleEvent(e);
- if (tooltip) {
- tooltip.handleEvent(e);
- }
-
plugins.notify(me, 'afterEvent', [e]);
me.render(); | true |
Other | chartjs | Chart.js | 5aaff3a1aa38ad8f807d676d26dbac933c8f2d6e.json | Convert Tooltip to a plugin (#6990)
* Convert Tooltip to a plugin
* code review feedback
* Update docs. Convert positioners map to be on the plugin directly | src/core/core.plugins.js | @@ -200,6 +200,13 @@ export default {
* @param {Chart.Controller} chart - The chart instance.
* @param {object} options - The plugin options.
*/
+/**
+ * @method IPlugin#reset
+ * @desc Called during chart reset
+ * @param {Chart.Controller} chart - The chart instance.
+ * @param {object} options - The plugin options.
+ * @since version 3.0.0
+ */
/**
* @method IPlugin#beforeDatasetsUpdate
* @desc Called before updating the `chart` datasets. If any plugin returns `false`, | true |
Other | chartjs | Chart.js | 5aaff3a1aa38ad8f807d676d26dbac933c8f2d6e.json | Convert Tooltip to a plugin (#6990)
* Convert Tooltip to a plugin
* code review feedback
* Update docs. Convert positioners map to be on the plugin directly | src/index.js | @@ -20,7 +20,6 @@ import pluginsCore from './core/core.plugins';
import Scale from './core/core.scale';
import scaleService from './core/core.scaleService';
import Ticks from './core/core.ticks';
-import Tooltip from './core/core.tooltip';
Chart.helpers = helpers;
Chart._adapters = _adapters;
@@ -39,7 +38,6 @@ Chart.plugins = pluginsCore;
Chart.Scale = Scale;
Chart.scaleService = scaleService;
Chart.Ticks = Ticks;
-Chart.Tooltip = Tooltip;
// Register built-in scales
import scales from './scales'; | true |
Other | chartjs | Chart.js | 5aaff3a1aa38ad8f807d676d26dbac933c8f2d6e.json | Convert Tooltip to a plugin (#6990)
* Convert Tooltip to a plugin
* code review feedback
* Update docs. Convert positioners map to be on the plugin directly | src/plugins/index.js | @@ -3,9 +3,11 @@
import filler from './plugin.filler';
import legend from './plugin.legend';
import title from './plugin.title';
+import tooltip from './plugin.tooltip';
export default {
filler,
legend,
- title
+ title,
+ tooltip
}; | true |
Other | chartjs | Chart.js | 5aaff3a1aa38ad8f807d676d26dbac933c8f2d6e.json | Convert Tooltip to a plugin (#6990)
* Convert Tooltip to a plugin
* code review feedback
* Update docs. Convert positioners map to be on the plugin directly | src/plugins/plugin.tooltip.js | @@ -1,9 +1,10 @@
'use strict';
-import defaults from './core.defaults';
-import Element from './core.element';
+import Animations from '../core/core.animations';
+import defaults from '../core/core.defaults';
+import Element from '../core/core.element';
+import plugins from '../core/core.plugins';
import helpers from '../helpers/index';
-import Animations from './core.animations';
const valueOrDefault = helpers.valueOrDefault;
const getRtlHelper = helpers.rtl.getRtlAdapter;
@@ -1001,4 +1002,49 @@ class Tooltip extends Element {
*/
Tooltip.positioners = positioners;
-export default Tooltip;
+export default {
+ id: 'tooltip',
+ _element: Tooltip,
+ positioners,
+
+ afterInit: function(chart) {
+ const tooltipOpts = chart.options.tooltips;
+
+ if (tooltipOpts) {
+ chart.tooltip = new Tooltip({_chart: chart});
+ }
+ },
+
+ beforeUpdate: function(chart) {
+ if (chart.tooltip) {
+ chart.tooltip.initialize();
+ }
+ },
+
+ reset: function(chart) {
+ if (chart.tooltip) {
+ chart.tooltip.initialize();
+ }
+ },
+
+ afterDraw: function(chart) {
+ const tooltip = chart.tooltip;
+ const args = {
+ tooltip
+ };
+
+ if (plugins.notify(chart, 'beforeTooltipDraw', [args]) === false) {
+ return;
+ }
+
+ tooltip.draw(chart.ctx);
+
+ plugins.notify(chart, 'afterTooltipDraw', [args]);
+ },
+
+ afterEvent: function(chart, e) {
+ if (chart.tooltip) {
+ chart.tooltip.handleEvent(e);
+ }
+ }
+}; | true |
Other | chartjs | Chart.js | 5aaff3a1aa38ad8f807d676d26dbac933c8f2d6e.json | Convert Tooltip to a plugin (#6990)
* Convert Tooltip to a plugin
* code review feedback
* Update docs. Convert positioners map to be on the plugin directly | test/specs/global.namespace.tests.js | @@ -16,8 +16,6 @@ describe('Chart namespace', function() {
expect(Chart.Scale instanceof Object).toBeTruthy();
expect(Chart.scaleService instanceof Object).toBeTruthy();
expect(Chart.Ticks instanceof Object).toBeTruthy();
- expect(Chart.Tooltip instanceof Object).toBeTruthy();
- expect(Chart.Tooltip.positioners instanceof Object).toBeTruthy();
});
});
| true |
Other | chartjs | Chart.js | 5aaff3a1aa38ad8f807d676d26dbac933c8f2d6e.json | Convert Tooltip to a plugin (#6990)
* Convert Tooltip to a plugin
* code review feedback
* Update docs. Convert positioners map to be on the plugin directly | test/specs/plugin.tooltip.tests.js | @@ -1,4 +1,7 @@
// Test the rectangle element
+const tooltipPlugin = Chart.plugins.getAll().find(p => p.id === 'tooltip');
+const Tooltip = tooltipPlugin._element;
+
describe('Core.Tooltip', function() {
describe('auto', jasmine.fixture.specs('core.tooltip'));
@@ -890,11 +893,11 @@ describe('Core.Tooltip', function() {
describe('positioners', function() {
it('Should call custom positioner with correct parameters and scope', function(done) {
- Chart.Tooltip.positioners.test = function() {
+ tooltipPlugin.positioners.test = function() {
return {x: 0, y: 0};
};
- spyOn(Chart.Tooltip.positioners, 'test').and.callThrough();
+ spyOn(tooltipPlugin.positioners, 'test').and.callThrough();
var chart = window.acquireChart({
type: 'line',
@@ -925,14 +928,14 @@ describe('Core.Tooltip', function() {
var datasetIndex = 0;
var meta = chart.getDatasetMeta(datasetIndex);
var point = meta.data[pointIndex];
- var fn = Chart.Tooltip.positioners.test;
+ var fn = tooltipPlugin.positioners.test;
afterEvent(chart, 'mousemove', function() {
expect(fn.calls.count()).toBe(1);
expect(fn.calls.first().args[0] instanceof Array).toBe(true);
expect(Object.prototype.hasOwnProperty.call(fn.calls.first().args[1], 'x')).toBe(true);
expect(Object.prototype.hasOwnProperty.call(fn.calls.first().args[1], 'y')).toBe(true);
- expect(fn.calls.first().object instanceof Chart.Tooltip).toBe(true);
+ expect(fn.calls.first().object instanceof Tooltip).toBe(true);
done();
});
@@ -1261,7 +1264,7 @@ describe('Core.Tooltip', function() {
];
var mockContext = window.createMockContext();
- var tooltip = new Chart.Tooltip({
+ var tooltip = new Tooltip({
_chart: {
options: {
tooltips: { | true |
Other | chartjs | Chart.js | fac507819f7ab4838f1d8b423d803232be93987d.json | Use import statements in test code (#6977) | src/adapters/adapter.moment.js | @@ -2,10 +2,10 @@
'use strict';
-var moment = require('moment');
-var adapters = require('../core/core.adapters');
+import moment from 'moment';
+import adapters from '../core/core.adapters';
-var FORMATS = {
+const FORMATS = {
datetime: 'MMM D, YYYY, h:mm:ss a',
millisecond: 'h:mm:ss.SSS a',
second: 'h:mm:ss a', | true |
Other | chartjs | Chart.js | fac507819f7ab4838f1d8b423d803232be93987d.json | Use import statements in test code (#6977) | src/adapters/index.js | @@ -7,4 +7,4 @@
// Built-in moment adapter that we need to keep for backward compatibility
// https://github.com/chartjs/Chart.js/issues/5542
-require('./adapter.moment');
+import './adapter.moment'; | true |
Other | chartjs | Chart.js | fac507819f7ab4838f1d8b423d803232be93987d.json | Use import statements in test code (#6977) | src/core/core.adapters.js | @@ -6,7 +6,7 @@
'use strict';
-var helpers = require('../helpers/index');
+import helpers from '../helpers';
function abstract() {
throw new Error(
@@ -105,4 +105,6 @@ DateAdapter.override = function(members) {
helpers.extend(DateAdapter.prototype, members);
};
-module.exports._date = DateAdapter;
+export default {
+ _date: DateAdapter
+}; | true |
Other | chartjs | Chart.js | fac507819f7ab4838f1d8b423d803232be93987d.json | Use import statements in test code (#6977) | test/fixture.js | @@ -2,7 +2,7 @@
'use strict';
-var utils = require('./utils');
+import utils from './utils';
function readFile(url, callback) {
var request = new XMLHttpRequest();
@@ -79,7 +79,6 @@ function specsFromFixtures(path) {
};
}
-module.exports = {
+export default {
specs: specsFromFixtures
};
- | true |
Other | chartjs | Chart.js | fac507819f7ab4838f1d8b423d803232be93987d.json | Use import statements in test code (#6977) | test/index.js | @@ -1,9 +1,9 @@
'use strict';
-var fixture = require('./fixture');
-var Context = require('./context');
-var matchers = require('./matchers');
-var utils = require('./utils');
+import fixture from './fixture';
+import Context from './context';
+import matchers from './matchers';
+import utils from './utils';
(function() {
| true |
Other | chartjs | Chart.js | fac507819f7ab4838f1d8b423d803232be93987d.json | Use import statements in test code (#6977) | test/matchers.js | @@ -1,7 +1,7 @@
'use strict';
-var pixelmatch = require('pixelmatch');
-var utils = require('./utils');
+import pixelmatch from 'pixelmatch';
+import utils from './utils';
function toPercent(value) {
return Math.round(value * 10000) / 100;
@@ -196,7 +196,7 @@ function toEqualImageData() {
};
}
-module.exports = {
+export default {
toBeCloseToPixel: toBeCloseToPixel,
toEqualOneOf: toEqualOneOf,
toBeValidChart: toBeValidChart, | true |
Other | chartjs | Chart.js | 2e880ed99d65435837cb71611a8565604e5b6d15.json | Rebuild legend after datasets are updated (#6969) | src/plugins/plugin.legend.js | @@ -688,7 +688,7 @@ export default {
}
},
- beforeUpdate: function(chart) {
+ afterUpdate: function(chart) {
var legendOpts = chart.options.legend;
var legend = chart.legend;
@@ -698,6 +698,7 @@ export default {
if (legend) {
layouts.configure(chart, legend, legendOpts);
legend.options = legendOpts;
+ legend.buildLabels();
} else {
createNewLegendAndAttach(chart, legendOpts);
} | false |
Other | chartjs | Chart.js | 02279b38fcf561224cca02f8eb5fc3131081f48a.json | Fix reference to distanceBetweenPoints (#6962) | src/core/core.tooltip.js | @@ -159,7 +159,7 @@ var positioners = {
var el = elements[i].element;
if (el && el.hasValue()) {
var center = el.getCenterPoint();
- var d = helpers.distanceBetweenPoints(eventPosition, center);
+ var d = helpers.math.distanceBetweenPoints(eventPosition, center);
if (d < minDistance) {
minDistance = d; | false |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | src/platforms/platform.dom.js | @@ -422,9 +422,9 @@ export default {
var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
var proxies = expando.proxies || (expando.proxies = {});
- var proxy = proxies[chart.id + '_' + type] = function(event) {
+ var proxy = proxies[chart.id + '_' + type] = throttled(function(event) {
listener(fromNativeEvent(event, chart));
- };
+ }, chart);
addListener(canvas, type, proxy);
}, | true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/.eslintrc.yml | @@ -7,6 +7,7 @@ env:
globals:
acquireChart: true
+ afterEvent: true
Chart: true
moment: true
waitForResize: true | true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/index.js | @@ -30,6 +30,7 @@ var utils = require('./utils');
window.devicePixelRatio = 1;
window.acquireChart = acquireChart;
+ window.afterEvent = utils.afterEvent;
window.releaseChart = releaseChart;
window.waitForResize = utils.waitForResize;
window.createMockContext = createMockContext; | true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/specs/controller.bubble.tests.js | @@ -288,24 +288,30 @@ describe('Chart.controllers.bubble', function() {
});
});
- it ('should handle default hover styles', function() {
+ it ('should handle default hover styles', function(done) {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
+ afterEvent(chart, 'mousemove', function() {
+ expect(point.options.backgroundColor).toBe('rgb(49, 135, 221)');
+ expect(point.options.borderColor).toBe('rgb(22, 89, 156)');
+ expect(point.options.borderWidth).toBe(1);
+ expect(point.options.radius).toBe(20 + 4);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(point.options.borderWidth).toBe(2);
+ expect(point.options.radius).toBe(20);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', point);
+ });
jasmine.triggerMouseEvent(chart, 'mousemove', point);
- expect(point.options.backgroundColor).toBe('rgb(49, 135, 221)');
- expect(point.options.borderColor).toBe('rgb(22, 89, 156)');
- expect(point.options.borderWidth).toBe(1);
- expect(point.options.radius).toBe(20 + 4);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', point);
- expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(point.options.borderWidth).toBe(2);
- expect(point.options.radius).toBe(20);
});
- it ('should handle hover styles defined via dataset properties', function() {
+ it ('should handle hover styles defined via dataset properties', function(done) {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
@@ -318,20 +324,27 @@ describe('Chart.controllers.bubble', function() {
chart.update();
+ afterEvent(chart, 'mousemove', function() {
+ expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
+ expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
+ expect(point.options.borderWidth).toBe(8.4);
+ expect(point.options.radius).toBe(20 + 4.2);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(point.options.borderWidth).toBe(2);
+ expect(point.options.radius).toBe(20);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', point);
+
+ });
jasmine.triggerMouseEvent(chart, 'mousemove', point);
- expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
- expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
- expect(point.options.borderWidth).toBe(8.4);
- expect(point.options.radius).toBe(20 + 4.2);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', point);
- expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(point.options.borderWidth).toBe(2);
- expect(point.options.radius).toBe(20);
});
- it ('should handle hover styles defined via element options', function() {
+ it ('should handle hover styles defined via element options', function(done) {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
@@ -344,17 +357,23 @@ describe('Chart.controllers.bubble', function() {
chart.update();
+ afterEvent(chart, 'mousemove', function() {
+ expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
+ expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
+ expect(point.options.borderWidth).toBe(8.4);
+ expect(point.options.radius).toBe(20 + 4.2);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(point.options.borderWidth).toBe(2);
+ expect(point.options.radius).toBe(20);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', point);
+ });
jasmine.triggerMouseEvent(chart, 'mousemove', point);
- expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
- expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
- expect(point.options.borderWidth).toBe(8.4);
- expect(point.options.radius).toBe(20 + 4.2);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', point);
- expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(point.options.borderWidth).toBe(2);
- expect(point.options.radius).toBe(20);
});
});
}); | true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/specs/controller.doughnut.tests.js | @@ -347,22 +347,28 @@ describe('Chart.controllers.doughnut', function() {
});
});
- it ('should handle default hover styles', function() {
+ it ('should handle default hover styles', function(done) {
var chart = this.chart;
var arc = chart.getDatasetMeta(0).data[0];
+ afterEvent(chart, 'mousemove', function() {
+ expect(arc.options.backgroundColor).toBe('rgb(49, 135, 221)');
+ expect(arc.options.borderColor).toBe('rgb(22, 89, 156)');
+ expect(arc.options.borderWidth).toBe(2);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(arc.options.borderWidth).toBe(2);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', arc);
+ });
jasmine.triggerMouseEvent(chart, 'mousemove', arc);
- expect(arc.options.backgroundColor).toBe('rgb(49, 135, 221)');
- expect(arc.options.borderColor).toBe('rgb(22, 89, 156)');
- expect(arc.options.borderWidth).toBe(2);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', arc);
- expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(arc.options.borderWidth).toBe(2);
});
- it ('should handle hover styles defined via dataset properties', function() {
+ it ('should handle hover styles defined via dataset properties', function(done) {
var chart = this.chart;
var arc = chart.getDatasetMeta(0).data[0];
@@ -374,18 +380,24 @@ describe('Chart.controllers.doughnut', function() {
chart.update();
+ afterEvent(chart, 'mousemove', function() {
+ expect(arc.options.backgroundColor).toBe('rgb(200, 100, 150)');
+ expect(arc.options.borderColor).toBe('rgb(150, 50, 100)');
+ expect(arc.options.borderWidth).toBe(8.4);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(arc.options.borderWidth).toBe(2);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', arc);
+ });
jasmine.triggerMouseEvent(chart, 'mousemove', arc);
- expect(arc.options.backgroundColor).toBe('rgb(200, 100, 150)');
- expect(arc.options.borderColor).toBe('rgb(150, 50, 100)');
- expect(arc.options.borderWidth).toBe(8.4);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', arc);
- expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(arc.options.borderWidth).toBe(2);
});
- it ('should handle hover styles defined via element options', function() {
+ it ('should handle hover styles defined via element options', function(done) {
var chart = this.chart;
var arc = chart.getDatasetMeta(0).data[0];
@@ -397,15 +409,21 @@ describe('Chart.controllers.doughnut', function() {
chart.update();
+ afterEvent(chart, 'mousemove', function() {
+ expect(arc.options.backgroundColor).toBe('rgb(200, 100, 150)');
+ expect(arc.options.borderColor).toBe('rgb(150, 50, 100)');
+ expect(arc.options.borderWidth).toBe(8.4);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(arc.options.borderWidth).toBe(2);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', arc);
+ });
jasmine.triggerMouseEvent(chart, 'mousemove', arc);
- expect(arc.options.backgroundColor).toBe('rgb(200, 100, 150)');
- expect(arc.options.borderColor).toBe('rgb(150, 50, 100)');
- expect(arc.options.borderWidth).toBe(8.4);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', arc);
- expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(arc.options.borderWidth).toBe(2);
});
});
}); | true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/specs/controller.line.tests.js | @@ -790,24 +790,31 @@ describe('Chart.controllers.line', function() {
});
});
- it ('should handle default hover styles', function() {
+ it ('should handle default hover styles', function(done) {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
- jasmine.triggerMouseEvent(chart, 'mousemove', point);
- expect(point.options.backgroundColor).toBe('rgb(49, 135, 221)');
- expect(point.options.borderColor).toBe('rgb(22, 89, 156)');
- expect(point.options.borderWidth).toBe(1);
- expect(point.options.radius).toBe(4);
+ afterEvent(chart, 'mousemove', function() {
+ expect(point.options.backgroundColor).toBe('rgb(49, 135, 221)');
+ expect(point.options.borderColor).toBe('rgb(22, 89, 156)');
+ expect(point.options.borderWidth).toBe(1);
+ expect(point.options.radius).toBe(4);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(point.options.borderWidth).toBe(2);
+ expect(point.options.radius).toBe(3);
+ done();
+ });
+
+ jasmine.triggerMouseEvent(chart, 'mouseout', point);
+ });
- jasmine.triggerMouseEvent(chart, 'mouseout', point);
- expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(point.options.borderWidth).toBe(2);
- expect(point.options.radius).toBe(3);
+ jasmine.triggerMouseEvent(chart, 'mousemove', point);
});
- it ('should handle hover styles defined via dataset properties', function() {
+ it ('should handle hover styles defined via dataset properties', function(done) {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
@@ -820,20 +827,26 @@ describe('Chart.controllers.line', function() {
chart.update();
- jasmine.triggerMouseEvent(chart, 'mousemove', point);
- expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
- expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
- expect(point.options.borderWidth).toBe(8.4);
- expect(point.options.radius).toBe(4.2);
+ afterEvent(chart, 'mousemove', function() {
+ expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
+ expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
+ expect(point.options.borderWidth).toBe(8.4);
+ expect(point.options.radius).toBe(4.2);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(point.options.borderWidth).toBe(2);
+ expect(point.options.radius).toBe(3);
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', point);
+ });
- jasmine.triggerMouseEvent(chart, 'mouseout', point);
- expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(point.options.borderWidth).toBe(2);
- expect(point.options.radius).toBe(3);
+ jasmine.triggerMouseEvent(chart, 'mousemove', point);
});
- it ('should handle hover styles defined via element options', function() {
+ it ('should handle hover styles defined via element options', function(done) {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
@@ -846,20 +859,28 @@ describe('Chart.controllers.line', function() {
chart.update();
- jasmine.triggerMouseEvent(chart, 'mousemove', point);
- expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
- expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
- expect(point.options.borderWidth).toBe(8.4);
- expect(point.options.radius).toBe(4.2);
+ afterEvent(chart, 'mousemove', function() {
+ expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
+ expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
+ expect(point.options.borderWidth).toBe(8.4);
+ expect(point.options.radius).toBe(4.2);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(point.options.borderWidth).toBe(2);
+ expect(point.options.radius).toBe(3);
+
+ done();
+ });
- jasmine.triggerMouseEvent(chart, 'mouseout', point);
- expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(point.options.borderWidth).toBe(2);
- expect(point.options.radius).toBe(3);
+ jasmine.triggerMouseEvent(chart, 'mouseout', point);
+ });
+
+ jasmine.triggerMouseEvent(chart, 'mousemove', point);
});
- it ('should handle dataset hover styles defined via dataset properties', function() {
+ it ('should handle dataset hover styles defined via dataset properties', function(done) {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
var dataset = chart.getDatasetMeta(0).dataset;
@@ -876,15 +897,23 @@ describe('Chart.controllers.line', function() {
chart.options.hover = {mode: 'dataset'};
chart.update();
+ afterEvent(chart, 'mousemove', function() {
+ expect(dataset.options.backgroundColor).toBe('#000');
+ expect(dataset.options.borderColor).toBe('#111');
+ expect(dataset.options.borderWidth).toBe(12);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(dataset.options.backgroundColor).toBe('#AAA');
+ expect(dataset.options.borderColor).toBe('#BBB');
+ expect(dataset.options.borderWidth).toBe(6);
+
+ done();
+ });
+
+ jasmine.triggerMouseEvent(chart, 'mouseout', point);
+ });
+
jasmine.triggerMouseEvent(chart, 'mousemove', point);
- expect(dataset.options.backgroundColor).toBe('#000');
- expect(dataset.options.borderColor).toBe('#111');
- expect(dataset.options.borderWidth).toBe(12);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', point);
- expect(dataset.options.backgroundColor).toBe('#AAA');
- expect(dataset.options.borderColor).toBe('#BBB');
- expect(dataset.options.borderWidth).toBe(6);
});
});
| true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/specs/controller.polarArea.tests.js | @@ -260,22 +260,28 @@ describe('Chart.controllers.polarArea', function() {
});
});
- it ('should handle default hover styles', function() {
+ it ('should handle default hover styles', function(done) {
var chart = this.chart;
var arc = chart.getDatasetMeta(0).data[0];
+ afterEvent(chart, 'mousemove', function() {
+ expect(arc.options.backgroundColor).toBe('rgb(49, 135, 221)');
+ expect(arc.options.borderColor).toBe('rgb(22, 89, 156)');
+ expect(arc.options.borderWidth).toBe(2);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(arc.options.borderWidth).toBe(2);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', arc);
+ });
jasmine.triggerMouseEvent(chart, 'mousemove', arc);
- expect(arc.options.backgroundColor).toBe('rgb(49, 135, 221)');
- expect(arc.options.borderColor).toBe('rgb(22, 89, 156)');
- expect(arc.options.borderWidth).toBe(2);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', arc);
- expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(arc.options.borderWidth).toBe(2);
});
- it ('should handle hover styles defined via dataset properties', function() {
+ it ('should handle hover styles defined via dataset properties', function(done) {
var chart = this.chart;
var arc = chart.getDatasetMeta(0).data[0];
@@ -287,18 +293,24 @@ describe('Chart.controllers.polarArea', function() {
chart.update();
+ afterEvent(chart, 'mousemove', function() {
+ expect(arc.options.backgroundColor).toBe('rgb(200, 100, 150)');
+ expect(arc.options.borderColor).toBe('rgb(150, 50, 100)');
+ expect(arc.options.borderWidth).toBe(8.4);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(arc.options.borderWidth).toBe(2);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', arc);
+ });
jasmine.triggerMouseEvent(chart, 'mousemove', arc);
- expect(arc.options.backgroundColor).toBe('rgb(200, 100, 150)');
- expect(arc.options.borderColor).toBe('rgb(150, 50, 100)');
- expect(arc.options.borderWidth).toBe(8.4);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', arc);
- expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(arc.options.borderWidth).toBe(2);
});
- it ('should handle hover styles defined via element options', function() {
+ it ('should handle hover styles defined via element options', function(done) {
var chart = this.chart;
var arc = chart.getDatasetMeta(0).data[0];
@@ -310,15 +322,21 @@ describe('Chart.controllers.polarArea', function() {
chart.update();
+ afterEvent(chart, 'mousemove', function() {
+ expect(arc.options.backgroundColor).toBe('rgb(200, 100, 150)');
+ expect(arc.options.borderColor).toBe('rgb(150, 50, 100)');
+ expect(arc.options.borderWidth).toBe(8.4);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(arc.options.borderWidth).toBe(2);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', arc);
+ });
jasmine.triggerMouseEvent(chart, 'mousemove', arc);
- expect(arc.options.backgroundColor).toBe('rgb(200, 100, 150)');
- expect(arc.options.borderColor).toBe('rgb(150, 50, 100)');
- expect(arc.options.borderWidth).toBe(8.4);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', arc);
- expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(arc.options.borderWidth).toBe(2);
});
});
}); | true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/specs/controller.radar.tests.js | @@ -252,24 +252,30 @@ describe('Chart.controllers.radar', function() {
});
});
- it ('should handle default hover styles', function() {
+ it ('should handle default hover styles', function(done) {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
+ afterEvent(chart, 'mousemove', function() {
+ expect(point.options.backgroundColor).toBe('rgb(49, 135, 221)');
+ expect(point.options.borderColor).toBe('rgb(22, 89, 156)');
+ expect(point.options.borderWidth).toBe(1);
+ expect(point.options.radius).toBe(4);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(point.options.borderWidth).toBe(2);
+ expect(point.options.radius).toBe(3);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', point);
+ });
jasmine.triggerMouseEvent(chart, 'mousemove', point);
- expect(point.options.backgroundColor).toBe('rgb(49, 135, 221)');
- expect(point.options.borderColor).toBe('rgb(22, 89, 156)');
- expect(point.options.borderWidth).toBe(1);
- expect(point.options.radius).toBe(4);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', point);
- expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(point.options.borderWidth).toBe(2);
- expect(point.options.radius).toBe(3);
});
- it ('should handle hover styles defined via dataset properties', function() {
+ it ('should handle hover styles defined via dataset properties', function(done) {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
@@ -282,20 +288,26 @@ describe('Chart.controllers.radar', function() {
chart.update();
+ afterEvent(chart, 'mousemove', function() {
+ expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
+ expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
+ expect(point.options.borderWidth).toBe(8.4);
+ expect(point.options.radius).toBe(4.2);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(point.options.borderWidth).toBe(2);
+ expect(point.options.radius).toBe(3);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', point);
+ });
jasmine.triggerMouseEvent(chart, 'mousemove', point);
- expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
- expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
- expect(point.options.borderWidth).toBe(8.4);
- expect(point.options.radius).toBe(4.2);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', point);
- expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(point.options.borderWidth).toBe(2);
- expect(point.options.radius).toBe(3);
});
- it ('should handle hover styles defined via element options', function() {
+ it ('should handle hover styles defined via element options', function(done) {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
@@ -308,17 +320,24 @@ describe('Chart.controllers.radar', function() {
chart.update();
+ afterEvent(chart, 'mousemove', function() {
+ expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
+ expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
+ expect(point.options.borderWidth).toBe(8.4);
+ expect(point.options.radius).toBe(4.2);
+
+ afterEvent(chart, 'mouseout', function() {
+ expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
+ expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
+ expect(point.options.borderWidth).toBe(2);
+ expect(point.options.radius).toBe(3);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mouseout', point);
+
+ });
jasmine.triggerMouseEvent(chart, 'mousemove', point);
- expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
- expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
- expect(point.options.borderWidth).toBe(8.4);
- expect(point.options.radius).toBe(4.2);
-
- jasmine.triggerMouseEvent(chart, 'mouseout', point);
- expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
- expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
- expect(point.options.borderWidth).toBe(2);
- expect(point.options.radius).toBe(3);
});
});
| true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/specs/controller.scatter.tests.js | @@ -3,7 +3,7 @@ describe('Chart.controllers.scatter', function() {
expect(typeof Chart.controllers.scatter).toBe('function');
});
- it('should test default tooltip callbacks', function() {
+ it('should test default tooltip callbacks', function(done) {
var chart = window.acquireChart({
type: 'scatter',
data: {
@@ -18,11 +18,16 @@ describe('Chart.controllers.scatter', function() {
options: {}
});
var point = chart.getDatasetMeta(0).data[0];
- jasmine.triggerMouseEvent(chart, 'mousemove', point);
- // Title should be empty
- expect(chart.tooltip.title.length).toBe(0);
- expect(chart.tooltip.body[0].lines).toEqual(['(10, 15)']);
+ afterEvent(chart, 'mousemove', function() {
+ // Title should be empty
+ expect(chart.tooltip.title.length).toBe(0);
+ expect(chart.tooltip.body[0].lines).toEqual(['(10, 15)']);
+
+ done();
+ });
+
+ jasmine.triggerMouseEvent(chart, 'mousemove', point);
});
describe('showLines option', function() { | true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/specs/core.controller.tests.js | @@ -1104,7 +1104,7 @@ describe('Chart', function() {
expect(chart.tooltip.options).toEqual(jasmine.objectContaining(newTooltipConfig));
});
- it ('should update the tooltip on update', function() {
+ it ('should update the tooltip on update', function(done) {
var chart = acquireChart({
type: 'line',
data: {
@@ -1126,18 +1126,21 @@ describe('Chart', function() {
var meta = chart.getDatasetMeta(0);
var point = meta.data[1];
- jasmine.triggerMouseEvent(chart, 'mousemove', point);
+ afterEvent(chart, 'mousemove', function() {
+ // Check and see if tooltip was displayed
+ var tooltip = chart.tooltip;
- // Check and see if tooltip was displayed
- var tooltip = chart.tooltip;
+ expect(chart.lastActive[0].element).toEqual(point);
+ expect(tooltip._active[0].element).toEqual(point);
- expect(chart.lastActive[0].element).toEqual(point);
- expect(tooltip._active[0].element).toEqual(point);
+ // Update and confirm tooltip is updated
+ chart.update();
+ expect(chart.lastActive[0].element).toEqual(point);
+ expect(tooltip._active[0].element).toEqual(point);
- // Update and confirm tooltip is updated
- chart.update();
- expect(chart.lastActive[0].element).toEqual(point);
- expect(tooltip._active[0].element).toEqual(point);
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mousemove', point);
});
it ('should update the metadata', function() { | true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/specs/core.tooltip.tests.js | @@ -29,7 +29,7 @@ describe('Core.Tooltip', function() {
});
describe('index mode', function() {
- it('Should only use x distance when intersect is false', function() {
+ it('Should only use x distance when intersect is false', function(done) {
var chart = window.acquireChart({
type: 'line',
data: {
@@ -62,20 +62,165 @@ describe('Core.Tooltip', function() {
var meta = chart.getDatasetMeta(0);
var point = meta.data[1];
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
+ afterEvent(chart, 'mousemove', function() {
+ // Check and see if tooltip was displayed
+ var tooltip = chart.tooltip;
+ var defaults = Chart.defaults;
+
+ expect(tooltip.options.xPadding).toEqual(6);
+ expect(tooltip.options.yPadding).toEqual(6);
+ expect(tooltip.xAlign).toEqual('left');
+ expect(tooltip.yAlign).toEqual('center');
+
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Body
+ bodyFontColor: '#fff',
+ bodyFontFamily: defaults.fontFamily,
+ bodyFontStyle: defaults.fontStyle,
+ bodyAlign: 'left',
+ bodyFontSize: defaults.fontSize,
+ bodySpacing: 2,
+ }));
+
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Title
+ titleFontColor: '#fff',
+ titleFontFamily: defaults.fontFamily,
+ titleFontStyle: 'bold',
+ titleFontSize: defaults.fontSize,
+ titleAlign: 'left',
+ titleSpacing: 2,
+ titleMarginBottom: 6,
+ }));
+
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Footer
+ footerFontColor: '#fff',
+ footerFontFamily: defaults.fontFamily,
+ footerFontStyle: 'bold',
+ footerFontSize: defaults.fontSize,
+ footerAlign: 'left',
+ footerSpacing: 2,
+ footerMarginTop: 6,
+ }));
+
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Appearance
+ caretSize: 5,
+ caretPadding: 2,
+ cornerRadius: 6,
+ backgroundColor: 'rgba(0,0,0,0.8)',
+ multiKeyBackground: '#fff',
+ displayColors: true
+ }));
+
+ expect(tooltip).toEqual(jasmine.objectContaining({
+ opacity: 1,
+
+ // Text
+ title: ['Point 2'],
+ beforeBody: [],
+ body: [{
+ before: [],
+ lines: ['Dataset 1: 20'],
+ after: []
+ }, {
+ before: [],
+ lines: ['Dataset 2: 40'],
+ after: []
+ }],
+ afterBody: [],
+ footer: [],
+ labelColors: [{
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }, {
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }]
+ }));
+
+ expect(tooltip.x).toBeCloseToPixel(267);
+ expect(tooltip.y).toBeCloseToPixel(155);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mousemove', {x: point.x, y: chart.chartArea.top});
+ });
+
+ it('Should only display if intersecting if intersect is set', function(done) {
+ var chart = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 20, 30],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ },
+ options: {
+ tooltips: {
+ mode: 'index',
+ intersect: true
+ }
+ }
+ });
+
+ // Trigger an event over top of the
+ var meta = chart.getDatasetMeta(0);
+ var point = meta.data[1];
+
+ afterEvent(chart, 'mousemove', function() {
+ // Check and see if tooltip was displayed
+ var tooltip = chart.tooltip;
+
+ expect(tooltip).toEqual(jasmine.objectContaining({
+ opacity: 0,
+ }));
- var evt = new MouseEvent('mousemove', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: rect.left + point.x,
- clientY: rect.top + chart.chartArea.top + 5 // +5 to make tests work consistently
+ done();
});
+ jasmine.triggerMouseEvent(chart, 'mousemove', {x: point.x, y: 0});
+ });
+ });
+
+ it('Should display in single mode', function(done) {
+ var chart = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 20, 30],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ },
+ options: {
+ tooltips: {
+ mode: 'nearest',
+ intersect: true
+ }
+ }
+ });
- // Manually trigger rather than having an async test
- node.dispatchEvent(evt);
+ // Trigger an event over top of the
+ var meta = chart.getDatasetMeta(0);
+ var point = meta.data[1];
+ afterEvent(chart, 'mousemove', function() {
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
var defaults = Chart.defaults;
@@ -137,197 +282,25 @@ describe('Core.Tooltip', function() {
before: [],
lines: ['Dataset 1: 20'],
after: []
- }, {
- before: [],
- lines: ['Dataset 2: 40'],
- after: []
}],
afterBody: [],
footer: [],
+ labelTextColors: ['#fff'],
labelColors: [{
borderColor: defaults.color,
backgroundColor: defaults.color
- }, {
- borderColor: defaults.color,
- backgroundColor: defaults.color
}]
}));
expect(tooltip.x).toBeCloseToPixel(267);
- expect(tooltip.y).toBeCloseToPixel(155);
- });
-
- it('Should only display if intersecting if intersect is set', function() {
- var chart = window.acquireChart({
- type: 'line',
- data: {
- datasets: [{
- label: 'Dataset 1',
- data: [10, 20, 30],
- pointHoverBorderColor: 'rgb(255, 0, 0)',
- pointHoverBackgroundColor: 'rgb(0, 255, 0)'
- }, {
- label: 'Dataset 2',
- data: [40, 40, 40],
- pointHoverBorderColor: 'rgb(0, 0, 255)',
- pointHoverBackgroundColor: 'rgb(0, 255, 255)'
- }],
- labels: ['Point 1', 'Point 2', 'Point 3']
- },
- options: {
- tooltips: {
- mode: 'index',
- intersect: true
- }
- }
- });
-
- // Trigger an event over top of the
- var meta = chart.getDatasetMeta(0);
- var point = meta.data[1];
-
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
-
- var evt = new MouseEvent('mousemove', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: rect.left + point.x,
- clientY: 0
- });
-
- // Manually trigger rather than having an async test
- node.dispatchEvent(evt);
-
- // Check and see if tooltip was displayed
- var tooltip = chart.tooltip;
-
- expect(tooltip).toEqual(jasmine.objectContaining({
- opacity: 0,
- }));
- });
- });
-
- it('Should display in single mode', function() {
- var chart = window.acquireChart({
- type: 'line',
- data: {
- datasets: [{
- label: 'Dataset 1',
- data: [10, 20, 30],
- pointHoverBorderColor: 'rgb(255, 0, 0)',
- pointHoverBackgroundColor: 'rgb(0, 255, 0)'
- }, {
- label: 'Dataset 2',
- data: [40, 40, 40],
- pointHoverBorderColor: 'rgb(0, 0, 255)',
- pointHoverBackgroundColor: 'rgb(0, 255, 255)'
- }],
- labels: ['Point 1', 'Point 2', 'Point 3']
- },
- options: {
- tooltips: {
- mode: 'nearest',
- intersect: true
- }
- }
- });
-
- // Trigger an event over top of the
- var meta = chart.getDatasetMeta(0);
- var point = meta.data[1];
+ expect(tooltip.y).toBeCloseToPixel(312);
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
-
- var evt = new MouseEvent('mousemove', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: rect.left + point.x,
- clientY: rect.top + point.y
+ done();
});
-
- // Manually trigger rather than having an async test
- node.dispatchEvent(evt);
-
- // Check and see if tooltip was displayed
- var tooltip = chart.tooltip;
- var defaults = Chart.defaults;
-
- expect(tooltip.options.xPadding).toEqual(6);
- expect(tooltip.options.yPadding).toEqual(6);
- expect(tooltip.xAlign).toEqual('left');
- expect(tooltip.yAlign).toEqual('center');
-
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Body
- bodyFontColor: '#fff',
- bodyFontFamily: defaults.fontFamily,
- bodyFontStyle: defaults.fontStyle,
- bodyAlign: 'left',
- bodyFontSize: defaults.fontSize,
- bodySpacing: 2,
- }));
-
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Title
- titleFontColor: '#fff',
- titleFontFamily: defaults.fontFamily,
- titleFontStyle: 'bold',
- titleFontSize: defaults.fontSize,
- titleAlign: 'left',
- titleSpacing: 2,
- titleMarginBottom: 6,
- }));
-
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Footer
- footerFontColor: '#fff',
- footerFontFamily: defaults.fontFamily,
- footerFontStyle: 'bold',
- footerFontSize: defaults.fontSize,
- footerAlign: 'left',
- footerSpacing: 2,
- footerMarginTop: 6,
- }));
-
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Appearance
- caretSize: 5,
- caretPadding: 2,
- cornerRadius: 6,
- backgroundColor: 'rgba(0,0,0,0.8)',
- multiKeyBackground: '#fff',
- displayColors: true
- }));
-
- expect(tooltip).toEqual(jasmine.objectContaining({
- opacity: 1,
-
- // Text
- title: ['Point 2'],
- beforeBody: [],
- body: [{
- before: [],
- lines: ['Dataset 1: 20'],
- after: []
- }],
- afterBody: [],
- footer: [],
- labelTextColors: ['#fff'],
- labelColors: [{
- borderColor: defaults.color,
- backgroundColor: defaults.color
- }]
- }));
-
- expect(tooltip.x).toBeCloseToPixel(267);
- expect(tooltip.y).toBeCloseToPixel(312);
+ jasmine.triggerMouseEvent(chart, 'mousemove', point);
});
- it('Should display information from user callbacks', function() {
+ it('Should display information from user callbacks', function(done) {
var chart = window.acquireChart({
type: 'line',
data: {
@@ -393,102 +366,93 @@ describe('Core.Tooltip', function() {
var meta = chart.getDatasetMeta(0);
var point = meta.data[1];
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
+ afterEvent(chart, 'mousemove', function() {
+ // Check and see if tooltip was displayed
+ var tooltip = chart.tooltip;
+ var defaults = Chart.defaults;
+
+ expect(tooltip.options.xPadding).toEqual(6);
+ expect(tooltip.options.yPadding).toEqual(6);
+ expect(tooltip.xAlign).toEqual('center');
+ expect(tooltip.yAlign).toEqual('top');
- var evt = new MouseEvent('mousemove', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: rect.left + point.x,
- clientY: rect.top + point.y
- });
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Body
+ bodyFontColor: '#fff',
+ bodyFontFamily: defaults.fontFamily,
+ bodyFontStyle: defaults.fontStyle,
+ bodyAlign: 'left',
+ bodyFontSize: defaults.fontSize,
+ bodySpacing: 2,
+ }));
- // Manually trigger rather than having an async test
- node.dispatchEvent(evt);
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Title
+ titleFontColor: '#fff',
+ titleFontFamily: defaults.fontFamily,
+ titleFontStyle: 'bold',
+ titleFontSize: defaults.fontSize,
+ titleAlign: 'left',
+ titleSpacing: 2,
+ titleMarginBottom: 6,
+ }));
- // Check and see if tooltip was displayed
- var tooltip = chart.tooltip;
- var defaults = Chart.defaults;
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Footer
+ footerFontColor: '#fff',
+ footerFontFamily: defaults.fontFamily,
+ footerFontStyle: 'bold',
+ footerFontSize: defaults.fontSize,
+ footerAlign: 'left',
+ footerSpacing: 2,
+ footerMarginTop: 6,
+ }));
+
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Appearance
+ caretSize: 5,
+ caretPadding: 2,
+ cornerRadius: 6,
+ backgroundColor: 'rgba(0,0,0,0.8)',
+ multiKeyBackground: '#fff',
+ }));
+
+ expect(tooltip).toEqual(jasmine.objectContaining({
+ opacity: 1,
+
+ // Text
+ title: ['beforeTitle', 'title', 'afterTitle'],
+ beforeBody: ['beforeBody'],
+ body: [{
+ before: ['beforeLabel'],
+ lines: ['label'],
+ after: ['afterLabel']
+ }, {
+ before: ['beforeLabel'],
+ lines: ['label'],
+ after: ['afterLabel']
+ }],
+ afterBody: ['afterBody'],
+ footer: ['beforeFooter', 'footer', 'afterFooter'],
+ labelTextColors: ['labelTextColor', 'labelTextColor'],
+ labelColors: [{
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }, {
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }]
+ }));
- expect(tooltip.options.xPadding).toEqual(6);
- expect(tooltip.options.yPadding).toEqual(6);
- expect(tooltip.xAlign).toEqual('center');
- expect(tooltip.yAlign).toEqual('top');
-
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Body
- bodyFontColor: '#fff',
- bodyFontFamily: defaults.fontFamily,
- bodyFontStyle: defaults.fontStyle,
- bodyAlign: 'left',
- bodyFontSize: defaults.fontSize,
- bodySpacing: 2,
- }));
-
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Title
- titleFontColor: '#fff',
- titleFontFamily: defaults.fontFamily,
- titleFontStyle: 'bold',
- titleFontSize: defaults.fontSize,
- titleAlign: 'left',
- titleSpacing: 2,
- titleMarginBottom: 6,
- }));
-
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Footer
- footerFontColor: '#fff',
- footerFontFamily: defaults.fontFamily,
- footerFontStyle: 'bold',
- footerFontSize: defaults.fontSize,
- footerAlign: 'left',
- footerSpacing: 2,
- footerMarginTop: 6,
- }));
-
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Appearance
- caretSize: 5,
- caretPadding: 2,
- cornerRadius: 6,
- backgroundColor: 'rgba(0,0,0,0.8)',
- multiKeyBackground: '#fff',
- }));
-
- expect(tooltip).toEqual(jasmine.objectContaining({
- opacity: 1,
-
- // Text
- title: ['beforeTitle', 'title', 'afterTitle'],
- beforeBody: ['beforeBody'],
- body: [{
- before: ['beforeLabel'],
- lines: ['label'],
- after: ['afterLabel']
- }, {
- before: ['beforeLabel'],
- lines: ['label'],
- after: ['afterLabel']
- }],
- afterBody: ['afterBody'],
- footer: ['beforeFooter', 'footer', 'afterFooter'],
- labelTextColors: ['labelTextColor', 'labelTextColor'],
- labelColors: [{
- borderColor: defaults.color,
- backgroundColor: defaults.color
- }, {
- borderColor: defaults.color,
- backgroundColor: defaults.color
- }]
- }));
-
- expect(tooltip.x).toBeCloseToPixel(214);
- expect(tooltip.y).toBeCloseToPixel(190);
+ expect(tooltip.x).toBeCloseToPixel(214);
+ expect(tooltip.y).toBeCloseToPixel(190);
+
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mousemove', point);
});
- it('Should allow sorting items', function() {
+ it('Should allow sorting items', function(done) {
var chart = window.acquireChart({
type: 'line',
data: {
@@ -519,57 +483,49 @@ describe('Core.Tooltip', function() {
var meta0 = chart.getDatasetMeta(0);
var point0 = meta0.data[1];
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
+ afterEvent(chart, 'mousemove', function() {
+ // Check and see if tooltip was displayed
+ var tooltip = chart.tooltip;
+ var defaults = Chart.defaults;
- var evt = new MouseEvent('mousemove', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: rect.left + point0.x,
- clientY: rect.top + point0.y
- });
+ expect(tooltip).toEqual(jasmine.objectContaining({
+ // Positioning
+ xAlign: 'left',
+ yAlign: 'center',
+
+ // Text
+ title: ['Point 2'],
+ beforeBody: [],
+ body: [{
+ before: [],
+ lines: ['Dataset 2: 40'],
+ after: []
+ }, {
+ before: [],
+ lines: ['Dataset 1: 20'],
+ after: []
+ }],
+ afterBody: [],
+ footer: [],
+ labelColors: [{
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }, {
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }]
+ }));
- // Manually trigger rather than having an async test
- node.dispatchEvent(evt);
+ expect(tooltip.x).toBeCloseToPixel(267);
+ expect(tooltip.y).toBeCloseToPixel(155);
- // Check and see if tooltip was displayed
- var tooltip = chart.tooltip;
- var defaults = Chart.defaults;
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mousemove', point0);
- expect(tooltip).toEqual(jasmine.objectContaining({
- // Positioning
- xAlign: 'left',
- yAlign: 'center',
-
- // Text
- title: ['Point 2'],
- beforeBody: [],
- body: [{
- before: [],
- lines: ['Dataset 2: 40'],
- after: []
- }, {
- before: [],
- lines: ['Dataset 1: 20'],
- after: []
- }],
- afterBody: [],
- footer: [],
- labelColors: [{
- borderColor: defaults.color,
- backgroundColor: defaults.color
- }, {
- borderColor: defaults.color,
- backgroundColor: defaults.color
- }]
- }));
-
- expect(tooltip.x).toBeCloseToPixel(267);
- expect(tooltip.y).toBeCloseToPixel(155);
});
- it('Should allow reversing items', function() {
+ it('Should allow reversing items', function(done) {
var chart = window.acquireChart({
type: 'line',
data: {
@@ -598,57 +554,49 @@ describe('Core.Tooltip', function() {
var meta0 = chart.getDatasetMeta(0);
var point0 = meta0.data[1];
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
+ afterEvent(chart, 'mousemove', function() {
+ // Check and see if tooltip was displayed
+ var tooltip = chart.tooltip;
+ var defaults = Chart.defaults;
+
+ expect(tooltip).toEqual(jasmine.objectContaining({
+ // Positioning
+ xAlign: 'left',
+ yAlign: 'center',
- var evt = new MouseEvent('mousemove', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: rect.left + point0.x,
- clientY: rect.top + point0.y
- });
+ // Text
+ title: ['Point 2'],
+ beforeBody: [],
+ body: [{
+ before: [],
+ lines: ['Dataset 2: 40'],
+ after: []
+ }, {
+ before: [],
+ lines: ['Dataset 1: 20'],
+ after: []
+ }],
+ afterBody: [],
+ footer: [],
+ labelColors: [{
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }, {
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }]
+ }));
- // Manually trigger rather than having an async test
- node.dispatchEvent(evt);
+ expect(tooltip.x).toBeCloseToPixel(267);
+ expect(tooltip.y).toBeCloseToPixel(155);
- // Check and see if tooltip was displayed
- var tooltip = chart.tooltip;
- var defaults = Chart.defaults;
+ done();
+ });
- expect(tooltip).toEqual(jasmine.objectContaining({
- // Positioning
- xAlign: 'left',
- yAlign: 'center',
-
- // Text
- title: ['Point 2'],
- beforeBody: [],
- body: [{
- before: [],
- lines: ['Dataset 2: 40'],
- after: []
- }, {
- before: [],
- lines: ['Dataset 1: 20'],
- after: []
- }],
- afterBody: [],
- footer: [],
- labelColors: [{
- borderColor: defaults.color,
- backgroundColor: defaults.color
- }, {
- borderColor: defaults.color,
- backgroundColor: defaults.color
- }]
- }));
-
- expect(tooltip.x).toBeCloseToPixel(267);
- expect(tooltip.y).toBeCloseToPixel(155);
+ jasmine.triggerMouseEvent(chart, 'mousemove', point0);
});
- it('Should follow dataset order', function() {
+ it('Should follow dataset order', function(done) {
var chart = window.acquireChart({
type: 'line',
data: {
@@ -678,57 +626,49 @@ describe('Core.Tooltip', function() {
var meta0 = chart.getDatasetMeta(0);
var point0 = meta0.data[1];
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
+ afterEvent(chart, 'mousemove', function() {
+ // Check and see if tooltip was displayed
+ var tooltip = chart.tooltip;
+ var defaults = Chart.defaults;
- var evt = new MouseEvent('mousemove', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: rect.left + point0.x,
- clientY: rect.top + point0.y
- });
+ expect(tooltip).toEqual(jasmine.objectContaining({
+ // Positioning
+ xAlign: 'left',
+ yAlign: 'center',
+
+ // Text
+ title: ['Point 2'],
+ beforeBody: [],
+ body: [{
+ before: [],
+ lines: ['Dataset 2: 40'],
+ after: []
+ }, {
+ before: [],
+ lines: ['Dataset 1: 20'],
+ after: []
+ }],
+ afterBody: [],
+ footer: [],
+ labelColors: [{
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }, {
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }]
+ }));
- // Manually trigger rather than having an async test
- node.dispatchEvent(evt);
+ expect(tooltip.x).toBeCloseToPixel(267);
+ expect(tooltip.y).toBeCloseToPixel(155);
- // Check and see if tooltip was displayed
- var tooltip = chart.tooltip;
- var defaults = Chart.defaults;
+ done();
+ });
- expect(tooltip).toEqual(jasmine.objectContaining({
- // Positioning
- xAlign: 'left',
- yAlign: 'center',
-
- // Text
- title: ['Point 2'],
- beforeBody: [],
- body: [{
- before: [],
- lines: ['Dataset 2: 40'],
- after: []
- }, {
- before: [],
- lines: ['Dataset 1: 20'],
- after: []
- }],
- afterBody: [],
- footer: [],
- labelColors: [{
- borderColor: defaults.color,
- backgroundColor: defaults.color
- }, {
- borderColor: defaults.color,
- backgroundColor: defaults.color
- }]
- }));
-
- expect(tooltip.x).toBeCloseToPixel(267);
- expect(tooltip.y).toBeCloseToPixel(155);
+ jasmine.triggerMouseEvent(chart, 'mousemove', point0);
});
- it('should filter items from the tooltip using the callback', function() {
+ it('should filter items from the tooltip using the callback', function(done) {
var chart = window.acquireChart({
type: 'line',
data: {
@@ -761,47 +701,39 @@ describe('Core.Tooltip', function() {
var meta0 = chart.getDatasetMeta(0);
var point0 = meta0.data[1];
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
+ afterEvent(chart, 'mousemove', function() {
+ // Check and see if tooltip was displayed
+ var tooltip = chart.tooltip;
+ var defaults = Chart.defaults;
- var evt = new MouseEvent('mousemove', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: rect.left + point0.x,
- clientY: rect.top + point0.y
- });
+ expect(tooltip).toEqual(jasmine.objectContaining({
+ // Positioning
+ xAlign: 'left',
+ yAlign: 'center',
- // Manually trigger rather than having an async test
- node.dispatchEvent(evt);
+ // Text
+ title: ['Point 2'],
+ beforeBody: [],
+ body: [{
+ before: [],
+ lines: ['Dataset 2: 40'],
+ after: []
+ }],
+ afterBody: [],
+ footer: [],
+ labelColors: [{
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }]
+ }));
- // Check and see if tooltip was displayed
- var tooltip = chart.tooltip;
- var defaults = Chart.defaults;
+ done();
+ });
- expect(tooltip).toEqual(jasmine.objectContaining({
- // Positioning
- xAlign: 'left',
- yAlign: 'center',
-
- // Text
- title: ['Point 2'],
- beforeBody: [],
- body: [{
- before: [],
- lines: ['Dataset 2: 40'],
- after: []
- }],
- afterBody: [],
- footer: [],
- labelColors: [{
- borderColor: defaults.color,
- backgroundColor: defaults.color
- }]
- }));
+ jasmine.triggerMouseEvent(chart, 'mousemove', point0);
});
- it('should set the caretPadding based on a config setting', function() {
+ it('should set the caretPadding based on a config setting', function(done) {
var chart = window.acquireChart({
type: 'line',
data: {
@@ -830,31 +762,23 @@ describe('Core.Tooltip', function() {
var meta0 = chart.getDatasetMeta(0);
var point0 = meta0.data[1];
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
-
- var evt = new MouseEvent('mousemove', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: rect.left + point0.x,
- clientY: rect.top + point0.y
- });
+ afterEvent(chart, 'mousemove', function() {
+ // Check and see if tooltip was displayed
+ var tooltip = chart.tooltip;
- // Manually trigger rather than having an async test
- node.dispatchEvent(evt);
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Positioning
+ caretPadding: 10,
+ }));
- // Check and see if tooltip was displayed
- var tooltip = chart.tooltip;
+ done();
+ });
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Positioning
- caretPadding: 10,
- }));
+ jasmine.triggerMouseEvent(chart, 'mousemove', point0);
});
['line', 'bar', 'horizontalBar'].forEach(function(type) {
- it('Should have dataPoints in a ' + type + ' chart', function() {
+ it('Should have dataPoints in a ' + type + ' chart', function(done) {
var chart = window.acquireChart({
type: type,
data: {
@@ -883,27 +807,32 @@ describe('Core.Tooltip', function() {
var pointIndex = 1;
var datasetIndex = 0;
var point = chart.getDatasetMeta(datasetIndex).data[pointIndex];
- jasmine.triggerMouseEvent(chart, 'mousemove', point);
- // Check and see if tooltip was displayed
- var tooltip = chart.tooltip;
+ afterEvent(chart, 'mousemove', function() {
+ // Check and see if tooltip was displayed
+ var tooltip = chart.tooltip;
+
+ expect(tooltip instanceof Object).toBe(true);
+ expect(tooltip.dataPoints instanceof Array).toBe(true);
+ expect(tooltip.dataPoints.length).toBe(1);
- expect(tooltip instanceof Object).toBe(true);
- expect(tooltip.dataPoints instanceof Array).toBe(true);
- expect(tooltip.dataPoints.length).toBe(1);
+ var tooltipItem = tooltip.dataPoints[0];
- var tooltipItem = tooltip.dataPoints[0];
+ expect(tooltipItem.index).toBe(pointIndex);
+ expect(tooltipItem.datasetIndex).toBe(datasetIndex);
+ expect(typeof tooltipItem.label).toBe('string');
+ expect(tooltipItem.label).toBe(chart.data.labels[pointIndex]);
+ expect(typeof tooltipItem.value).toBe('string');
+ expect(tooltipItem.value).toBe('' + chart.data.datasets[datasetIndex].data[pointIndex]);
- expect(tooltipItem.index).toBe(pointIndex);
- expect(tooltipItem.datasetIndex).toBe(datasetIndex);
- expect(typeof tooltipItem.label).toBe('string');
- expect(tooltipItem.label).toBe(chart.data.labels[pointIndex]);
- expect(typeof tooltipItem.value).toBe('string');
- expect(tooltipItem.value).toBe('' + chart.data.datasets[datasetIndex].data[pointIndex]);
+ done();
+ });
+
+ jasmine.triggerMouseEvent(chart, 'mousemove', point);
});
});
- it('Should not update if active element has not changed', function() {
+ it('Should not update if active element has not changed', function(done) {
var chart = window.acquireChart({
type: 'line',
data: {
@@ -937,36 +866,29 @@ describe('Core.Tooltip', function() {
var meta = chart.getDatasetMeta(0);
var firstPoint = meta.data[1];
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
-
- var firstEvent = new MouseEvent('mousemove', {
- view: window,
- bubbles: false,
- cancelable: true,
- clientX: rect.left + firstPoint.x,
- clientY: rect.top + firstPoint.y
- });
-
var tooltip = chart.tooltip;
spyOn(tooltip, 'update');
- /* Manually trigger rather than having an async test */
+ afterEvent(chart, 'mousemove', function() {
+ expect(tooltip.update).toHaveBeenCalledWith(true);
- // First dispatch change event, should update tooltip
- node.dispatchEvent(firstEvent);
- expect(tooltip.update).toHaveBeenCalledWith(true);
+ // Reset calls
+ tooltip.update.calls.reset();
- // Reset calls
- tooltip.update.calls.reset();
+ afterEvent(chart, 'mousemove', function() {
+ expect(tooltip.update).not.toHaveBeenCalled();
- // Second dispatch change event (same event), should not update tooltip
- node.dispatchEvent(firstEvent);
- expect(tooltip.update).not.toHaveBeenCalled();
+ done();
+ });
+ // Second dispatch change event (same event), should not update tooltip
+ jasmine.triggerMouseEvent(chart, 'mousemove', firstPoint);
+ });
+ // First dispatch change event, should update tooltip
+ jasmine.triggerMouseEvent(chart, 'mousemove', firstPoint);
});
describe('positioners', function() {
- it('Should call custom positioner with correct parameters and scope', function() {
+ it('Should call custom positioner with correct parameters and scope', function(done) {
Chart.Tooltip.positioners.test = function() {
return {x: 0, y: 0};
@@ -1003,29 +925,22 @@ describe('Core.Tooltip', function() {
var datasetIndex = 0;
var meta = chart.getDatasetMeta(datasetIndex);
var point = meta.data[pointIndex];
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
- var evt = new MouseEvent('mousemove', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: rect.left + point.x,
- clientY: rect.top + point.y
- });
+ var fn = Chart.Tooltip.positioners.test;
- // Manually trigger rather than having an async test
- node.dispatchEvent(evt);
+ afterEvent(chart, 'mousemove', function() {
+ expect(fn.calls.count()).toBe(1);
+ expect(fn.calls.first().args[0] instanceof Array).toBe(true);
+ expect(Object.prototype.hasOwnProperty.call(fn.calls.first().args[1], 'x')).toBe(true);
+ expect(Object.prototype.hasOwnProperty.call(fn.calls.first().args[1], 'y')).toBe(true);
+ expect(fn.calls.first().object instanceof Chart.Tooltip).toBe(true);
- var fn = Chart.Tooltip.positioners.test;
- expect(fn.calls.count()).toBe(1);
- expect(fn.calls.first().args[0] instanceof Array).toBe(true);
- expect(Object.prototype.hasOwnProperty.call(fn.calls.first().args[1], 'x')).toBe(true);
- expect(Object.prototype.hasOwnProperty.call(fn.calls.first().args[1], 'y')).toBe(true);
- expect(fn.calls.first().object instanceof Chart.Tooltip).toBe(true);
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mousemove', point);
});
});
- it('Should avoid tooltip truncation in x axis if there is enough space to show tooltip without truncation', function() {
+ it('Should avoid tooltip truncation in x axis if there is enough space to show tooltip without truncation', function(done) {
var chart = window.acquireChart({
type: 'pie',
data: {
@@ -1057,46 +972,47 @@ describe('Core.Tooltip', function() {
}
});
- // Trigger an event over top of the slice
- for (var slice = 0; slice < 2; slice++) {
+ function testSlice(slice, count) {
var meta = chart.getDatasetMeta(0);
var point = meta.data[slice].getCenterPoint();
var tooltipPosition = meta.data[slice].tooltipPosition();
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
-
- var mouseMoveEvent = new MouseEvent('mousemove', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: rect.left + point.x,
- clientY: rect.top + point.y
- });
- var mouseOutEvent = new MouseEvent('mouseout');
- // Lets cycle while tooltip is narrower than chart area
- var infiniteCycleDefense = 70;
- for (var i = 0; i < infiniteCycleDefense; i++) {
+ function recursive(left) {
chart.config.data.labels[slice] = chart.config.data.labels[slice] + 'l';
chart.update();
- node.dispatchEvent(mouseOutEvent);
- node.dispatchEvent(mouseMoveEvent);
- var tooltip = chart.tooltip;
- expect(tooltip.dataPoints.length).toBe(1);
- expect(tooltip.x).toBeGreaterThanOrEqual(0);
- if (tooltip.width <= chart.width) {
- expect(tooltip.x + tooltip.width).toBeLessThanOrEqual(chart.width);
- }
- expect(tooltip.caretX).toBeCloseToPixel(tooltipPosition.x);
- // if tooltip is longer than chart area then all tests done
- if (tooltip.width > chart.width) {
- break;
- }
+
+ afterEvent(chart, 'mouseout', function() {
+ afterEvent(chart, 'mousemove', function() {
+ var tooltip = chart.tooltip;
+ expect(tooltip.dataPoints.length).toBe(1);
+ expect(tooltip.x).toBeGreaterThanOrEqual(0);
+ if (tooltip.width <= chart.width) {
+ expect(tooltip.x + tooltip.width).toBeLessThanOrEqual(chart.width);
+ }
+ expect(tooltip.caretX).toBeCloseToPixel(tooltipPosition.x);
+ // if tooltip is longer than chart area then all tests done
+ if (tooltip.width > chart.width || left === 0) {
+ done(left === 0 && new Error('max iterations reached'));
+ } else {
+ recursive(left - 1);
+ }
+ });
+ jasmine.triggerMouseEvent(chart, 'mousemove', point);
+ });
+
+ jasmine.triggerMouseEvent(chart, 'mouseout', point);
}
+
+ recursive(count);
+ }
+
+ // Trigger an event over top of the slice
+ for (var slice = 0; slice < 2; slice++) {
+ testSlice(slice, 70);
}
});
- it('Should split newlines into separate lines in user callbacks', function() {
+ it('Should split newlines into separate lines in user callbacks', function(done) {
var chart = window.acquireChart({
type: 'line',
data: {
@@ -1161,95 +1077,89 @@ describe('Core.Tooltip', function() {
// Trigger an event over top of the
var meta = chart.getDatasetMeta(0);
var point = meta.data[1];
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
- var evt = new MouseEvent('mousemove', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: rect.left + point.x,
- clientY: rect.top + point.y
- });
- // Manually trigger rather than having an async test
- node.dispatchEvent(evt);
+ afterEvent(chart, 'mousemove', function() {
+ // Check and see if tooltip was displayed
+ var tooltip = chart.tooltip;
+ var defaults = Chart.defaults;
- // Check and see if tooltip was displayed
- var tooltip = chart.tooltip;
- var defaults = Chart.defaults;
+ expect(tooltip.options.xPadding).toEqual(6);
+ expect(tooltip.options.yPadding).toEqual(6);
+ expect(tooltip.xAlign).toEqual('center');
+ expect(tooltip.yAlign).toEqual('top');
+
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Body
+ bodyFontColor: '#fff',
+ bodyFontFamily: defaults.fontFamily,
+ bodyFontStyle: defaults.fontStyle,
+ bodyAlign: 'left',
+ bodyFontSize: defaults.fontSize,
+ bodySpacing: 2,
+ }));
+
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Title
+ titleFontColor: '#fff',
+ titleFontFamily: defaults.fontFamily,
+ titleFontStyle: 'bold',
+ titleFontSize: defaults.fontSize,
+ titleAlign: 'left',
+ titleSpacing: 2,
+ titleMarginBottom: 6,
+ }));
+
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Footer
+ footerFontColor: '#fff',
+ footerFontFamily: defaults.fontFamily,
+ footerFontStyle: 'bold',
+ footerFontSize: defaults.fontSize,
+ footerAlign: 'left',
+ footerSpacing: 2,
+ footerMarginTop: 6,
+ }));
+
+ expect(tooltip.options).toEqual(jasmine.objectContaining({
+ // Appearance
+ caretSize: 5,
+ caretPadding: 2,
+ cornerRadius: 6,
+ backgroundColor: 'rgba(0,0,0,0.8)',
+ multiKeyBackground: '#fff',
+ }));
+
+ expect(tooltip).toEqual(jasmine.objectContaining({
+ opacity: 1,
+
+ // Text
+ title: ['beforeTitle', 'newline', 'title', 'newline', 'afterTitle', 'newline'],
+ beforeBody: ['beforeBody', 'newline'],
+ body: [{
+ before: ['beforeLabel', 'newline'],
+ lines: ['label'],
+ after: ['afterLabel', 'newline']
+ }, {
+ before: ['beforeLabel', 'newline'],
+ lines: ['label'],
+ after: ['afterLabel', 'newline']
+ }],
+ afterBody: ['afterBody', 'newline'],
+ footer: ['beforeFooter', 'newline', 'footer', 'newline', 'afterFooter', 'newline'],
+ labelTextColors: ['labelTextColor', 'labelTextColor'],
+ labelColors: [{
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }, {
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
+ }]
+ }));
+
+ done();
+ });
- expect(tooltip.options.xPadding).toEqual(6);
- expect(tooltip.options.yPadding).toEqual(6);
- expect(tooltip.xAlign).toEqual('center');
- expect(tooltip.yAlign).toEqual('top');
-
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Body
- bodyFontColor: '#fff',
- bodyFontFamily: defaults.fontFamily,
- bodyFontStyle: defaults.fontStyle,
- bodyAlign: 'left',
- bodyFontSize: defaults.fontSize,
- bodySpacing: 2,
- }));
-
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Title
- titleFontColor: '#fff',
- titleFontFamily: defaults.fontFamily,
- titleFontStyle: 'bold',
- titleFontSize: defaults.fontSize,
- titleAlign: 'left',
- titleSpacing: 2,
- titleMarginBottom: 6,
- }));
-
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Footer
- footerFontColor: '#fff',
- footerFontFamily: defaults.fontFamily,
- footerFontStyle: 'bold',
- footerFontSize: defaults.fontSize,
- footerAlign: 'left',
- footerSpacing: 2,
- footerMarginTop: 6,
- }));
-
- expect(tooltip.options).toEqual(jasmine.objectContaining({
- // Appearance
- caretSize: 5,
- caretPadding: 2,
- cornerRadius: 6,
- backgroundColor: 'rgba(0,0,0,0.8)',
- multiKeyBackground: '#fff',
- }));
-
- expect(tooltip).toEqual(jasmine.objectContaining({
- opacity: 1,
-
- // Text
- title: ['beforeTitle', 'newline', 'title', 'newline', 'afterTitle', 'newline'],
- beforeBody: ['beforeBody', 'newline'],
- body: [{
- before: ['beforeLabel', 'newline'],
- lines: ['label'],
- after: ['afterLabel', 'newline']
- }, {
- before: ['beforeLabel', 'newline'],
- lines: ['label'],
- after: ['afterLabel', 'newline']
- }],
- afterBody: ['afterBody', 'newline'],
- footer: ['beforeFooter', 'newline', 'footer', 'newline', 'afterFooter', 'newline'],
- labelTextColors: ['labelTextColor', 'labelTextColor'],
- labelColors: [{
- borderColor: defaults.color,
- backgroundColor: defaults.color
- }, {
- borderColor: defaults.color,
- backgroundColor: defaults.color
- }]
- }));
+ jasmine.triggerMouseEvent(chart, 'mousemove', point);
});
describe('text align', function() { | true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/specs/platform.dom.tests.js | @@ -356,7 +356,7 @@ describe('Platform.dom', function() {
});
describe('event handling', function() {
- it('should notify plugins about events', function() {
+ it('should notify plugins about events', function(done) {
var notifiedEvent;
var plugin = {
afterEvent: function(chart, e) {
@@ -377,32 +377,24 @@ describe('Platform.dom', function() {
plugins: [plugin]
});
- var node = chart.canvas;
- var rect = node.getBoundingClientRect();
- var clientX = (rect.left + rect.right) / 2;
- var clientY = (rect.top + rect.bottom) / 2;
-
- var evt = new MouseEvent('click', {
- view: window,
- bubbles: true,
- cancelable: true,
- clientX: clientX,
- clientY: clientY
- });
+ afterEvent(chart, 'click', function() {
+ // Check that notifiedEvent is correct
+ expect(notifiedEvent).not.toBe(undefined);
- // Manually trigger rather than having an async test
- node.dispatchEvent(evt);
+ // Is type correctly translated
+ expect(notifiedEvent.type).toBe('click');
- // Check that notifiedEvent is correct
- expect(notifiedEvent).not.toBe(undefined);
- expect(notifiedEvent.native).toBe(evt);
+ // Relative Position
+ expect(notifiedEvent.x).toBeCloseToPixel(chart.width / 2);
+ expect(notifiedEvent.y).toBeCloseToPixel(chart.height / 2);
- // Is type correctly translated
- expect(notifiedEvent.type).toBe(evt.type);
+ done();
+ });
- // Relative Position
- expect(notifiedEvent.x).toBeCloseToPixel(chart.width / 2);
- expect(notifiedEvent.y).toBeCloseToPixel(chart.height / 2);
+ jasmine.triggerMouseEvent(chart, 'click', {
+ x: chart.width / 2,
+ y: chart.height / 2
+ });
});
});
}); | true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/specs/plugin.legend.tests.js | @@ -602,7 +602,7 @@ describe('Legend block tests', function() {
});
describe('callbacks', function() {
- it('should call onClick, onHover and onLeave at the correct times', function() {
+ it('should call onClick, onHover and onLeave at the correct times', function(done) {
var clickItem = null;
var hoverItem = null;
var leaveItem = null;
@@ -636,17 +636,22 @@ describe('Legend block tests', function() {
y: hb.top + (hb.height / 2)
};
- jasmine.triggerMouseEvent(chart, 'click', el);
-
- expect(clickItem).toBe(chart.legend.legendItems[0]);
-
- jasmine.triggerMouseEvent(chart, 'mousemove', el);
+ afterEvent(chart, 'click', function() {
+ expect(clickItem).toBe(chart.legend.legendItems[0]);
- expect(hoverItem).toBe(chart.legend.legendItems[0]);
+ afterEvent(chart, 'mousemove', function() {
+ expect(hoverItem).toBe(chart.legend.legendItems[0]);
- jasmine.triggerMouseEvent(chart, 'mousemove', chart.getDatasetMeta(0).data[0]);
+ afterEvent(chart, 'mousemove', function() {
+ expect(leaveItem).toBe(chart.legend.legendItems[0]);
- expect(leaveItem).toBe(chart.legend.legendItems[0]);
+ done();
+ });
+ jasmine.triggerMouseEvent(chart, 'mousemove', chart.getDatasetMeta(0).data[0]);
+ });
+ jasmine.triggerMouseEvent(chart, 'mousemove', el);
+ });
+ jasmine.triggerMouseEvent(chart, 'click', el);
});
});
}); | true |
Other | chartjs | Chart.js | a1c2dd6fb64ba128db95ac4ea2c46a064959bb47.json | Throttle all events (to 1 / frame each) (#6953)
* Throttle all events
* Asynchronize event tests | test/utils.js | @@ -106,6 +106,18 @@ function waitForResize(chart, callback) {
};
}
+function afterEvent(chart, type, callback) {
+ var override = chart.eventHandler;
+ chart.eventHandler = function(event) {
+ override.call(this, event);
+ if (event.type === type) {
+ chart.eventHandler = override;
+ // eslint-disable-next-line callback-return
+ callback();
+ }
+ };
+}
+
function _resolveElementPoint(el) {
var point = {x: 0, y: 0};
if (el) {
@@ -140,5 +152,6 @@ module.exports = {
releaseChart: releaseChart,
readImageData: readImageData,
triggerMouseEvent: triggerMouseEvent,
- waitForResize: waitForResize
+ waitForResize: waitForResize,
+ afterEvent: afterEvent
}; | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | docs/configuration/README.md | @@ -37,8 +37,8 @@ var chartDifferentHoverMode = new Chart(ctx, {
Options may be configured directly on the dataset. The dataset options can be changed at 3 different levels and are evaluated with the following priority:
- per dataset: dataset.*
-- per chart: options.datasets[type].*
-- or globally: Chart.defaults.datasets[type].*
+- per chart: options[type].datasets.*
+- or globally: Chart.defaults[type].datasets.*
where type corresponds to the dataset type.
| true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | docs/developers/charts.md | @@ -81,10 +81,6 @@ For example, to derive a new chart type that extends from a bubble chart, you wo
// It looks like a bug exists when the defaults don't exist
Chart.defaults.derivedBubble = Chart.defaults.bubble;
-// Sets the default dataset config for 'derivedBubble' to be the same as the bubble dataset defaults.
-// It looks like a bug exists when the dataset defaults don't exist
-Chart.defaults.datasets.derivedBubble = Chart.defaults.datasets.bubble;
-
// I think the recommend using Chart.controllers.bubble.extend({ extensions here });
var custom = Chart.controllers.bubble.extend({
draw: function(ease) { | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | docs/getting-started/v3-migration.md | @@ -45,6 +45,7 @@ Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released
### Options
+* Dataset options are now configured as `options[type].datasets` rather than `options.datasets[type]`
* `Polar area` `startAngle` option is now consistent with `Radar`, 0 is at top and value is in degrees. Default is changed from `-½π` to `0`.
* `scales.[x/y]Axes` arrays were removed. Scales are now configured directly to `options.scales` object with the object key being the scale Id.
* `scales.[x/y]Axes.barPercentage` was moved to dataset option `barPercentage` | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | src/controllers/controller.bar.js | @@ -12,6 +12,17 @@ defaults._set('bar', {
mode: 'index'
},
+ datasets: {
+ categoryPercentage: 0.8,
+ barPercentage: 0.9,
+ animation: {
+ numbers: {
+ type: 'number',
+ properties: ['x', 'y', 'base', 'width', 'height']
+ }
+ }
+ },
+
scales: {
x: {
type: 'category',
@@ -27,19 +38,6 @@ defaults._set('bar', {
}
});
-defaults._set('datasets', {
- bar: {
- categoryPercentage: 0.8,
- barPercentage: 0.9,
- animation: {
- numbers: {
- type: 'number',
- properties: ['x', 'y', 'base', 'width', 'height']
- }
- }
- }
-});
-
/**
* Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
* @private | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | src/controllers/controller.horizontalBar.js | @@ -25,6 +25,11 @@ defaults._set('horizontalBar', {
}
},
+ datasets: {
+ categoryPercentage: 0.8,
+ barPercentage: 0.9
+ },
+
elements: {
rectangle: {
borderSkipped: 'left'
@@ -37,13 +42,6 @@ defaults._set('horizontalBar', {
}
});
-defaults._set('datasets', {
- horizontalBar: {
- categoryPercentage: 0.8,
- barPercentage: 0.9
- }
-});
-
export default BarController.extend({
/**
* @private | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | src/controllers/controller.scatter.js | @@ -15,6 +15,10 @@ defaults._set('scatter', {
}
},
+ datasets: {
+ showLine: false
+ },
+
tooltips: {
callbacks: {
title: function() {
@@ -27,11 +31,5 @@ defaults._set('scatter', {
}
});
-defaults._set('datasets', {
- scatter: {
- showLine: false
- }
-});
-
// Scatter charts use line controllers
export default LineController; | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | src/core/core.datasetController.js | @@ -476,7 +476,7 @@ helpers.extend(DatasetController.prototype, {
_configure: function() {
const me = this;
me._config = helpers.merge({}, [
- me.chart.options.datasets[me._type],
+ me.chart.options[me._type].datasets,
me.getDataset(),
], {
merger: function(key, target, source) { | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | test/fixtures/controller.bar/bar-thickness-multiple.json | @@ -18,8 +18,8 @@
"responsive": false,
"legend": false,
"title": false,
- "datasets": {
- "bar": {
+ "bar": {
+ "datasets": {
"barPercentage": 1,
"categoryPercentage": 1
} | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | test/fixtures/controller.bar/bar-thickness-no-overlap.json | @@ -18,8 +18,8 @@
"responsive": false,
"legend": false,
"title": false,
- "datasets": {
- "bar": {
+ "bar": {
+ "datasets": {
"barPercentage": 1,
"categoryPercentage": 1
} | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | test/fixtures/controller.bar/bar-thickness-offset.json | @@ -18,8 +18,8 @@
"responsive": false,
"legend": false,
"title": false,
- "datasets": {
- "bar": {
+ "bar": {
+ "datasets": {
"barPercentage": 1,
"categoryPercentage": 1
} | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | test/fixtures/controller.bar/bar-thickness-reverse.json | @@ -18,8 +18,8 @@
"responsive": false,
"legend": false,
"title": false,
- "datasets": {
- "bar": {
+ "bar": {
+ "datasets": {
"barPercentage": 1,
"categoryPercentage": 1
} | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | test/fixtures/controller.bar/bar-thickness-stacked.json | @@ -18,8 +18,8 @@
"responsive": false,
"legend": false,
"title": false,
- "datasets": {
- "bar": {
+ "bar": {
+ "datasets": {
"barPercentage": 1,
"categoryPercentage": 1
} | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | test/fixtures/controller.bar/stacking/logarithmic-strings.js | @@ -14,8 +14,8 @@ module.exports = {
options: {
legend: false,
title: false,
- datasets: {
- bar: {
+ bar: {
+ datasets: {
barPercentage: 1,
}
}, | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | test/fixtures/controller.bar/stacking/logarithmic.js | @@ -14,8 +14,8 @@ module.exports = {
options: {
legend: false,
title: false,
- datasets: {
- bar: {
+ bar: {
+ datasets: {
barPercentage: 1,
}
}, | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | test/fixtures/plugin.filler/fill-line-dataset-interpolated.js | @@ -41,8 +41,8 @@ module.exports = {
responsive: false,
legend: false,
title: false,
- datasets: {
- line: {
+ line: {
+ datasets: {
lineTension: 0.4,
borderWidth: 1,
pointRadius: 1.5, | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | test/specs/controller.bar.tests.js | @@ -1387,7 +1387,7 @@ describe('Chart.controllers.bar', function() {
var chart = window.acquireChart(this.config);
var meta = chart.getDatasetMeta(0);
var xScale = chart.scales[meta.xAxisID];
- var options = Chart.defaults.datasets.bar;
+ var options = Chart.defaults.bar.datasets;
var categoryPercentage = options.categoryPercentage;
var barPercentage = options.barPercentage;
@@ -1535,8 +1535,8 @@ describe('Chart.controllers.bar', function() {
options: {
legend: false,
title: false,
- datasets: {
- bar: {
+ bar: {
+ datasets: {
barThickness: barThickness
}
},
@@ -1561,7 +1561,7 @@ describe('Chart.controllers.bar', function() {
expected = barThickness;
} else {
var scale = chart.scales.x;
- var options = Chart.defaults.datasets.bar;
+ var options = Chart.defaults.bar.datasets;
var categoryPercentage = options.categoryPercentage;
var barPercentage = options.barPercentage;
var tickInterval = scale.getPixelForTick(1) - scale.getPixelForTick(0); | true |
Other | chartjs | Chart.js | 9bd2af9e9b7bd2ad586fb17d7a47f72e055c0144.json | Move location of dataset options (#6955)
* Move location of dataset options
* Fix misplaced period | test/specs/controller.line.tests.js | @@ -559,18 +559,18 @@ describe('Chart.controllers.line', function() {
describe('dataset global defaults', function() {
beforeEach(function() {
- this._defaults = Chart.helpers.clone(Chart.defaults.datasets.line);
+ this._defaults = Chart.helpers.clone(Chart.defaults.line.datasets);
});
afterEach(function() {
- Chart.defaults.datasets.line = this._defaults;
+ Chart.defaults.line.datasets = this._defaults;
delete this._defaults;
});
it('should utilize the dataset global default options', function() {
- Chart.defaults.datasets.line = Chart.defaults.datasets.line || {};
+ Chart.defaults.line.datasets = Chart.defaults.line.datasets || {};
- Chart.helpers.merge(Chart.defaults.datasets.line, {
+ Chart.helpers.merge(Chart.defaults.line.datasets, {
spanGaps: true,
lineTension: 0.231,
backgroundColor: '#add',
@@ -611,9 +611,9 @@ describe('Chart.controllers.line', function() {
});
it('should be overriden by user-supplied values', function() {
- Chart.defaults.datasets.line = Chart.defaults.datasets.line || {};
+ Chart.defaults.line.datasets = Chart.defaults.line.datasets || {};
- Chart.helpers.merge(Chart.defaults.datasets.line, {
+ Chart.helpers.merge(Chart.defaults.line.datasets, {
spanGaps: true,
lineTension: 0.231
});
@@ -630,8 +630,8 @@ describe('Chart.controllers.line', function() {
labels: ['label1', 'label2']
},
options: {
- datasets: {
- line: {
+ line: {
+ datasets: {
lineTension: 0.345,
backgroundColor: '#add'
}
@@ -661,8 +661,8 @@ describe('Chart.controllers.line', function() {
labels: ['label1', 'label2']
},
options: {
- datasets: {
- line: {
+ line: {
+ datasets: {
spanGaps: true,
lineTension: 0.231,
backgroundColor: '#add', | true |
Other | chartjs | Chart.js | 5e6fb37646d7d04465c3cd094f724228e2078639.json | Detect stack change (#6947)
* Detect stack change
* Add test | src/core/core.datasetController.js | @@ -443,13 +443,30 @@ helpers.extend(DatasetController.prototype, {
const labelsChanged = me._labelCheck();
const scaleChanged = me._scaleCheck();
const meta = me._cachedMeta;
+ const dataset = me.getDataset();
+ let stackChanged = false;
// make sure cached _stacked status is current
meta._stacked = isStacked(meta.vScale, meta);
+ // detect change in stack option
+ if (meta.stack !== dataset.stack) {
+ stackChanged = true;
+ // remove values from old stack
+ meta._parsed.forEach(function(parsed) {
+ delete parsed._stacks[meta.vScale.id][meta.index];
+ });
+ meta.stack = dataset.stack;
+ }
+
// 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);
+ me.resyncElements(dataChanged | labelsChanged | scaleChanged | stackChanged);
+
+ // if stack changed, update stack values for the whole dataset
+ if (stackChanged) {
+ updateStacks(me, meta._parsed);
+ }
},
/** | true |
Other | chartjs | Chart.js | 5e6fb37646d7d04465c3cd094f724228e2078639.json | Detect stack change (#6947)
* Detect stack change
* Add test | test/specs/core.datasetController.tests.js | @@ -388,6 +388,50 @@ describe('Chart.DatasetController', function() {
expect(meta.yAxisID).toBe('secondYScaleID');
});
+ it('should re-synchronize stacks when stack is changed', function() {
+ var chart = acquireChart({
+ type: 'bar',
+ data: {
+ labels: ['a', 'b'],
+ datasets: [{
+ data: [1, 10],
+ stack: '1'
+ }, {
+ data: [2, 20],
+ stack: '2'
+ }, {
+ data: [3, 30],
+ stack: '1'
+ }]
+ }
+ });
+
+ expect(chart._stacks).toEqual({
+ 'x.y.1.bar': {
+ 0: {0: 1, 2: 3},
+ 1: {0: 10, 2: 30}
+ },
+ 'x.y.2.bar': {
+ 0: {1: 2},
+ 1: {1: 20}
+ }
+ });
+
+ chart.data.datasets[2].stack = '2';
+ chart.update();
+
+ expect(chart._stacks).toEqual({
+ 'x.y.1.bar': {
+ 0: {0: 1},
+ 1: {0: 10}
+ },
+ 'x.y.2.bar': {
+ 0: {1: 2, 2: 3},
+ 1: {1: 20, 2: 30}
+ }
+ });
+ });
+
it('should cleanup attached properties when the reference changes or when the chart is destroyed', function() {
var data0 = [0, 1, 2, 3, 4, 5];
var data1 = [6, 7, 8]; | true |
Other | chartjs | Chart.js | f1677b6652328f449c1995f3e551c1b666eb2c8f.json | Limit interactions to chartArea (+/-0.5px) (#6943)
Limit interactions to chartArea (+/-0.5px) | docs/getting-started/v3-migration.md | @@ -19,6 +19,7 @@ Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released
### Interactions
+* `interactions` are now limited to the chart area
* `{mode: 'label'}` was replaced with `{mode: 'index'}`
* `{mode: 'single'}` was replaced with `{mode: 'nearest', intersect: true}`
* `modes['X-axis']` was replaced with `{mode: 'index', intersect: false}`
@@ -117,6 +118,7 @@ Animation system was completely rewritten in Chart.js v3. Each property can now
* `Element._view`
* `TimeScale._getPixelForOffset`
* `TimeScale.getLabelWidth`
+* `Tooltip._lastActive`
### Renamed
| true |
Other | chartjs | Chart.js | f1677b6652328f449c1995f3e551c1b666eb2c8f.json | Limit interactions to chartArea (+/-0.5px) (#6943)
Limit interactions to chartArea (+/-0.5px) | src/controllers/controller.horizontalBar.js | @@ -12,7 +12,8 @@ defaults._set('horizontalBar', {
scales: {
x: {
type: 'linear',
- position: 'bottom'
+ position: 'bottom',
+ beginAtZero: true
},
y: {
type: 'category', | true |
Other | chartjs | Chart.js | f1677b6652328f449c1995f3e551c1b666eb2c8f.json | Limit interactions to chartArea (+/-0.5px) (#6943)
Limit interactions to chartArea (+/-0.5px) | src/core/core.interaction.js | @@ -2,6 +2,7 @@
import helpers from '../helpers/index';
import {isNumber} from '../helpers/helpers.math';
+import {_isPointInArea} from '../helpers/helpers.canvas';
/**
* Helper function to get relative position for an event
@@ -43,6 +44,8 @@ function evaluateAllVisibleItems(chart, handler) {
/**
* Helper function to check the items at the hovered index on the index scale
* @param {Chart} chart - the chart
+ * @param {string} axis - the axis mode. x|y|xy
+ * @param {object} position - the point to be nearest to
* @param {function} handler - the callback to execute for each visible item
* @return whether all scales were of a suitable type
*/
@@ -91,13 +94,18 @@ function getDistanceMetricForAxis(axis) {
/**
* Helper function to get the items that intersect the event position
- * @param {ChartElement[]} items - elements to filter
+ * @param {Chart} chart - the chart
* @param {object} position - the point to be nearest to
+ * @param {string} axis - the axis mode. x|y|xy
* @return {ChartElement[]} the nearest items
*/
function getIntersectItems(chart, position, axis) {
const items = [];
+ if (!_isPointInArea(position, chart.chartArea)) {
+ return items;
+ }
+
const evaluationFunc = function(element, datasetIndex, index) {
if (element.inRange(position.x, position.y)) {
items.push({element, datasetIndex, index});
@@ -126,6 +134,10 @@ function getNearestItems(chart, position, axis, intersect) {
let minDistance = Number.POSITIVE_INFINITY;
let items = [];
+ if (!_isPointInArea(position, chart.chartArea)) {
+ return items;
+ }
+
const evaluationFunc = function(element, datasetIndex, index) {
if (intersect && !element.inRange(position.x, position.y)) {
return; | true |
Other | chartjs | Chart.js | f1677b6652328f449c1995f3e551c1b666eb2c8f.json | Limit interactions to chartArea (+/-0.5px) (#6943)
Limit interactions to chartArea (+/-0.5px) | src/core/core.tooltip.js | @@ -219,10 +219,10 @@ function createTooltipItem(chart, item) {
const {label, value} = chart.getDatasetMeta(datasetIndex).controller._getLabelAndValue(index);
return {
- label: label,
- value: value,
- index: index,
- datasetIndex: datasetIndex
+ label,
+ value,
+ index,
+ datasetIndex
};
}
@@ -452,7 +452,6 @@ class Tooltip extends Element {
const me = this;
me.opacity = 0;
me._active = [];
- me._lastActive = [];
me.initialize();
}
@@ -962,28 +961,26 @@ class Tooltip extends Element {
* @returns {boolean} true if the tooltip changed
*/
handleEvent(e) {
- var me = this;
- var options = me.options;
- var changed = false;
-
- me._lastActive = me._lastActive || [];
+ const me = this;
+ const options = me.options;
+ const lastActive = me._active || [];
+ let changed = false;
+ let active = [];
// Find Active Elements for tooltips
- if (e.type === 'mouseout') {
- me._active = [];
- } else {
- me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
+ if (e.type !== 'mouseout') {
+ active = me._chart.getElementsAtEventForMode(e, options.mode, options);
if (options.reverse) {
- me._active.reverse();
+ active.reverse();
}
}
// Remember Last Actives
- changed = !helpers._elementsEqual(me._active, me._lastActive);
+ changed = !helpers._elementsEqual(active, lastActive);
// Only handle target event on tooltip change
if (changed) {
- me._lastActive = me._active;
+ me._active = active;
if (options.enabled || options.custom) {
me._eventPosition = {
@@ -992,7 +989,6 @@ class Tooltip extends Element {
};
me.update(true);
- // me.pivot();
}
}
| true |
Other | chartjs | Chart.js | f1677b6652328f449c1995f3e551c1b666eb2c8f.json | Limit interactions to chartArea (+/-0.5px) (#6943)
Limit interactions to chartArea (+/-0.5px) | src/helpers/helpers.canvas.js | @@ -153,7 +153,7 @@ export function drawPoint(ctx, style, radius, x, y, rotation) {
* @private
*/
export function _isPointInArea(point, area) {
- var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
+ const epsilon = 0.5; // margin - to match rounded decimals
return point.x > area.left - epsilon && point.x < area.right + epsilon &&
point.y > area.top - epsilon && point.y < area.bottom + epsilon; | true |
Other | chartjs | Chart.js | f1677b6652328f449c1995f3e551c1b666eb2c8f.json | Limit interactions to chartArea (+/-0.5px) (#6943)
Limit interactions to chartArea (+/-0.5px) | test/specs/controller.line.tests.js | @@ -773,6 +773,11 @@ describe('Chart.controllers.line', function() {
}]
},
options: {
+ scales: {
+ x: {
+ offset: true
+ }
+ },
elements: {
point: {
backgroundColor: 'rgb(100, 150, 200)', | true |
Other | chartjs | Chart.js | f1677b6652328f449c1995f3e551c1b666eb2c8f.json | Limit interactions to chartArea (+/-0.5px) (#6943)
Limit interactions to chartArea (+/-0.5px) | test/specs/core.controller.tests.js | @@ -1130,12 +1130,12 @@ describe('Chart', function() {
var tooltip = chart.tooltip;
expect(chart.lastActive[0].element).toEqual(point);
- expect(tooltip._lastActive[0].element).toEqual(point);
+ expect(tooltip._active[0].element).toEqual(point);
// Update and confirm tooltip is updated
chart.update();
expect(chart.lastActive[0].element).toEqual(point);
- expect(tooltip._lastActive[0].element).toEqual(point);
+ expect(tooltip._active[0].element).toEqual(point);
});
it ('should update the metadata', function() { | true |
Other | chartjs | Chart.js | f1677b6652328f449c1995f3e551c1b666eb2c8f.json | Limit interactions to chartArea (+/-0.5px) (#6943)
Limit interactions to chartArea (+/-0.5px) | test/specs/core.interaction.tests.js | @@ -143,8 +143,8 @@ describe('Core.Interaction', function() {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
- x: 0,
- y: 0
+ x: chart.chartArea.left,
+ y: chart.chartArea.top
};
var elements = Chart.Interaction.modes.index(chart, evt, {intersect: false}).map(item => item.element);
@@ -182,8 +182,8 @@ describe('Core.Interaction', function() {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
- x: 0,
- y: 0
+ x: chart.chartArea.left,
+ y: chart.chartArea.top
};
var elements = Chart.Interaction.modes.index(chart, evt, {axis: 'xy', intersect: false}).map(item => item.element);
@@ -279,8 +279,8 @@ describe('Core.Interaction', function() {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
- x: 0,
- y: 0
+ x: chart.chartArea.left,
+ y: chart.chartArea.top
};
var elements = Chart.Interaction.modes.dataset(chart, evt, {axis: 'x', intersect: false});
@@ -293,8 +293,8 @@ describe('Core.Interaction', function() {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
- x: 0,
- y: 0
+ x: chart.chartArea.left,
+ y: chart.chartArea.top
};
var elements = Chart.Interaction.modes.dataset(chart, evt, {axis: 'y', intersect: false});
@@ -307,8 +307,8 @@ describe('Core.Interaction', function() {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
- x: 0,
- y: 0
+ x: chart.chartArea.left,
+ y: chart.chartArea.top
};
var elements = Chart.Interaction.modes.dataset(chart, evt, {intersect: false});
@@ -348,8 +348,8 @@ describe('Core.Interaction', function() {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
- x: 0,
- y: 0
+ x: chart.chartArea.left,
+ y: chart.chartArea.top
};
// Nearest to 0,0 (top left) will be first point of dataset 2 | true |
Other | chartjs | Chart.js | f1677b6652328f449c1995f3e551c1b666eb2c8f.json | Limit interactions to chartArea (+/-0.5px) (#6943)
Limit interactions to chartArea (+/-0.5px) | test/specs/core.tooltip.tests.js | @@ -70,7 +70,7 @@ describe('Core.Tooltip', function() {
bubbles: true,
cancelable: true,
clientX: rect.left + point.x,
- clientY: 0
+ clientY: rect.top + chart.chartArea.top + 5 // +5 to make tests work consistently
});
// Manually trigger rather than having an async test | true |
Other | chartjs | Chart.js | f1677b6652328f449c1995f3e551c1b666eb2c8f.json | Limit interactions to chartArea (+/-0.5px) (#6943)
Limit interactions to chartArea (+/-0.5px) | test/specs/helpers.canvas.tests.js | @@ -32,8 +32,8 @@ describe('Chart.helpers.canvas', function() {
expect(isPointInArea({x: -1e-12, y: -1e-12}, area)).toBe(true);
expect(isPointInArea({x: 512, y: 256}, area)).toBe(true);
expect(isPointInArea({x: 512 + 1e-12, y: 256 + 1e-12}, area)).toBe(true);
- expect(isPointInArea({x: -1e-3, y: 0}, area)).toBe(false);
- expect(isPointInArea({x: 0, y: 256 + 1e-3}, area)).toBe(false);
+ expect(isPointInArea({x: -0.5, y: 0}, area)).toBe(false);
+ expect(isPointInArea({x: 0, y: 256.5}, area)).toBe(false);
});
});
}); | true |
Other | chartjs | Chart.js | a6a12282c49e006d3a6fc06297f39b84fe409deb.json | Fix memory leak on destroy (#8438) | src/core/core.config.js | @@ -156,9 +156,13 @@ export default class Config {
update(options) {
const config = this._config;
+ this.clearCache();
+ config.options = initOptions(config, options);
+ }
+
+ clearCache() {
this._scopeCache.clear();
this._resolverCache.clear();
- config.options = initOptions(config, options);
}
/** | true |
Other | chartjs | Chart.js | a6a12282c49e006d3a6fc06297f39b84fe409deb.json | Fix memory leak on destroy (#8438) | src/core/core.controller.js | @@ -831,6 +831,8 @@ class Chart {
me._destroyDatasetMeta(i);
}
+ me.config.clearCache();
+
if (canvas) {
me.unbindEvents();
clearCanvas(canvas, ctx); | true |
Other | chartjs | Chart.js | 81e28c9895ad685b2b567a5de4b70ea591d275ae.json | Add a note about hover options (#8436) | docs/docs/general/interactions/index.md | @@ -9,3 +9,5 @@ The interaction configuration is passed into the `options.interaction` namespace
| `mode` | `string` | `'nearest'` | Sets which elements appear in the tooltip. See [Interaction Modes](./modes.md#interaction-modes) for details.
| `intersect` | `boolean` | `true` | if true, the hover mode only applies when the mouse position intersects an item on the chart.
| `axis` | `string` | `'x'` | Can be set to `'x'`, `'y'`, or `'xy'` to define which directions are used in calculating distances. Defaults to `'x'` for `'index'` mode and `'xy'` in `dataset` and `'nearest'` modes.
+
+The same options can be set into the `options.hover` namespace, in which case they will only affect the hover effect and the tooltip configuration will be kept independent. | false |
Other | chartjs | Chart.js | 19a91bebfbed1ed5c57ccda02563147512350569.json | Remove unused typedoc option that is deprecated (#8433)
* Remove unused typedoc option that is deprecated
* Improved filtering for top level file changes | .github/workflows/ci.yml | @@ -34,13 +34,19 @@ jobs:
filters: |
docs:
- 'docs/**'
+ - 'package.json'
+ - 'tsconfig.json'
src:
- 'src/**'
+ - 'package.json'
test:
- 'test/**'
- 'karma.conf.js'
+ - 'package.json'
types:
- 'types/**'
+ - 'package.json'
+ - 'tsconfig.json'
- name: Install
run: npm ci
- name: Build | true |
Other | chartjs | Chart.js | 19a91bebfbed1ed5c57ccda02563147512350569.json | Remove unused typedoc option that is deprecated (#8433)
* Remove unused typedoc option that is deprecated
* Improved filtering for top level file changes | tsconfig.json | @@ -14,7 +14,6 @@
"name": "Chart.js",
"entryPoints": ["src/index.esm.js"],
"excludeExternals": true,
- "excludeNotExported": true,
"includeVersion": true,
"out": "./dist/docs/typedoc"
}, | true |
Other | chartjs | Chart.js | 505afa7f1323cf6e7975369eba30056977085eaa.json | Fix element creation for large dataset (#8388)
* Fix element creation for large dataset
* Fix syncing
* Remove duplication | src/core/core.datasetController.js | @@ -990,18 +990,25 @@ export default class DatasetController {
*/
_insertElements(start, count, resetNewElements = true) {
const me = this;
- const elements = new Array(count);
const meta = me._cachedMeta;
const data = meta.data;
+ const end = start + count;
let i;
- for (i = 0; i < count; ++i) {
- elements[i] = new me.dataElementType();
+ const move = (arr) => {
+ arr.length += count;
+ for (i = arr.length - 1; i >= end; i--) {
+ arr[i] = arr[i - count];
+ }
+ };
+ move(data);
+
+ for (i = start; i < end; ++i) {
+ data[i] = new me.dataElementType();
}
- data.splice(start, 0, ...elements);
if (me._parsing) {
- meta._parsed.splice(start, 0, ...new Array(count));
+ move(meta._parsed);
}
me.parse(start, count);
| true |
Other | chartjs | Chart.js | 505afa7f1323cf6e7975369eba30056977085eaa.json | Fix element creation for large dataset (#8388)
* Fix element creation for large dataset
* Fix syncing
* Remove duplication | test/specs/controller.line.tests.js | @@ -907,4 +907,30 @@ describe('Chart.controllers.line', function() {
expect(meta.data[2].options.borderWidth).toBe(3);
expect(meta.data[3].options.borderWidth).toBe(4);
});
+
+ it('should render a million points', function() {
+ var data = [];
+ for (let x = 0; x < 1e6; x++) {
+ data.push({x, y: Math.sin(x / 10000)});
+ }
+ function createChart() {
+ window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ data,
+ borderWidth: 1,
+ radius: 0
+ }],
+ },
+ options: {
+ scales: {
+ x: {type: 'linear'},
+ y: {type: 'linear'}
+ }
+ }
+ });
+ }
+ expect(createChart).not.toThrow();
+ });
}); | true |
Other | chartjs | Chart.js | 650956b2e1ec8a9591135476cc61f64ddaad7f12.json | Create a new hook to enable data decimation (#8255)
* Create a new hook to enable data decimation
The `beforeElementUpdate` hook can be used to decimate data. The chart
elements will not be created until after this hook has fired ensuring that
if decimation occurs, only the needed elements will be created.
* Address code review feedback
* Rename hook to beforeElementsUpdate
* Simplify parsing logic
* Add decimation plugin to the core
* Allow a dataset to specify a different data key
* Decimation plugin uses the dataKey feature
* Refactor the decimation plugin to support configurable algorithms
* Lint the plugin changes
* Tests for the dataKey feature
* Convert test files to tabs
* Standardize on tabs in ts files
* Remove the dataKey feature
* Replace dataKey usage in decimation plugin
We define a new descriptor for the `data` key allowing the
plugin to be simpler.
* Disable decimation when indexAxis is Y
* Simplify the decimation width approximation
* Resolve the indexAxis correctly in all cases
* Initial documentation
* Reverse check
* Update TS definitions for new plugin options
* Move defineProperty after bailouts
* Add destroy hook | docs/docs/configuration/decimation.md | @@ -0,0 +1,33 @@
+---
+title: Data Decimation
+---
+
+The decimation plugin can be used with line charts to automatically decimate data at the start of the chart lifecycle. Before enabling this plugin, review the [requirements](#requirements) to ensure that it will work with the chart you want to create.
+
+## Configuration Options
+
+The decimation plugin configuration is passed into the `options.plugins.decimation` namespace. The global options for the plugin are defined in `Chart.defaults.plugins.decimation`.
+
+| Name | Type | Default | Description
+| ---- | ---- | ------- | -----------
+| `enabled` | `boolean` | `true` | Is decimation enabled?
+| `algorithm` | `string` | `'min-max'` | Decimation algorithm to use. See the [more...](#decimation-algorithms)
+
+## Decimation Algorithms
+
+Decimation algorithm to use for data. Options are:
+
+* `'min-max'`
+
+### Min/Max Decimation
+
+[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.
+
+## Requirements
+
+To use the decimation plugin, the following requirements must be met:
+
+1. The dataset must have an `indexAxis` of `'x'`
+2. The dataset must be a line
+3. The X axis for the dataset must be either a `'linear'` or `'time'` type axis
+4. The dataset object must be mutable. The plugin stores the original data as `dataset._data` and then defines a new `data` property on the dataset. | true |
Other | chartjs | Chart.js | 650956b2e1ec8a9591135476cc61f64ddaad7f12.json | Create a new hook to enable data decimation (#8255)
* Create a new hook to enable data decimation
The `beforeElementUpdate` hook can be used to decimate data. The chart
elements will not be created until after this hook has fired ensuring that
if decimation occurs, only the needed elements will be created.
* Address code review feedback
* Rename hook to beforeElementsUpdate
* Simplify parsing logic
* Add decimation plugin to the core
* Allow a dataset to specify a different data key
* Decimation plugin uses the dataKey feature
* Refactor the decimation plugin to support configurable algorithms
* Lint the plugin changes
* Tests for the dataKey feature
* Convert test files to tabs
* Standardize on tabs in ts files
* Remove the dataKey feature
* Replace dataKey usage in decimation plugin
We define a new descriptor for the `data` key allowing the
plugin to be simpler.
* Disable decimation when indexAxis is Y
* Simplify the decimation width approximation
* Resolve the indexAxis correctly in all cases
* Initial documentation
* Reverse check
* Update TS definitions for new plugin options
* Move defineProperty after bailouts
* Add destroy hook | docs/docs/general/performance.md | @@ -18,7 +18,7 @@ Chart.js is fastest if you provide data with indices that are unique, sorted, an
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.
+The [decimation plugin](./configuration/decimation.md) can be used with line charts to decimate data before the chart is rendered. This will provide the best performance since it will reduce the memory needed to render the chart.
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.
| true |
Other | chartjs | Chart.js | 650956b2e1ec8a9591135476cc61f64ddaad7f12.json | Create a new hook to enable data decimation (#8255)
* Create a new hook to enable data decimation
The `beforeElementUpdate` hook can be used to decimate data. The chart
elements will not be created until after this hook has fired ensuring that
if decimation occurs, only the needed elements will be created.
* Address code review feedback
* Rename hook to beforeElementsUpdate
* Simplify parsing logic
* Add decimation plugin to the core
* Allow a dataset to specify a different data key
* Decimation plugin uses the dataKey feature
* Refactor the decimation plugin to support configurable algorithms
* Lint the plugin changes
* Tests for the dataKey feature
* Convert test files to tabs
* Standardize on tabs in ts files
* Remove the dataKey feature
* Replace dataKey usage in decimation plugin
We define a new descriptor for the `data` key allowing the
plugin to be simpler.
* Disable decimation when indexAxis is Y
* Simplify the decimation width approximation
* Resolve the indexAxis correctly in all cases
* Initial documentation
* Reverse check
* Update TS definitions for new plugin options
* Move defineProperty after bailouts
* Add destroy hook | docs/sidebars.js | @@ -30,7 +30,8 @@ module.exports = {
'configuration/legend',
'configuration/title',
'configuration/tooltip',
- 'configuration/elements'
+ 'configuration/elements',
+ 'configuration/decimation'
],
'Chart Types': [
'charts/line', | true |
Other | chartjs | Chart.js | 650956b2e1ec8a9591135476cc61f64ddaad7f12.json | Create a new hook to enable data decimation (#8255)
* Create a new hook to enable data decimation
The `beforeElementUpdate` hook can be used to decimate data. The chart
elements will not be created until after this hook has fired ensuring that
if decimation occurs, only the needed elements will be created.
* Address code review feedback
* Rename hook to beforeElementsUpdate
* Simplify parsing logic
* Add decimation plugin to the core
* Allow a dataset to specify a different data key
* Decimation plugin uses the dataKey feature
* Refactor the decimation plugin to support configurable algorithms
* Lint the plugin changes
* Tests for the dataKey feature
* Convert test files to tabs
* Standardize on tabs in ts files
* Remove the dataKey feature
* Replace dataKey usage in decimation plugin
We define a new descriptor for the `data` key allowing the
plugin to be simpler.
* Disable decimation when indexAxis is Y
* Simplify the decimation width approximation
* Resolve the indexAxis correctly in all cases
* Initial documentation
* Reverse check
* Update TS definitions for new plugin options
* Move defineProperty after bailouts
* Add destroy hook | src/core/core.controller.js | @@ -466,9 +466,15 @@ class Chart {
// Make sure dataset controllers are updated and new controllers are reset
const newControllers = me.buildOrUpdateControllers();
+ me.notifyPlugins('beforeElementsUpdate');
+
// Make sure all dataset controllers have correct meta data counts
for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
- me.getDatasetMeta(i).controller.buildOrUpdateElements();
+ const {controller} = me.getDatasetMeta(i);
+ const reset = !animsDisabled && newControllers.indexOf(controller) === -1;
+ // New controllers will be reset after the layout pass, so we only want to modify
+ // elements added to new datasets
+ controller.buildOrUpdateElements(reset);
}
me._updateLayout(); | true |
Other | chartjs | Chart.js | 650956b2e1ec8a9591135476cc61f64ddaad7f12.json | Create a new hook to enable data decimation (#8255)
* Create a new hook to enable data decimation
The `beforeElementUpdate` hook can be used to decimate data. The chart
elements will not be created until after this hook has fired ensuring that
if decimation occurs, only the needed elements will be created.
* Address code review feedback
* Rename hook to beforeElementsUpdate
* Simplify parsing logic
* Add decimation plugin to the core
* Allow a dataset to specify a different data key
* Decimation plugin uses the dataKey feature
* Refactor the decimation plugin to support configurable algorithms
* Lint the plugin changes
* Tests for the dataKey feature
* Convert test files to tabs
* Standardize on tabs in ts files
* Remove the dataKey feature
* Replace dataKey usage in decimation plugin
We define a new descriptor for the `data` key allowing the
plugin to be simpler.
* Disable decimation when indexAxis is Y
* Simplify the decimation width approximation
* Resolve the indexAxis correctly in all cases
* Initial documentation
* Reverse check
* Update TS definitions for new plugin options
* Move defineProperty after bailouts
* Add destroy hook | src/core/core.datasetController.js | @@ -349,19 +349,12 @@ export default class DatasetController {
me._dataCheck();
- const data = me._data;
- const metaData = meta.data = new Array(data.length);
-
- for (let i = 0, ilen = data.length; i < ilen; ++i) {
- metaData[i] = new me.dataElementType();
- }
-
if (me.datasetElementType) {
meta.dataset = new me.datasetElementType();
}
}
- buildOrUpdateElements() {
+ buildOrUpdateElements(resetNewElements) {
const me = this;
const meta = me._cachedMeta;
const dataset = me.getDataset();
@@ -382,7 +375,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();
+ me._resyncElements(resetNewElements);
// if stack changed, update stack values for the whole dataset
if (stackChanged) {
@@ -402,7 +395,10 @@ export default class DatasetController {
me.getDataset(),
], {
merger(key, target, source) {
- if (key !== 'data') {
+ // Cloning the data is expensive and unnecessary.
+ // Additionally, plugins may add dataset level fields that should
+ // not be cloned. We identify those via an underscore prefix
+ if (key !== 'data' && key.charAt(0) !== '_') {
_merger(key, target, source);
}
}
@@ -419,13 +415,10 @@ export default class DatasetController {
const {_cachedMeta: meta, _data: data} = me;
const {iScale, _stacked} = meta;
const iAxis = iScale.axis;
- let sorted = true;
- let i, parsed, cur, prev;
- if (start > 0) {
- sorted = meta._sorted;
- prev = meta._parsed[start - 1];
- }
+ let sorted = start === 0 && count === data.length ? true : meta._sorted;
+ let prev = start > 0 && meta._parsed[start - 1];
+ let i, cur, parsed;
if (me._parsing === false) {
meta._parsed = data;
@@ -971,13 +964,13 @@ export default class DatasetController {
/**
* @private
*/
- _resyncElements() {
+ _resyncElements(resetNewElements) {
const me = this;
const numMeta = me._cachedMeta.data.length;
const numData = me._data.length;
if (numData > numMeta) {
- me._insertElements(numMeta, numData - numMeta);
+ me._insertElements(numMeta, numData - numMeta, resetNewElements);
} else if (numData < numMeta) {
me._removeElements(numData, numMeta - numData);
}
@@ -988,7 +981,7 @@ export default class DatasetController {
/**
* @private
*/
- _insertElements(start, count) {
+ _insertElements(start, count, resetNewElements = true) {
const me = this;
const elements = new Array(count);
const meta = me._cachedMeta;
@@ -1005,7 +998,9 @@ export default class DatasetController {
}
me.parse(start, count);
- me.updateElements(data, start, count, 'reset');
+ if (resetNewElements) {
+ me.updateElements(data, start, count, 'reset');
+ }
}
updateElements(element, start, count, mode) {} // eslint-disable-line no-unused-vars | true |
Other | chartjs | Chart.js | 650956b2e1ec8a9591135476cc61f64ddaad7f12.json | Create a new hook to enable data decimation (#8255)
* Create a new hook to enable data decimation
The `beforeElementUpdate` hook can be used to decimate data. The chart
elements will not be created until after this hook has fired ensuring that
if decimation occurs, only the needed elements will be created.
* Address code review feedback
* Rename hook to beforeElementsUpdate
* Simplify parsing logic
* Add decimation plugin to the core
* Allow a dataset to specify a different data key
* Decimation plugin uses the dataKey feature
* Refactor the decimation plugin to support configurable algorithms
* Lint the plugin changes
* Tests for the dataKey feature
* Convert test files to tabs
* Standardize on tabs in ts files
* Remove the dataKey feature
* Replace dataKey usage in decimation plugin
We define a new descriptor for the `data` key allowing the
plugin to be simpler.
* Disable decimation when indexAxis is Y
* Simplify the decimation width approximation
* Resolve the indexAxis correctly in all cases
* Initial documentation
* Reverse check
* Update TS definitions for new plugin options
* Move defineProperty after bailouts
* Add destroy hook | src/plugins/index.js | @@ -1,3 +1,4 @@
+export {default as Decimation} from './plugin.decimation';
export {default as Filler} from './plugin.filler';
export {default as Legend} from './plugin.legend';
export {default as Title} from './plugin.title'; | true |
Other | chartjs | Chart.js | 650956b2e1ec8a9591135476cc61f64ddaad7f12.json | Create a new hook to enable data decimation (#8255)
* Create a new hook to enable data decimation
The `beforeElementUpdate` hook can be used to decimate data. The chart
elements will not be created until after this hook has fired ensuring that
if decimation occurs, only the needed elements will be created.
* Address code review feedback
* Rename hook to beforeElementsUpdate
* Simplify parsing logic
* Add decimation plugin to the core
* Allow a dataset to specify a different data key
* Decimation plugin uses the dataKey feature
* Refactor the decimation plugin to support configurable algorithms
* Lint the plugin changes
* Tests for the dataKey feature
* Convert test files to tabs
* Standardize on tabs in ts files
* Remove the dataKey feature
* Replace dataKey usage in decimation plugin
We define a new descriptor for the `data` key allowing the
plugin to be simpler.
* Disable decimation when indexAxis is Y
* Simplify the decimation width approximation
* Resolve the indexAxis correctly in all cases
* Initial documentation
* Reverse check
* Update TS definitions for new plugin options
* Move defineProperty after bailouts
* Add destroy hook | src/plugins/plugin.decimation.js | @@ -0,0 +1,135 @@
+import {isNullOrUndef, resolve} from '../helpers';
+
+function minMaxDecimation(data, availableWidth) {
+ let i, point, x, y, prevX, minIndex, maxIndex, minY, maxY;
+ const decimated = [];
+
+ const xMin = data[0].x;
+ const xMax = data[data.length - 1].x;
+ const dx = xMax - xMin;
+
+ for (i = 0; i < data.length; ++i) {
+ point = data[i];
+ x = (point.x - xMin) / dx * availableWidth;
+ y = point.y;
+ const truncX = x | 0;
+
+ if (truncX === prevX) {
+ // Determine `minY` / `maxY` and `avgX` while we stay within same x-position
+ if (y < minY) {
+ minY = y;
+ minIndex = i;
+ } else if (y > maxY) {
+ maxY = y;
+ maxIndex = i;
+ }
+ } else {
+ // Push up to 4 points, 3 for the last interval and the first point for this interval
+ if (minIndex && maxIndex) {
+ decimated.push(data[minIndex], data[maxIndex]);
+ }
+ if (i > 0) {
+ // Last point in the previous interval
+ decimated.push(data[i - 1]);
+ }
+ decimated.push(point);
+ prevX = truncX;
+ minY = maxY = y;
+ minIndex = maxIndex = i;
+ }
+ }
+
+ return decimated;
+}
+
+export default {
+ id: 'decimation',
+
+ defaults: {
+ algorithm: 'min-max',
+ enabled: false,
+ },
+
+ beforeElementsUpdate: (chart, args, options) => {
+ if (!options.enabled) {
+ return;
+ }
+
+ // Assume the entire chart is available to show a few more points than needed
+ const availableWidth = chart.width;
+
+ chart.data.datasets.forEach((dataset, datasetIndex) => {
+ const {_data, indexAxis} = dataset;
+ const meta = chart.getDatasetMeta(datasetIndex);
+ const data = _data || dataset.data;
+
+ if (resolve([indexAxis, chart.options.indexAxis]) === 'y') {
+ // Decimation is only supported for lines that have an X indexAxis
+ return;
+ }
+
+ if (meta.type !== 'line') {
+ // Only line datasets are supported
+ return;
+ }
+
+ const xAxis = chart.scales[meta.xAxisID];
+ if (xAxis.type !== 'linear' && xAxis.type !== 'time') {
+ // Only linear interpolation is supported
+ return;
+ }
+
+ if (chart.options.parsing) {
+ // Plugin only supports data that does not need parsing
+ return;
+ }
+
+ if (data.length <= 4 * availableWidth) {
+ // No decimation is required until we are above this threshold
+ return;
+ }
+
+ if (isNullOrUndef(_data)) {
+ // First time we are seeing this dataset
+ // We override the 'data' property with a setter that stores the
+ // raw data in _data, but reads the decimated data from _decimated
+ // TODO: Undo this on chart destruction
+ dataset._data = data;
+ delete dataset.data;
+ Object.defineProperty(dataset, 'data', {
+ configurable: true,
+ enumerable: true,
+ get: function() {
+ return this._decimated;
+ },
+ set: function(d) {
+ this._data = d;
+ }
+ });
+ }
+
+ // Point the chart to the decimated data
+ let decimated;
+ switch (options.algorithm) {
+ case 'min-max':
+ decimated = minMaxDecimation(data, availableWidth);
+ break;
+ default:
+ throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);
+ }
+
+ dataset._decimated = decimated;
+ });
+ },
+
+ destroy(chart) {
+ chart.data.datasets.forEach((dataset) => {
+ if (dataset._decimated) {
+ const data = dataset._data;
+ delete dataset._decimated;
+ delete dataset._data;
+ Object.defineProperty(dataset, 'data', {value: data});
+ }
+ });
+ }
+}; | true |
Other | chartjs | Chart.js | 650956b2e1ec8a9591135476cc61f64ddaad7f12.json | Create a new hook to enable data decimation (#8255)
* Create a new hook to enable data decimation
The `beforeElementUpdate` hook can be used to decimate data. The chart
elements will not be created until after this hook has fired ensuring that
if decimation occurs, only the needed elements will be created.
* Address code review feedback
* Rename hook to beforeElementsUpdate
* Simplify parsing logic
* Add decimation plugin to the core
* Allow a dataset to specify a different data key
* Decimation plugin uses the dataKey feature
* Refactor the decimation plugin to support configurable algorithms
* Lint the plugin changes
* Tests for the dataKey feature
* Convert test files to tabs
* Standardize on tabs in ts files
* Remove the dataKey feature
* Replace dataKey usage in decimation plugin
We define a new descriptor for the `data` key allowing the
plugin to be simpler.
* Disable decimation when indexAxis is Y
* Simplify the decimation width approximation
* Resolve the indexAxis correctly in all cases
* Initial documentation
* Reverse check
* Update TS definitions for new plugin options
* Move defineProperty after bailouts
* Add destroy hook | types/index.esm.d.ts | @@ -539,7 +539,7 @@ export class DatasetController<TElement extends Element = Element, TDatasetEleme
configure(): void;
initialize(): void;
addElements(): void;
- buildOrUpdateElements(): void;
+ buildOrUpdateElements(resetNewElements?: boolean): void;
getStyle(index: number, active: boolean): any;
protected resolveDatasetElementOptions(active: boolean): any;
@@ -789,6 +789,14 @@ export interface Plugin<O = {}> extends ExtendedPlugin {
* @param {object} options - The plugin options.
*/
afterUpdate?(chart: Chart, args: { mode: UpdateMode }, options: O): void;
+ /**
+ * @desc Called during the update process, before any chart elements have been created.
+ * This can be used for data decimation by changing the data array inside a dataset.
+ * @param {Chart} chart - The chart instance.
+ * @param {object} args - The call arguments.
+ * @param {object} options - The plugin options.
+ */
+ beforeElementsUpdate?(chart: Chart, args: {}, options: O): void;
/**
* @desc Called during chart reset
* @param {Chart} chart - The chart instance.
@@ -1902,8 +1910,16 @@ export class BasePlatform {
export class BasicPlatform extends BasePlatform {}
export class DomPlatform extends BasePlatform {}
-export const Filler: Plugin;
+export declare enum DecimationAlgorithm {
+ minmax = 'min-max',
+}
+export interface DecimationOptions {
+ enabled: boolean;
+ algorithm: DecimationAlgorithm;
+}
+
+export const Filler: Plugin;
export interface FillerOptions {
propagate: boolean;
}
@@ -2477,6 +2493,7 @@ export interface TooltipItem {
}
export interface PluginOptionsByType {
+ decimation: DecimationOptions;
filler: FillerOptions;
legend: LegendOptions;
title: TitleOptions; | true |
Other | chartjs | Chart.js | ad84d285d841cefc8fef6a8e8e301bd5a68c010e.json | Rename LayoutItem.fullWidth to fullSize (#8358) | docs/docs/configuration/legend.md | @@ -15,7 +15,7 @@ The legend configuration is passed into the `options.plugins.legend` namespace.
| `align` | `string` | `'center'` | Alignment of the legend. [more...](#align)
| `maxHeight` | `number` | | Maximum height of the legend, in pixels
| `maxWidth` | `number` | | Maximum width of the legend, in pixels
-| `fullWidth` | `boolean` | `true` | Marks that this box should take the full width of the canvas (pushing down other boxes). This is unlikely to need to be changed in day-to-day use.
+| `fullSize` | `boolean` | `true` | Marks that this box should take the full width/height of the canvas (moving other boxes). This is unlikely to need to be changed in day-to-day use.
| `onClick` | `function` | | A callback that is called when a click event is registered on a label item. Arguments: `[event, legendItem, legend]`.
| `onHover` | `function` | | A callback that is called when a 'mousemove' event is registered on top of a label item. Arguments: `[event, legendItem, legend]`.
| `onLeave` | `function` | | A callback that is called when a 'mousemove' event is registered outside of a previously hovered label item. Arguments: `[event, legendItem, legend]`. | true |
Other | chartjs | Chart.js | ad84d285d841cefc8fef6a8e8e301bd5a68c010e.json | Rename LayoutItem.fullWidth to fullSize (#8358) | docs/docs/getting-started/v3-migration.md | @@ -402,6 +402,7 @@ The following properties were renamed during v3 development:
* `helpers.callCallback` was renamed to `helpers.callback`
* `helpers.drawRoundedRectangle` was renamed to `helpers.roundedRect`
* `helpers.getValueOrDefault` was renamed to `helpers.valueOrDefault`
+* `LayoutItem.fullWidth` was renamed to `LayoutItem.fullSize`
* `Scale.calculateTickRotation` was renamed to `Scale.calculateLabelRotation`
* `Tooltip.options.legendColorBackgroupd` was renamed to `Tooltip.options.multiKeyBackground`
@@ -434,6 +435,7 @@ The private APIs listed below were renamed:
* `DatasetController.onDataUnshift` was renamed to `DatasetController._onDataUnshift`
* `DatasetController.removeElements` was renamed to `DatasetController._removeElements`
* `DatasetController.resyncElements` was renamed to `DatasetController._resyncElements`
+* `LayoutItem.isFullWidth` was renamed to `LayoutItem.isFullSize`
* `RadialLinearScale.setReductions` was renamed to `RadialLinearScale._setReductions`
* `Scale.handleMargins` was renamed to `Scale._handleMargins`
| true |
Other | chartjs | Chart.js | ad84d285d841cefc8fef6a8e8e301bd5a68c010e.json | Rename LayoutItem.fullWidth to fullSize (#8358) | src/core/core.controller.js | @@ -324,7 +324,7 @@ class Chart {
each(scales, (scale) => {
// Set LayoutItem parameters for backwards compatibility
- scale.fullWidth = scale.options.fullWidth;
+ scale.fullSize = scale.options.fullSize;
scale.position = scale.options.position;
scale.weight = scale.options.weight;
layouts.addBox(me, scale); | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.