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 | 51be3447170fc648c3b5bc3002c963be62bccdf9.json | Preserve object prototypes when cloning (#7381) | src/helpers/helpers.core.js | @@ -199,7 +199,7 @@ export function clone(source) {
}
if (isObject(source)) {
- const target = {};
+ const target = Object.create(source);
const keys = Object.keys(source);
const klen = keys.length;
let k = 0; | true |
Other | chartjs | Chart.js | 51be3447170fc648c3b5bc3002c963be62bccdf9.json | Preserve object prototypes when cloning (#7381) | test/specs/helpers.core.tests.js | @@ -360,6 +360,27 @@ describe('Chart.helpers.core', function() {
expect(output.o).not.toBe(o0);
expect(output.o.a).not.toBe(a1);
});
+ it('should preserve prototype of objects', function() {
+ // https://github.com/chartjs/Chart.js/issues/7340
+ class MyConfigObject {
+ constructor(s) {
+ this._s = s;
+ }
+ func() {
+ return 10;
+ }
+ }
+ var original = new MyConfigObject('something');
+ var output = helpers.merge({}, {
+ plugins: [{
+ test: original
+ }]
+ });
+ var clone = output.plugins[0].test;
+ expect(clone).toBeInstanceOf(MyConfigObject);
+ expect(clone).toEqual(original);
+ expect(clone === original).toBeFalse();
+ });
});
describe('mergeIf', function() { | true |
Other | chartjs | Chart.js | 50f2a1097a7db459adf38a9e9981e7aa26967c72.json | Detect data modifications with equal values (#7350)
Fix data shift-push with identical values | src/core/core.datasetController.js | @@ -235,6 +235,7 @@ export default class DatasetController {
this._parsing = false;
this._data = undefined;
this._dataCopy = undefined;
+ this._dataModified = false;
this._objectData = undefined;
this._labels = undefined;
this._scaleStacked = {};
@@ -359,7 +360,7 @@ export default class DatasetController {
me._data = convertObjectDataToArray(data);
me._objectData = data;
} else {
- if (me._data === data && helpers.arrayEquals(data, me._dataCopy)) {
+ if (me._data === data && !me._dataModified && helpers.arrayEquals(data, me._dataCopy)) {
return false;
}
@@ -372,6 +373,8 @@ export default class DatasetController {
// Note: This is suboptimal, but better than always parsing the data
me._dataCopy = data.slice(0);
+ me._dataModified = false;
+
if (data && Object.isExtensible(data)) {
listenArrayEvents(data, me);
}
@@ -1111,20 +1114,23 @@ export default class DatasetController {
_onDataPush() {
const count = arguments.length;
this._insertElements(this.getDataset().data.length - count, count);
+ this._dataModified = true;
}
/**
* @private
*/
_onDataPop() {
this._removeElements(this._cachedMeta.data.length - 1, 1);
+ this._dataModified = true;
}
/**
* @private
*/
_onDataShift() {
this._removeElements(0, 1);
+ this._dataModified = true;
}
/**
@@ -1133,13 +1139,15 @@ export default class DatasetController {
_onDataSplice(start, count) {
this._removeElements(start, count);
this._insertElements(start, arguments.length - 2);
+ this._dataModified = true;
}
/**
* @private
*/
_onDataUnshift() {
this._insertElements(0, arguments.length);
+ this._dataModified = true;
}
}
| true |
Other | chartjs | Chart.js | 50f2a1097a7db459adf38a9e9981e7aa26967c72.json | Detect data modifications with equal values (#7350)
Fix data shift-push with identical values | test/specs/core.datasetController.tests.js | @@ -343,6 +343,32 @@ describe('Chart.DatasetController', function() {
expect(meta.data.length).toBe(42);
});
+ // https://github.com/chartjs/Chart.js/issues/7243
+ it('should re-synchronize metadata when data is moved and values are equal', function() {
+ var data = [10, 10, 10, 10, 10, 10];
+ var chart = acquireChart({
+ type: 'line',
+ data: {
+ labels: ['a', 'b', 'c', 'd', 'e', 'f'],
+ datasets: [{
+ data,
+ fill: true
+ }]
+ }
+ });
+
+ var meta = chart.getDatasetMeta(0);
+
+ expect(meta.data.length).toBe(6);
+ const firstX = meta.data[0].x;
+
+ data.push(data.shift());
+ chart.update();
+
+ expect(meta.data.length).toBe(6);
+ expect(meta.data[0].x).toEqual(firstX);
+ });
+
it('should re-synchronize metadata when scaleID changes', function() {
var chart = acquireChart({
type: 'line', | true |
Other | chartjs | Chart.js | ab1b0ca2b9403e00545e1caf026e951b37358ed5.json | Add a JSDoc for _dataCheck (#7377) | src/core/core.datasetController.js | @@ -339,6 +339,7 @@ export default class DatasetController {
}
/**
+ * @return {boolean} whether the data was modified
* @private
*/
_dataCheck() { | false |
Other | chartjs | Chart.js | 53f503825219e4a8ff78be16b858a0e969f9b435.json | Use correct index when resolving bubble options (#7375) | src/controllers/controller.bubble.js | @@ -110,7 +110,7 @@ export default class BubbleController extends DatasetController {
};
if (includeOptions) {
- properties.options = me.resolveDataElementOptions(i, mode);
+ properties.options = me.resolveDataElementOptions(index, mode);
if (reset) {
properties.options.radius = 0; | false |
Other | chartjs | Chart.js | c5e76fc592cddfe81cec2c9978f56c2a485552b2.json | Fix broken links to contributor's guide (#7348)
Closes https://github.com/chartjs/Chart.js/issues/7347 | README.md | @@ -25,7 +25,7 @@
## Contributing
-Instructions on building and testing Chart.js can be found in [the documentation](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md#building-and-testing). Before submitting an issue or a pull request, please take a moment to look over the [contributing guidelines](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md) first. For support, please post questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/chartjs) with the `chartjs` tag.
+Instructions on building and testing Chart.js can be found in [the documentation](https://www.chartjs.org/docs/latest/developers/contributing.html#building-and-testing). Before submitting an issue or a pull request, please take a moment to look over the [contributing guidelines](https://www.chartjs.org/docs/latest/developers/contributing.html) first. For support, please post questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/chartjs) with the `chartjs` tag.
## License
| false |
Other | chartjs | Chart.js | 319a6a40b995d94acd048939ca47e75e9ba46dce.json | Use @rollup/plugin-inject for ResizeObserver poly (#7360) | package-lock.json | @@ -1030,6 +1030,17 @@
"resolve": "^1.11.0"
}
},
+ "@rollup/plugin-inject": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@rollup/plugin-inject/-/plugin-inject-4.0.2.tgz",
+ "integrity": "sha512-TSLMA8waJ7Dmgmoc8JfPnwUwVZgLjjIAM6MqeIFqPO2ODK36JqE0Cf2F54UTgCUuW8da93Mvoj75a6KAVWgylw==",
+ "dev": true,
+ "requires": {
+ "@rollup/pluginutils": "^3.0.4",
+ "estree-walker": "^1.0.1",
+ "magic-string": "^0.25.5"
+ }
+ },
"@rollup/plugin-json": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-4.0.3.tgz",
@@ -7578,15 +7589,6 @@
"rollup-pluginutils": "^2.3.3"
}
},
- "rollup-plugin-polyfill": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/rollup-plugin-polyfill/-/rollup-plugin-polyfill-3.0.0.tgz",
- "integrity": "sha512-LfJ1OR/wJrJdNDVNrdhVm7CgENfaNoQlFYMaQ0vlQH3zO+BMVrBMWDX9k6HVcr9gHsKbthrkiBzWRfFU9fr0hQ==",
- "dev": true,
- "requires": {
- "magic-string": "^0.25.3"
- }
- },
"rollup-plugin-terser": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/rollup-plugin-terser/-/rollup-plugin-terser-5.3.0.tgz", | true |
Other | chartjs | Chart.js | 319a6a40b995d94acd048939ca47e75e9ba46dce.json | Use @rollup/plugin-inject for ResizeObserver poly (#7360) | package.json | @@ -38,6 +38,7 @@
"@babel/plugin-transform-object-assign": "^7.8.3",
"@babel/preset-env": "^7.9.6",
"@rollup/plugin-commonjs": "^11.1.0",
+ "@rollup/plugin-inject": "^4.0.2",
"@rollup/plugin-json": "^4.0.3",
"@rollup/plugin-node-resolve": "^7.1.3",
"babel-plugin-istanbul": "^6.0.0",
@@ -75,7 +76,6 @@
"rollup": "^2.7.6",
"rollup-plugin-babel": "^4.4.0",
"rollup-plugin-cleanup": "^3.1.1",
- "rollup-plugin-polyfill": "^3.0.0",
"rollup-plugin-terser": "^5.3.0",
"rollup-plugin-web-worker-loader": "^1.2.0",
"typedoc": "^0.17.6", | true |
Other | chartjs | Chart.js | 319a6a40b995d94acd048939ca47e75e9ba46dce.json | Use @rollup/plugin-inject for ResizeObserver poly (#7360) | rollup.config.js | @@ -3,7 +3,7 @@
const babel = require('rollup-plugin-babel');
const cleanup = require('rollup-plugin-cleanup');
-const polyfill = require('rollup-plugin-polyfill');
+const inject = require('@rollup/plugin-inject');
const json = require('@rollup/plugin-json');
const resolve = require('@rollup/plugin-node-resolve');
const terser = require('rollup-plugin-terser').terser;
@@ -25,7 +25,9 @@ module.exports = [
{
input,
plugins: [
- polyfill(['resize-observer-polyfill', './platform/platform.dom.js']),
+ inject({
+ ResizeObserver: 'resize-observer-polyfill'
+ }),
json(),
resolve(),
babel(),
@@ -44,7 +46,9 @@ module.exports = [
{
input,
plugins: [
- polyfill(['resize-observer-polyfill', './platform/platform.dom.js']),
+ inject({
+ ResizeObserver: 'resize-observer-polyfill'
+ }),
json(),
resolve(),
babel(), | true |
Other | chartjs | Chart.js | a301ca148c4536793a740e7d263e74bc258ed25b.json | Add a scale.init method (#7346) | src/core/core.controller.js | @@ -403,9 +403,6 @@ export default class Chart {
let scale = null;
if (id in scales && scales[id].type === scaleType) {
scale = scales[id];
- scale.options = scaleOptions;
- scale.ctx = me.ctx;
- scale.chart = me;
} else {
const scaleClass = scaleService.getScaleConstructor(scaleType);
if (!scaleClass) {
@@ -414,18 +411,13 @@ export default class Chart {
scale = new scaleClass({
id,
type: scaleType,
- options: scaleOptions,
ctx: me.ctx,
chart: me
});
scales[scale.id] = scale;
}
- scale.axis = scale.options.position === 'chartArea' ? 'r' : scale.isHorizontal() ? 'x' : 'y';
-
- // parse min/max value, so we can properly determine min/max for other scales
- scale._userMin = scale.parse(scale.options.min);
- scale._userMax = scale.parse(scale.options.max);
+ scale.init(scaleOptions);
// TODO(SB): I think we should be able to remove this custom case (options.scale)
// and consider it as a regular scale part of the "scales"" map only! This would | true |
Other | chartjs | Chart.js | a301ca148c4536793a740e7d263e74bc258ed25b.json | Add a scale.init method (#7346) | src/core/core.scale.js | @@ -278,7 +278,7 @@ export default class Scale extends Element {
/** @type {string} */
this.type = cfg.type;
/** @type {object} */
- this.options = cfg.options;
+ this.options = undefined;
/** @type {CanvasRenderingContext2D} */
this.ctx = cfg.ctx;
/** @type {Chart} */
@@ -344,10 +344,25 @@ export default class Scale extends Element {
this._borderValue = 0;
}
+ /**
+ * @param {object} options
+ * @since 3.0
+ */
+ init(options) {
+ const me = this;
+ me.options = options;
+
+ me.axis = me.isHorizontal() ? 'x' : 'y';
+
+ // parse min/max value, so we can properly determine min/max for other scales
+ me._userMin = me.parse(options.min);
+ me._userMax = me.parse(options.max);
+ }
+
/**
* Parse a supported input value to internal representation.
* @param {*} raw
- * @param {number} index
+ * @param {number} [index]
* @since 3.0
*/
parse(raw, index) { // eslint-disable-line no-unused-vars | true |
Other | chartjs | Chart.js | a301ca148c4536793a740e7d263e74bc258ed25b.json | Add a scale.init method (#7346) | src/scales/scale.radialLinear.js | @@ -309,6 +309,11 @@ export default class RadialLinearScale extends LinearScaleBase {
this.pointLabels = [];
}
+ init(options) {
+ super.init(options);
+ this.axis = 'r';
+ }
+
setDimensions() {
const me = this;
| true |
Other | chartjs | Chart.js | a301ca148c4536793a740e7d263e74bc258ed25b.json | Add a scale.init method (#7346) | src/scales/scale.time.js | @@ -555,10 +555,6 @@ export default class TimeScale extends Scale {
constructor(props) {
super(props);
- const options = this.options;
- const time = options.time || (options.time = {});
- const adapter = this._adapter = new adapters._date(options.adapters.date);
-
/** @type {{data: number[], labels: number[], all: number[]}} */
this._cache = {
data: [],
@@ -574,12 +570,19 @@ export default class TimeScale extends Scale {
this._offsets = {};
/** @type {object[]} */
this._table = [];
+ }
+
+ init(options) {
+ const time = options.time || (options.time = {});
+ const adapter = this._adapter = new adapters._date(options.adapters.date);
// Backward compatibility: before introducing adapter, `displayFormats` was
// supposed to contain *all* unit/string pairs but this can't be resolved
// when loading the scale (adapters are loaded afterward), so let's populate
// missing formats on update
mergeIf(time.displayFormats, adapter.formats());
+
+ super.init(options);
}
/** | true |
Other | chartjs | Chart.js | a301ca148c4536793a740e7d263e74bc258ed25b.json | Add a scale.init method (#7346) | test/specs/scale.category.tests.js | @@ -76,13 +76,13 @@ describe('Category scale tests', function() {
var Constructor = Chart.scaleService.getScaleConstructor('category');
var scale = new Constructor({
ctx: {},
- options: config,
chart: {
data: mockData
},
id: scaleID
});
+ scale.init(config);
scale.determineDataLimits();
scale.ticks = scale.buildTicks();
expect(getValues(scale)).toEqual(mockData.xLabels);
@@ -104,13 +104,13 @@ describe('Category scale tests', function() {
var Constructor = Chart.scaleService.getScaleConstructor('category');
var scale = new Constructor({
ctx: {},
- options: config,
chart: {
data: mockData
},
id: scaleID
});
+ scale.init(config);
scale.determineDataLimits();
scale.ticks = scale.buildTicks();
expect(getValues(scale)).toEqual(mockData.yLabels); | true |
Other | chartjs | Chart.js | a94e1e175c5d5551a89c60835e3a91f569dc10b7.json | Add Algolia to docs (#7329) | docs/docusaurus.config.js | @@ -10,6 +10,13 @@ module.exports = {
plugins: ['@docusaurus/plugin-google-analytics'],
scripts: ['https://www.chartjs.org/dist/VERSION/Chart.min.js'],
themeConfig: {
+ algolia: {
+ apiKey: 'd7ee00a3cbaaf3c33e28ad1c274e7ba6',
+ indexName: 'chartjs',
+ algoliaOptions: {
+ facetFilters: [`version:VERSION`],
+ }
+ },
googleAnalytics: {
trackingID: 'UA-28909194-3',
// Optional fields. | false |
Other | chartjs | Chart.js | 3a25fe29213cbe3f386988609699aab703f856cb.json | Document the removal of deprecated properties (#7334) | docs/docs/getting-started/v3-migration.md | @@ -173,15 +173,27 @@ The following properties and methods were removed:
#### Chart
* `Chart.borderWidth`
* `Chart.chart.chart`
+* `Chart.Bar`. New charts are created via `new Chart` and providing the appropriate `type` parameter
+* `Chart.Bubble`. New charts are created via `new Chart` and providing the appropriate `type` parameter
+* `Chart.Chart`
* `Chart.Controller`
+* `Chart.Doughnut`. New charts are created via `new Chart` and providing the appropriate `type` parameter
* `Chart.innerRadius` now lives on doughnut, pie, and polarArea controllers
+* `Chart.Legend` was moved to `Chart.plugins.legend._element` and made private
+* `Chart.Line`. New charts are created via `new Chart` and providing the appropriate `type` parameter
+* `Chart.LinearScaleBase` now must be imported and cannot be accessed off the `Chart` object
* `Chart.offsetX`
* `Chart.offsetY`
* `Chart.outerRadius` now lives on doughnut, pie, and polarArea controllers
+* `Chart.PolarArea`. New charts are created via `new Chart` and providing the appropriate `type` parameter
* `Chart.prototype.generateLegend`
* `Chart.platform`. It only contained `disableCSSInjection`. CSS is never injected in v3.
+* `Chart.PluginBase`
+* `Chart.Radar`. New charts are created via `new Chart` and providing the appropriate `type` parameter
* `Chart.radiusLength`
+* `Chart.Scatter`. New charts are created via `new Chart` and providing the appropriate `type` parameter
* `Chart.types`
+* `Chart.Title` was moved to `Chart.plugins.title._element` and made private
* `Chart.Tooltip` is now provided by the tooltip plugin. The positioners can be accessed from `tooltipPlugin.positioners`
* `ILayoutItem.minSize`
@@ -267,6 +279,9 @@ The following properties were renamed during v3 development:
* `Chart.Animation.animationObject` was renamed to `Chart.Animation`
* `Chart.Animation.chartInstance` was renamed to `Chart.Animation.chart`
+* `Chart.canvasHelpers` was renamed to `Chart.helpers.canvas`
+* `Chart.layoutService` was renamed to `Chart.layouts`
+* `Chart.pluginService` was renamed to `Chart.plugins`
* `helpers._decimalPlaces` was renamed to `helpers.math._decimalPlaces`
* `helpers.almostEquals` was renamed to `helpers.math.almostEquals`
* `helpers.almostWhole` was renamed to `helpers.math.almostWhole` | false |
Other | chartjs | Chart.js | 00f726b0eaeeaad177ded228a00cb4c4e0c9e529.json | Update the contributing guide for Docusaurus (#7327) | docs/docs/developers/contributing.md | @@ -39,12 +39,20 @@ The following commands are now available from the repository root:
> gulp lint // perform code linting (ESLint)
> gulp test // perform code linting and run unit tests
> gulp test --browsers ... // test with specified browsers (comma-separated)
-> gulp docs // build the documentation in ./dist/docs
-> gulp docs --watch // starts the gitbook live reloaded server
```
More information can be found in [gulpfile.js](https://github.com/chartjs/Chart.js/blob/master/gulpfile.js).
+### Documentation
+
+We use [Docusaurus v2](https://v2.docusaurus.io/docs/introduction) to manage the docs which are contained as Markdown files in the docs directory. You can run the doc server locally using the commands provided by Docusaurus:
+
+```
+$ cd docs
+$ npm install
+$ npm run start
+```
+
### Image-Based Tests
Some display-related functionality is difficult to test via typical Jasmine units. For this reason, we introduced image-based tests ([#3988](https://github.com/chartjs/Chart.js/pull/3988) and [#5777](https://github.com/chartjs/Chart.js/pull/5777)) to assert that a chart is drawn pixel-for-pixel matching an expected image. | false |
Other | chartjs | Chart.js | 6bbbbe42ce4f80db4cebba5a3eafc5d42643837d.json | Remove old docs from gitignore (#7314) | .gitignore | @@ -1,26 +1,28 @@
+# Deployment
/coverage
/custom
/dist
-/docs/index.md
/gh-pages
-/jsdoc
-.idea
-.project
-.settings
-.vscode
-*.log
-*.swp
-*.stackdump
-build
-node_modules
+# Node.js
+node_modules/
npm-debug.log*
+# Docs
.docusaurus
.cache-loader
+build/
+# Development
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
+.idea
+.project
+.settings
+.vscode
+*.log
+*.swp
+*.stackdump | false |
Other | chartjs | Chart.js | 1228981e4f62d9a9d3f8cf3b90ef9138ebba7983.json | Fix couple of small issues (#7268) | rollup.config.js | @@ -3,7 +3,7 @@
const babel = require('rollup-plugin-babel');
const cleanup = require('rollup-plugin-cleanup');
-const polyfill = require('rollup-plugin-polyfill')
+const polyfill = require('rollup-plugin-polyfill');
const json = require('@rollup/plugin-json');
const resolve = require('@rollup/plugin-node-resolve');
const terser = require('rollup-plugin-terser').terser; | true |
Other | chartjs | Chart.js | 1228981e4f62d9a9d3f8cf3b90ef9138ebba7983.json | Fix couple of small issues (#7268) | src/elements/element.rectangle.js | @@ -176,7 +176,7 @@ export default class Rectangle extends Element {
}
getCenterPoint(useFinalPosition) {
- const {x, y, base, horizontal} = this.getProps(['x', 'y', 'base', 'horizontal', useFinalPosition]);
+ const {x, y, base, horizontal} = this.getProps(['x', 'y', 'base', 'horizontal'], useFinalPosition);
return {
x: horizontal ? (x + base) / 2 : x,
y: horizontal ? y : (y + base) / 2 | true |
Other | chartjs | Chart.js | 1228981e4f62d9a9d3f8cf3b90ef9138ebba7983.json | Fix couple of small issues (#7268) | src/plugins/plugin.tooltip.js | @@ -45,7 +45,7 @@ defaults.set('tooltips', {
easing: 'easeOutQuart',
numbers: {
type: 'number',
- properties: ['x', 'y', 'width', 'height'],
+ properties: ['x', 'y', 'width', 'height', 'caretX', 'caretY'],
},
opacity: {
easing: 'linear', | true |
Other | chartjs | Chart.js | 14021d369a0eca3b9a669dd317839a909040b81f.json | Remove unused layouts.defaults (#7264)
* Remove unused layouts.defaults
* Add to migration guide | docs/getting-started/v3-migration.md | @@ -221,6 +221,10 @@ The following properties and methods were removed:
* `helpers.scaleMerge`
* `helpers.where`
+#### Layout
+
+* `Layout.defaults`
+
#### Scales
* `LogarithmicScale.minNotZero` | true |
Other | chartjs | Chart.js | 14021d369a0eca3b9a669dd317839a909040b81f.json | Remove unused layouts.defaults (#7264)
* Remove unused layouts.defaults
* Add to migration guide | src/core/core.layouts.js | @@ -230,7 +230,6 @@ defaults.set('layout', {
// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
// It is this service's responsibility of carrying out that layout.
export default {
- defaults: {},
/**
* Register a box to a chart. | true |
Other | chartjs | Chart.js | 14021d369a0eca3b9a669dd317839a909040b81f.json | Remove unused layouts.defaults (#7264)
* Remove unused layouts.defaults
* Add to migration guide | test/specs/core.layouts.tests.js | @@ -6,7 +6,6 @@ describe('Chart.layouts', function() {
it('should be exposed through Chart.layouts', function() {
expect(Chart.layouts).toBeDefined();
expect(typeof Chart.layouts).toBe('object');
- expect(Chart.layouts.defaults).toBeDefined();
expect(Chart.layouts.addBox).toBeDefined();
expect(Chart.layouts.removeBox).toBeDefined();
expect(Chart.layouts.configure).toBeDefined(); | true |
Other | chartjs | Chart.js | 5129e1aaf7800e1a816b4638cde3326af684eb31.json | update introduction documentation #7245 (#7247) | docs/README.md | @@ -54,7 +54,7 @@ var myChart = new Chart(ctx, {
## Contributing
-Before submitting an issue or a pull request to the project, please take a moment to look over the [contributing guidelines](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md) first.
+Before submitting an issue or a pull request to the project, please take a moment to look over the [contributing guidelines](./developers/contributing.md) first.
For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](https://stackoverflow.com/questions/tagged/chartjs).
| false |
Other | chartjs | Chart.js | 3f58edbe800aacb9fc943a19af700e1cc8c439d4.json | Remove unused method parameter (#7229) | src/core/core.scale.js | @@ -175,10 +175,9 @@ function getEvenSpacing(arr) {
/**
* @param {number[]} majorIndices
* @param {Tick[]} ticks
- * @param {number} axisLength
* @param {number} ticksLimit
*/
-function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
+function calculateSpacing(majorIndices, ticks, ticksLimit) {
const evenMajorSpacing = getEvenSpacing(majorIndices);
const spacing = ticks.length / ticksLimit;
@@ -1021,8 +1020,7 @@ export default class Scale extends Element {
_autoSkip(ticks) {
const me = this;
const tickOpts = me.options.ticks;
- const axisLength = me._length;
- const ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize();
+ const ticksLimit = tickOpts.maxTicksLimit || me._length / me._tickSize();
const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
const numMajorIndices = majorIndices.length;
const first = majorIndices[0];
@@ -1035,7 +1033,7 @@ export default class Scale extends Element {
return newTicks;
}
- const spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit);
+ const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);
if (numMajorIndices > 0) {
let i, ilen; | false |
Other | chartjs | Chart.js | 8b01ab1326be8dead099cdb494e2efdc46ff4dbf.json | Use round when setting new chart size (#7221) | src/core/core.controller.js | @@ -313,8 +313,8 @@ export default class Chart {
// the canvas display style uses the same integer values to avoid blurring effect.
// Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
- const newWidth = Math.max(0, Math.floor(width));
- const newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : height));
+ const newWidth = Math.max(0, Math.round(width));
+ const newHeight = Math.max(0, Math.round(aspectRatio ? newWidth / aspectRatio : height));
// detect devicePixelRation changes
const oldRatio = me.currentDevicePixelRatio; | false |
Other | chartjs | Chart.js | 60858547ac8e391a845d8b304914b84a5d948d86.json | Fix events in shadow dom (#7224) | src/helpers/helpers.dom.js | @@ -86,7 +86,7 @@ function _calculatePadding(container, padding, parentDimension) {
export function getRelativePosition(evt, chart) {
let mouseX, mouseY;
const e = evt.originalEvent || evt;
- const canvasElement = evt.target || evt.srcElement;
+ const canvasElement = chart.canvas;
const boundingRect = canvasElement.getBoundingClientRect();
const touches = e.touches; | false |
Other | chartjs | Chart.js | e8f2a5a27108d103cea18aad4aa835a7068d8499.json | Remove index override, (#9469)
Make barchart more inline with v2 behaviour and other charts | src/controllers/controller.bar.js | @@ -634,10 +634,6 @@ BarController.defaults = {
* @type {any}
*/
BarController.overrides = {
- interaction: {
- mode: 'index'
- },
-
scales: {
_index_: {
type: 'category', | false |
Other | chartjs | Chart.js | 2400fcb432d4bce68abfbe54cbc9cc8c930c381f.json | Adjust text to code example (#9475)
The previous text explains that, in the example, the font color is set and overridden but the code sets and overrides the _font size_. | docs/general/fonts.md | @@ -2,7 +2,7 @@
There are special global settings that can change all of the fonts on the chart. These options are in `Chart.defaults.font`. The global font settings only apply when more specific options are not included in the config.
-For example, in this chart the text will all be red except for the labels in the legend.
+For example, in this chart the text will have a font size of 16px except for the labels in the legend.
```javascript
Chart.defaults.font.size = 16; | false |
Other | chartjs | Chart.js | df4944786709fb2b3a9038e6676f5491d9243a14.json | Limit Math.asin inputs to the range [-1, 1] (#9410) | src/core/core.scale.js | @@ -593,8 +593,8 @@ export default class Scale extends Element {
- tickOpts.padding - getTitleHeight(options.title, me.chart.options.font);
maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
labelRotation = toDegrees(Math.min(
- Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
- Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
+ Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)),
+ Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))
));
labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
} | false |
Other | chartjs | Chart.js | f315daf5cfc443b3bab32510c5d34079691ba288.json | Add missing resizeDelay option to types (#9403)
This option is defined in the documentation (https://www.chartjs.org/docs/master/configuration/responsive.html) and the native js code, but not listed in the types. This allows its use in typescript. | types/index.esm.d.ts | @@ -1412,6 +1412,11 @@ export interface CoreChartOptions<TType extends ChartType> extends ParsingOption
* @default true
*/
maintainAspectRatio: boolean;
+ /**
+ * Delay the resize update by give amount of milliseconds. This can ease the resize process by debouncing update of the elements.
+ * @default 0
+ */
+ resizeDelay: number;
/**
* Canvas aspect ratio (i.e. width / height, a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style. | false |
Other | chartjs | Chart.js | 655c635191328f5e4d0ddf2adb9ff46d0760f301.json | Add SubTitle to the list of all esm imports (#9384) | docs/getting-started/integration.md | @@ -49,7 +49,8 @@ import {
Filler,
Legend,
Title,
- Tooltip
+ Tooltip,
+ SubTitle
} from 'chart.js';
Chart.register(
@@ -75,7 +76,8 @@ Chart.register(
Filler,
Legend,
Title,
- Tooltip
+ Tooltip,
+ SubTitle
);
var myChart = new Chart(ctx, {...}); | false |
Other | chartjs | Chart.js | d661bd788b51ae6a5444d3148f15e94af3e72e68.json | Resolve warnings from typings (#9363) | types/adapters.d.ts | @@ -3,7 +3,7 @@ export type TimeUnit = 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'w
export interface DateAdapter {
// Override one or multiple of the methods to adjust to the logic of the current date library.
override(members: Partial<DateAdapter>): void;
- readonly options: any;
+ readonly options: unknown;
/**
* Returns a map of time formats for the supported formatting units defined
@@ -13,10 +13,10 @@ export interface DateAdapter {
formats(): { [key: string]: string };
/**
* Parses the given `value` and return the associated timestamp.
- * @param {any} value - the value to parse (usually comes from the data)
+ * @param {unknown} value - the value to parse (usually comes from the data)
* @param {string} [format] - the expected data format
*/
- parse(value: any, format?: TimeUnit): number | null;
+ parse(value: unknown, format?: TimeUnit): number | null;
/**
* Returns the formatted date in the specified `format` for a given `timestamp`.
* @param {number} timestamp - the timestamp to format | true |
Other | chartjs | Chart.js | d661bd788b51ae6a5444d3148f15e94af3e72e68.json | Resolve warnings from typings (#9363) | types/element.d.ts | @@ -1,30 +1,17 @@
+import { AnyObject } from './basic';
import { Point } from './geometric';
-export interface Element<T = {}, O = {}> {
+export interface Element<T = AnyObject, O = AnyObject> {
readonly x: number;
readonly y: number;
readonly active: boolean;
readonly options: O;
tooltipPosition(useFinalPosition?: boolean): Point;
hasValue(): boolean;
- getProps<P extends keyof T>(props: [P], final?: boolean): Pick<T, P>;
- getProps<P extends keyof T, P2 extends keyof T>(props: [P, P2], final?: boolean): Pick<T, P | P2>;
- getProps<P extends keyof T, P2 extends keyof T, P3 extends keyof T>(
- props: [P, P2, P3],
- final?: boolean
- ): Pick<T, P | P2 | P3>;
- getProps<P extends keyof T, P2 extends keyof T, P3 extends keyof T, P4 extends keyof T>(
- props: [P, P2, P3, P4],
- final?: boolean
- ): Pick<T, P | P2 | P3 | P4>;
- getProps<P extends keyof T, P2 extends keyof T, P3 extends keyof T, P4 extends keyof T, P5 extends keyof T>(
- props: [P, P2, P3, P4, P5],
- final?: boolean
- ): Pick<T, P | P2 | P3 | P4 | P5>;
- getProps(props: (keyof T)[], final?: boolean): T;
+ getProps<P extends (keyof T)[]>(props: P, final?: boolean): Pick<T, P[number]>;
}
export const Element: {
prototype: Element;
- new <T = {}, O = {}>(): Element<T, O>;
+ new <T = AnyObject, O = AnyObject>(): Element<T, O>;
}; | true |
Other | chartjs | Chart.js | d661bd788b51ae6a5444d3148f15e94af3e72e68.json | Resolve warnings from typings (#9363) | types/helpers/helpers.color.d.ts | @@ -1,5 +1,12 @@
export function color(value: CanvasGradient): CanvasGradient;
export function color(value: CanvasPattern): CanvasPattern;
+export function color(
+ value:
+ | string
+ | { r: number; g: number; b: number; a: number }
+ | [number, number, number]
+ | [number, number, number, number]
+): ColorModel;
export interface ColorModel {
rgbString(): string;
@@ -20,13 +27,6 @@ export interface ColorModel {
desaturate(ratio: number): ColorModel;
rotate(deg: number): this;
}
-export function color(
- value:
- | string
- | { r: number; g: number; b: number; a: number }
- | [number, number, number]
- | [number, number, number, number]
-): ColorModel;
export function getHoverColor(value: CanvasGradient): CanvasGradient;
export function getHoverColor(value: CanvasPattern): CanvasPattern; | true |
Other | chartjs | Chart.js | d661bd788b51ae6a5444d3148f15e94af3e72e68.json | Resolve warnings from typings (#9363) | types/helpers/helpers.extras.d.ts | @@ -12,7 +12,7 @@ export function requestAnimFrame(cb: () => void): void;
* @param {*} thisArg
* @param {function} [updateFn]
*/
-export function throttled(fn: (...args: any[]) => void, thisArg: any, updateFn?: (...args: any[]) => any[]): (...args: any[]) => void;
+export function throttled(fn: (...args: unknown[]) => void, thisArg: unknown, updateFn?: (...args: unknown[]) => unknown[]): (...args: unknown[]) => void;
/**
* Debounces calling `fn` for `delay` ms | true |
Other | chartjs | Chart.js | d661bd788b51ae6a5444d3148f15e94af3e72e68.json | Resolve warnings from typings (#9363) | types/helpers/helpers.math.d.ts | @@ -1,5 +1,5 @@
export function log10(x: number): number;
-export function isNumber(v: any): boolean;
+export function isNumber(v: unknown): boolean;
export function almostEquals(x: number, y: number, epsilon: number): boolean;
export function almostWhole(x: number, epsilon: number): number;
export function sign(x: number): number; | true |
Other | chartjs | Chart.js | d661bd788b51ae6a5444d3148f15e94af3e72e68.json | Resolve warnings from typings (#9363) | types/index.esm.d.ts | @@ -1156,7 +1156,7 @@ export interface CoreScaleOptions {
afterUpdate(axis: Scale): void;
}
-export interface Scale<O extends CoreScaleOptions = CoreScaleOptions> extends Element<{}, O>, LayoutItem {
+export interface Scale<O extends CoreScaleOptions = CoreScaleOptions> extends Element<unknown, O>, LayoutItem {
readonly id: string;
readonly type: string;
readonly ctx: CanvasRenderingContext2D;
@@ -1680,7 +1680,9 @@ export const ArcElement: ChartComponent & {
new (cfg: AnyObject): ArcElement;
};
-export interface LineProps {}
+export interface LineProps {
+ points: Point[]
+}
export interface LineOptions extends CommonElementOptions {
/** | true |
Other | chartjs | Chart.js | d661bd788b51ae6a5444d3148f15e94af3e72e68.json | Resolve warnings from typings (#9363) | types/utils.d.ts | @@ -1,3 +1,4 @@
+/* eslint-disable @typescript-eslint/ban-types */
// DeepPartial implementation taken from the utility-types NPM package, which is
// Copyright (c) 2016 Piotr Witek <piotrek.witek@gmail.com> (http://piotrwitek.github.io)
@@ -9,10 +10,11 @@ export type DeepPartial<T> = T extends Function
: T extends object
? _DeepPartialObject<T>
: T | undefined;
- type _DeepPartialArray<T> = Array<DeepPartial<T>>
+
+type _DeepPartialArray<T> = Array<DeepPartial<T>>
type _DeepPartialObject<T> = { [P in keyof T]?: DeepPartial<T[P]> };
export type DistributiveArray<T> = [T] extends [unknown] ? Array<T> : never
// From https://stackoverflow.com/a/50375286
-export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
+export type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; | true |
Other | chartjs | Chart.js | 124581a679fa9e048defedc245c7f41ac90c448a.json | Add type tests for float bar / object data arrays (#9348) | types/tests/data_types.ts | @@ -0,0 +1,20 @@
+import { Chart } from '../index.esm';
+
+const chart = new Chart('chart', {
+ type: 'bar',
+ data: {
+ labels: ['1', '2', '3'],
+ datasets: [{ data: [[1, 2], [1, 2], [1, 2]] }],
+ }
+});
+
+const chart2 = new Chart('chart2', {
+ type: 'bar',
+ data: {
+ datasets: [{
+ data: [{ id: 'Sales', nested: { value: 1500 } }, { id: 'Purchases', nested: { value: 500 } }],
+ }],
+ },
+ options: { parsing: { xAxisKey: 'id', yAxisKey: 'nested.value' },
+ },
+}); | false |
Other | chartjs | Chart.js | 760fcff6fa7c9228fbaa58a5dcefaa287f5c0381.json | Fix typing of the isoWeekday field (#9330) | types/index.esm.d.ts | @@ -3025,7 +3025,7 @@ export type TimeScaleOptions = CartesianScaleOptions & {
* If `number`, the index of the first day of the week (0 - Sunday, 6 - Saturday).
* @default false
*/
- isoWeekday: false | number;
+ isoWeekday: boolean | number;
/**
* Sets how different time units are displayed.
*/ | false |
Other | chartjs | Chart.js | e5dee9f88e021cfe11ebced3ddb013ed5c6d679a.json | Fix comma causing Terser issue (#9326) | src/scales/scale.linearbase.js | @@ -98,7 +98,7 @@ function generateTicks(generationOptions, dataRange) {
// until this point
const decimalPlaces = Math.max(
_decimalPlaces(spacing),
- _decimalPlaces(niceMin),
+ _decimalPlaces(niceMin)
);
factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision);
niceMin = Math.round(niceMin * factor) / factor; | false |
Other | chartjs | Chart.js | 3bb0241dee98ead81e350a39e32a35656bd5665d.json | Fix broken link (#9315) | docs/charts/scatter.md | @@ -56,7 +56,7 @@ Namespaces:
* `options.elements.point` - options for all [point elements](../configuration/elements.md#point-configuration)
* `options` - options for the whole chart
-The scatter chart supports all of the same properties as the [line chart](./charts/line.md#dataset-properties).
+The scatter chart supports all of the same properties as the [line chart](./line.md#dataset-properties).
By default, the scatter chart will override the showLine property of the line chart to `false`.
The index scale is of the type `linear`. This means if you are using the labels array the values have to be numbers or parsable to numbers, the same applies to the object format for the keys. | false |
Other | chartjs | Chart.js | ed73dce18bd5a2d523409d1fcaadaf2bcdd1d89c.json | Docs: describe catching events with plugin (#9296) | docs/configuration/interactions.md | @@ -56,6 +56,30 @@ var chart = new Chart(ctx, {
});
```
+Events that do not fire over chartArea, like `mouseout`, can be captured using a simple plugin:
+
+```javascript
+var chart = new Chart(ctx, {
+ type: 'line',
+ data: data,
+ options: {
+ // these are the default events:
+ // events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
+ },
+ plugins: [{
+ id: 'myEventCatcher',
+ beforeEvent(chart, args, pluginOptions) {
+ const event = args.event;
+ if (event.type === 'mouseout') {
+ // process the event
+ }
+ }
+ }]
+});
+```
+
+For more information about plugins, see [Plugins](../developers/plugins.md)
+
### Converting Events to Data Values
A common occurrence is taking an event, such as a click, and finding the data coordinates on the chart where the event occurred. Chart.js provides helpers that make this a straightforward process. | false |
Other | chartjs | Chart.js | 2768c7dea7b7934fc464f551ac50bdec13574bb0.json | Fix type definitions for `getPixelForValue` (#9263)
Update docs: From what I can tell, the `index` parameter was re-introduced as part of the new `normalized` option. | docs/developers/axes.md | @@ -90,9 +90,8 @@ To work with Chart.js, custom scale types must implement the following interface
// Get the pixel (x coordinate for horizontal axis, y coordinate for vertical axis) for a given value
// @param value : the value to get the pixel for
- // @param index : index into the data array of the value
- // @param datasetIndex : index of the dataset the value comes from
- getPixelForValue: function(value, index, datasetIndex) {},
+ // @param [index] : index into the data array of the value
+ getPixelForValue: function(value, index) {},
// Get the value for a given pixel (x coordinate for horizontal axis, y coordinate for vertical axis)
// @param pixel : pixel value | true |
Other | chartjs | Chart.js | 2768c7dea7b7934fc464f551ac50bdec13574bb0.json | Fix type definitions for `getPixelForValue` (#9263)
Update docs: From what I can tell, the `index` parameter was re-introduced as part of the new `normalized` option. | docs/getting-started/v3-migration.md | @@ -467,7 +467,7 @@ The APIs listed in this section have changed in signature or behaviour from vers
#### Changed in Scales
* `Scale.getLabelForIndex` was replaced by `scale.getLabelForValue`
-* `Scale.getPixelForValue` now has only one parameter. For the `TimeScale` that parameter must be millis since the epoch
+* `Scale.getPixelForValue` now only requires one parameter. For the `TimeScale` that parameter must be millis since the epoch. As a performance optimization, it may take an optional second parameter, giving the index of the data point.
##### Changed in Ticks
| true |
Other | chartjs | Chart.js | 2768c7dea7b7934fc464f551ac50bdec13574bb0.json | Fix type definitions for `getPixelForValue` (#9263)
Update docs: From what I can tell, the `index` parameter was re-introduced as part of the new `normalized` option. | types/index.esm.d.ts | @@ -1219,7 +1219,7 @@ export interface Scale<O extends CoreScaleOptions = CoreScaleOptions> extends El
* @param {number} [index]
* @return {number}
*/
- getPixelForValue(value: number, index: number): number;
+ getPixelForValue(value: number, index?: number): number;
/**
* Used to get the data value from a given pixel. This is the inverse of getPixelForValue | true |
Other | chartjs | Chart.js | 54da5341f19c6b551a38d65f2e2835e372ec4dbb.json | Docs: Add copy button to code blocks (#9262) | docs/.vuepress/config.js | @@ -29,6 +29,7 @@ module.exports = {
{base: '/samples', alternative: ['bar/vertical']},
],
}],
+ ['vuepress-plugin-code-copy', true],
[
'vuepress-plugin-typedoc',
{ | true |
Other | chartjs | Chart.js | 54da5341f19c6b551a38d65f2e2835e372ec4dbb.json | Docs: Add copy button to code blocks (#9262) | package-lock.json | @@ -6,7 +6,7 @@
"packages": {
"": {
"name": "chart.js",
- "version": "3.3.0",
+ "version": "3.3.1",
"license": "MIT",
"devDependencies": {
"@kurkle/color": "^0.1.9",
@@ -57,6 +57,7 @@
"typescript": "~4.1.0",
"vue-tabs-component": "^1.5.0",
"vuepress": "^1.8.2",
+ "vuepress-plugin-code-copy": "^1.0.6",
"vuepress-plugin-flexsearch": "^0.1.0",
"vuepress-plugin-redirect": "^1.2.5",
"vuepress-plugin-tabs": "^0.3.0",
@@ -17417,6 +17418,12 @@
"object.getownpropertydescriptors": "^2.0.3"
}
},
+ "node_modules/vuepress-plugin-code-copy": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/vuepress-plugin-code-copy/-/vuepress-plugin-code-copy-1.0.6.tgz",
+ "integrity": "sha512-FiqwMtlb4rEsOI56O6sSkekcd3SlESxbkR2IaTIQxsMOMoalKfW5R9WlR1Pjm10v6jmU661Ex8MR11k9IzrNUg==",
+ "dev": true
+ },
"node_modules/vuepress-plugin-container": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/vuepress-plugin-container/-/vuepress-plugin-container-2.1.5.tgz",
@@ -33321,6 +33328,12 @@
}
}
},
+ "vuepress-plugin-code-copy": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/vuepress-plugin-code-copy/-/vuepress-plugin-code-copy-1.0.6.tgz",
+ "integrity": "sha512-FiqwMtlb4rEsOI56O6sSkekcd3SlESxbkR2IaTIQxsMOMoalKfW5R9WlR1Pjm10v6jmU661Ex8MR11k9IzrNUg==",
+ "dev": true
+ },
"vuepress-plugin-container": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/vuepress-plugin-container/-/vuepress-plugin-container-2.1.5.tgz", | true |
Other | chartjs | Chart.js | 54da5341f19c6b551a38d65f2e2835e372ec4dbb.json | Docs: Add copy button to code blocks (#9262) | package.json | @@ -97,6 +97,7 @@
"typescript": "~4.1.0",
"vue-tabs-component": "^1.5.0",
"vuepress": "^1.8.2",
+ "vuepress-plugin-code-copy": "^1.0.6",
"vuepress-plugin-flexsearch": "^0.1.0",
"vuepress-plugin-redirect": "^1.2.5",
"vuepress-plugin-tabs": "^0.3.0", | true |
Other | chartjs | Chart.js | 9c5a1aabce16d48721464c23452ca2d1b652ae27.json | Simplify financial sample (#7070) | samples/samples.js | @@ -157,6 +157,9 @@
}, {
title: 'Center Positioning',
path: 'scales/axis-center-position.html'
+ }, {
+ title: 'Custom major ticks',
+ path: 'scales/financial.html'
}]
}, {
title: 'Legend',
@@ -239,9 +242,6 @@
}, {
title: 'Advanced',
items: [{
- title: 'Custom minor and major ticks',
- path: 'advanced/financial.html'
- }, {
title: 'Progress bar',
path: 'advanced/progress-bar.html'
}, { | true |
Other | chartjs | Chart.js | 9c5a1aabce16d48721464c23452ca2d1b652ae27.json | Simplify financial sample (#7070) | samples/scales/financial.html | @@ -62,12 +62,17 @@
return date.hour() < 9 || (date.hour() === 9 && date.minute() < 30);
}
+
+ function after4pm(date) {
+ return date.hour() > 16 || (date.hour() === 16 && date.minute() > 0);
+ }
+
// Returns true if outside 9:30am-4pm on a weekday
function outsideMarketHours(date) {
if (date.isoWeekday() > 5) {
return true;
}
- if (unitLessThanDay() && (beforeNineThirty(date) || date.hour() > 16)) {
+ if (unitLessThanDay() && (beforeNineThirty(date) || after4pm(date))) {
return true;
}
return false;
@@ -140,69 +145,26 @@
fontStyle: function(context) {
return context.tick.major ? 'bold' : undefined;
},
- source: 'labels', // We provided no labels. Generate no ticks. We'll make our own
+ source: 'data',
autoSkip: true,
autoSkipPadding: 75,
maxRotation: 0,
sampleSize: 100
},
- // Custom logic that chooses ticks from dataset timestamp by choosing first timestamp in time period
+ // Custom logic that chooses major ticks by first timestamp in time period
+ // E.g. if March 1 & 2 are missing from dataset because they're weekends, we pick March 3 to be beginning of month
afterBuildTicks: function(scale) {
- // Determine units according to our own logic
- // Make sure there's at least 10 ticks generated. autoSkip will remove any extras
const units = ['second', 'minute', 'hour', 'day', 'month', 'year'];
- const duration = moment.duration(moment(scale.max).diff(scale.min));
const unit = document.getElementById('unit').value;
- let minorUnit = unit;
- for (let i = units.indexOf(minorUnit); i < units.length; i++) {
- const periods = duration.as(units[i]);
- if (periods < 10) {
- break;
- }
- minorUnit = units[i];
- }
let majorUnit;
- if (units.indexOf(minorUnit) !== units.length - 1) {
- majorUnit = units[units.indexOf(minorUnit) + 1];
- }
-
- // Generate ticks according to our own logic
- const data = scale.chart.data.datasets[0].data;
- const firstDate = moment(data[0].t);
-
- function findIndex(ts) {
- // Note that we could make this faster by doing a binary search
- // However, Chart.helpers.collection._lookup requires key and it's already pretty fast
- let result = -1;
- for (let i = 0; i < data.length; i++) {
- if (data[i].t >= ts) {
- result = i;
- break;
- }
- }
- if (result === 0) {
- return isFirstUnitOfPeriod(firstDate, unit, minorUnit) ? 0 : 1;
- }
- return result;
- }
-
- // minor ticks
- let start = moment(scale.min).startOf(minorUnit);
- const end = moment(scale.max);
- const values = new Set();
- for (let date = start; date.isBefore(end); date.add(1, minorUnit)) {
- const index = findIndex(+date);
- if (index !== -1) {
- values.add(data[index].t);
- }
+ if (units.indexOf(unit) !== units.length - 1) {
+ majorUnit = units[units.indexOf(unit) + 1];
}
- const ticks = Array.from(values, value => ({value}));
// major ticks
+ const ticks = scale.ticks;
for (let i = 0; i < ticks.length; i++) {
- if (!majorUnit || isFirstUnitOfPeriod(moment(ticks[i].value), unit, majorUnit)) {
- ticks[i].major = true;
- }
+ ticks[i].major = !majorUnit || isFirstUnitOfPeriod(moment(ticks[i].value), unit, majorUnit);
}
scale.ticks = ticks;
} | true |
Other | chartjs | Chart.js | 6affaa2a73429da1a1b990ff1c726dc317148931.json | Convert controllers to ES6 classes (#7061) | src/controllers/controller.bar.js | @@ -182,49 +182,36 @@ function isFloatBar(custom) {
return custom && custom.barStart !== undefined && custom.barEnd !== undefined;
}
-export default DatasetController.extend({
+class BarController extends DatasetController {
- dataElementType: Rectangle,
-
- /**
- * @private
- */
- _dataElementOptions: [
- 'backgroundColor',
- 'borderColor',
- 'borderSkipped',
- 'borderWidth',
- 'barPercentage',
- 'barThickness',
- 'categoryPercentage',
- 'maxBarThickness',
- 'minBarLength'
- ],
+ constructor(chart, datasetIndex) {
+ super(chart, datasetIndex);
+ }
/**
* Overriding primitive data parsing since we support mixed primitive/array
* data for float bars
* @private
*/
- _parsePrimitiveData: function() {
+ _parsePrimitiveData() {
return parseArrayOrPrimitive.apply(this, arguments);
- },
+ }
/**
* Overriding array data parsing since we support mixed primitive/array
* data for float bars
* @private
*/
- _parseArrayData: function() {
+ _parseArrayData() {
return parseArrayOrPrimitive.apply(this, arguments);
- },
+ }
/**
* Overriding object data parsing since we support mixed primitive/array
* value-scale data for float bars
* @private
*/
- _parseObjectData: function(meta, data, start, count) {
+ _parseObjectData(meta, data, start, count) {
const {iScale, vScale} = meta;
const vProp = vScale.axis;
const parsed = [];
@@ -242,12 +229,12 @@ export default DatasetController.extend({
parsed.push(item);
}
return parsed;
- },
+ }
/**
* @private
*/
- _getLabelAndValue: function(index) {
+ _getLabelAndValue(index) {
const me = this;
const meta = me._cachedMeta;
const {iScale, vScale} = meta;
@@ -261,9 +248,9 @@ export default DatasetController.extend({
label: '' + iScale.getLabelForValue(parsed[iScale.axis]),
value: value
};
- },
+ }
- initialize: function() {
+ initialize() {
var me = this;
var meta;
@@ -272,16 +259,16 @@ export default DatasetController.extend({
meta = me._cachedMeta;
meta.stack = me.getDataset().stack;
meta.bar = true;
- },
+ }
- update: function(mode) {
+ update(mode) {
const me = this;
const rects = me._cachedMeta.data;
me.updateElements(rects, 0, mode);
- },
+ }
- updateElements: function(rectangles, start, mode) {
+ updateElements(rectangles, start, mode) {
const me = this;
const reset = mode === 'reset';
const vscale = me._cachedMeta.vScale;
@@ -322,15 +309,15 @@ export default DatasetController.extend({
}
me._updateSharedOptions(sharedOptions, mode);
- },
+ }
/**
* Returns the stacks based on groups and bar visibility.
* @param {number} [last] - The dataset index
* @returns {string[]} The list of stack IDs
* @private
*/
- _getStacks: function(last) {
+ _getStacks(last) {
const me = this;
const meta = me._cachedMeta;
const iScale = meta.iScale;
@@ -364,15 +351,15 @@ export default DatasetController.extend({
}
return stacks;
- },
+ }
/**
* Returns the effective number of stacks based on groups and bar visibility.
* @private
*/
- getStackCount: function() {
+ getStackCount() {
return this._getStacks().length;
- },
+ }
/**
* Returns the stack index for the given dataset based on groups and bar visibility.
@@ -381,7 +368,7 @@ export default DatasetController.extend({
* @returns {number} The stack index
* @private
*/
- getStackIndex: function(datasetIndex, name) {
+ getStackIndex(datasetIndex, name) {
var stacks = this._getStacks(datasetIndex);
var index = (name !== undefined)
? stacks.indexOf(name)
@@ -390,12 +377,12 @@ export default DatasetController.extend({
return (index === -1)
? stacks.length - 1
: index;
- },
+ }
/**
* @private
*/
- getRuler: function() {
+ getRuler() {
const me = this;
const meta = me._cachedMeta;
const iScale = meta.iScale;
@@ -413,13 +400,13 @@ export default DatasetController.extend({
stackCount: me.getStackCount(),
scale: iScale
};
- },
+ }
/**
* Note: pixel values are not clamped to the scale area.
* @private
*/
- calculateBarValuePixels: function(index, options) {
+ calculateBarValuePixels(index, options) {
const me = this;
const meta = me._cachedMeta;
const vScale = meta.vScale;
@@ -468,12 +455,12 @@ export default DatasetController.extend({
head: head,
center: head + size / 2
};
- },
+ }
/**
* @private
*/
- calculateBarIndexPixels: function(index, ruler, options) {
+ calculateBarIndexPixels(index, ruler, options) {
var me = this;
var range = options.barThickness === 'flex'
? computeFlexCategoryTraits(index, ruler, options)
@@ -491,9 +478,9 @@ export default DatasetController.extend({
center: center,
size: size
};
- },
+ }
- draw: function() {
+ draw() {
const me = this;
const chart = me.chart;
const meta = me._cachedMeta;
@@ -513,4 +500,23 @@ export default DatasetController.extend({
unclipArea(chart.ctx);
}
-});
+}
+
+BarController.prototype.dataElementType = Rectangle;
+
+/**
+ * @private
+ */
+BarController.prototype._dataElementOptions = [
+ 'backgroundColor',
+ 'borderColor',
+ 'borderSkipped',
+ 'borderWidth',
+ 'barPercentage',
+ 'barThickness',
+ 'categoryPercentage',
+ 'maxBarThickness',
+ 'minBarLength'
+];
+
+export default BarController; | true |
Other | chartjs | Chart.js | 6affaa2a73429da1a1b990ff1c726dc317148931.json | Convert controllers to ES6 classes (#7061) | src/controllers/controller.bubble.js | @@ -33,30 +33,17 @@ defaults._set('bubble', {
}
});
-export default DatasetController.extend({
- /**
- * @protected
- */
- dataElementType: Point,
+class BubbleController extends DatasetController {
- /**
- * @private
- */
- _dataElementOptions: [
- 'backgroundColor',
- 'borderColor',
- 'borderWidth',
- 'hitRadius',
- 'radius',
- 'pointStyle',
- 'rotation'
- ],
+ constructor(chart, datasetIndex) {
+ super(chart, datasetIndex);
+ }
/**
* Parse array of objects
* @private
*/
- _parseObjectData: function(meta, data, start, count) {
+ _parseObjectData(meta, data, start, count) {
const {xScale, yScale} = meta;
const parsed = [];
let i, ilen, item;
@@ -69,12 +56,12 @@ export default DatasetController.extend({
});
}
return parsed;
- },
+ }
/**
* @private
*/
- _getMaxOverflow: function() {
+ _getMaxOverflow() {
const me = this;
const meta = me._cachedMeta;
let i = (meta.data || []).length - 1;
@@ -83,12 +70,12 @@ export default DatasetController.extend({
max = Math.max(max, me.getStyle(i, true).radius);
}
return max > 0 && max;
- },
+ }
/**
* @private
*/
- _getLabelAndValue: function(index) {
+ _getLabelAndValue(index) {
const me = this;
const meta = me._cachedMeta;
const {xScale, yScale} = meta;
@@ -101,23 +88,23 @@ export default DatasetController.extend({
label: meta.label,
value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'
};
- },
+ }
/**
* @protected
*/
- update: function(mode) {
+ update(mode) {
const me = this;
const points = me._cachedMeta.data;
// Update Points
me.updateElements(points, 0, mode);
- },
+ }
/**
* @protected
*/
- updateElements: function(points, start, mode) {
+ updateElements(points, start, mode) {
const me = this;
const reset = mode === 'reset';
const {xScale, yScale} = me._cachedMeta;
@@ -149,12 +136,12 @@ export default DatasetController.extend({
}
me._updateSharedOptions(sharedOptions, mode);
- },
+ }
/**
* @private
*/
- _resolveDataElementOptions: function(index, mode) {
+ _resolveDataElementOptions(index, mode) {
var me = this;
var chart = me.chart;
var dataset = me.getDataset();
@@ -187,4 +174,25 @@ export default DatasetController.extend({
return values;
}
-});
+}
+
+/**
+ * @protected
+ */
+BubbleController.prototype.dataElementType = Point;
+
+/**
+ * @private
+ */
+BubbleController.prototype._dataElementOptions = [
+ 'backgroundColor',
+ 'borderColor',
+ 'borderWidth',
+ 'hitRadius',
+ 'radius',
+ 'pointStyle',
+ 'rotation'
+];
+
+
+export default BubbleController; | true |
Other | chartjs | Chart.js | 6affaa2a73429da1a1b990ff1c726dc317148931.json | Convert controllers to ES6 classes (#7061) | src/controllers/controller.doughnut.js | @@ -3,7 +3,7 @@
import DatasetController from '../core/core.datasetController';
import defaults from '../core/core.defaults';
import Arc from '../elements/element.arc';
-import {isArray, noop, valueOrDefault} from '../helpers/helpers.core';
+import {isArray, valueOrDefault} from '../helpers/helpers.core';
const PI = Math.PI;
const DOUBLE_PI = PI * 2;
@@ -96,40 +96,29 @@ defaults._set('doughnut', {
}
});
-export default DatasetController.extend({
+class DoughnutController extends DatasetController {
- dataElementType: Arc,
-
- linkScales: noop,
+ constructor(chart, datasetIndex) {
+ super(chart, datasetIndex);
+ }
- /**
- * @private
- */
- _dataElementOptions: [
- 'backgroundColor',
- 'borderColor',
- 'borderWidth',
- 'borderAlign',
- 'hoverBackgroundColor',
- 'hoverBorderColor',
- 'hoverBorderWidth',
- ],
+ linkScales() {}
/**
* Override data parsing, since we are not using scales
* @private
*/
- _parse: function(start, count) {
+ _parse(start, count) {
var data = this.getDataset().data;
var meta = this._cachedMeta;
var i, ilen;
for (i = start, ilen = start + count; i < ilen; ++i) {
meta._parsed[i] = +data[i];
}
- },
+ }
// Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
- getRingIndex: function(datasetIndex) {
+ getRingIndex(datasetIndex) {
var ringIndex = 0;
for (var j = 0; j < datasetIndex; ++j) {
@@ -139,9 +128,9 @@ export default DatasetController.extend({
}
return ringIndex;
- },
+ }
- update: function(mode) {
+ update(mode) {
var me = this;
var chart = me.chart;
var chartArea = chart.chartArea;
@@ -199,19 +188,19 @@ export default DatasetController.extend({
me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
me.updateElements(arcs, 0, mode);
- },
+ }
/**
* @private
*/
- _circumference: function(i, reset) {
+ _circumference(i, reset) {
const me = this;
const opts = me.chart.options;
const meta = me._cachedMeta;
return reset && opts.animation.animateRotate ? 0 : meta.data[i].hidden ? 0 : me.calculateCircumference(meta._parsed[i] * opts.circumference / DOUBLE_PI);
- },
+ }
- updateElements: function(arcs, start, mode) {
+ updateElements(arcs, start, mode) {
const me = this;
const reset = mode === 'reset';
const chart = me.chart;
@@ -248,9 +237,9 @@ export default DatasetController.extend({
me._updateElement(arc, index, properties, mode);
}
- },
+ }
- calculateTotal: function() {
+ calculateTotal() {
const meta = this._cachedMeta;
const metaData = meta.data;
let total = 0;
@@ -268,18 +257,18 @@ export default DatasetController.extend({
}*/
return total;
- },
+ }
- calculateCircumference: function(value) {
+ calculateCircumference(value) {
var total = this._cachedMeta.total;
if (total > 0 && !isNaN(value)) {
return DOUBLE_PI * (Math.abs(value) / total);
}
return 0;
- },
+ }
// gets the max border or hover width to properly scale pie charts
- getMaxBorderWidth: function(arcs) {
+ getMaxBorderWidth(arcs) {
var me = this;
var max = 0;
var chart = me.chart;
@@ -311,13 +300,13 @@ export default DatasetController.extend({
}
}
return max;
- },
+ }
/**
* Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
* @private
*/
- _getRingWeightOffset: function(datasetIndex) {
+ _getRingWeightOffset(datasetIndex) {
var ringWeightOffset = 0;
for (var i = 0; i < datasetIndex; ++i) {
@@ -327,20 +316,38 @@ export default DatasetController.extend({
}
return ringWeightOffset;
- },
+ }
/**
* @private
*/
- _getRingWeight: function(dataSetIndex) {
+ _getRingWeight(dataSetIndex) {
return Math.max(valueOrDefault(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
- },
+ }
/**
* Returns the sum of all visibile data set weights. This value can be 0.
* @private
*/
- _getVisibleDatasetWeightTotal: function() {
+ _getVisibleDatasetWeightTotal() {
return this._getRingWeightOffset(this.chart.data.datasets.length);
}
-});
+}
+
+DoughnutController.prototype.dataElementType = Arc;
+
+
+/**
+ * @private
+ */
+DoughnutController.prototype._dataElementOptions = [
+ 'backgroundColor',
+ 'borderColor',
+ 'borderWidth',
+ 'borderAlign',
+ 'hoverBackgroundColor',
+ 'hoverBorderColor',
+ 'hoverBorderWidth',
+];
+
+export default DoughnutController; | true |
Other | chartjs | Chart.js | 6affaa2a73429da1a1b990ff1c726dc317148931.json | Convert controllers to ES6 classes (#7061) | src/controllers/controller.horizontalBar.js | @@ -42,18 +42,25 @@ defaults._set('horizontalBar', {
}
});
-export default BarController.extend({
+class HorizontalBarController extends BarController {
+
+ constructor(chart, datasetIndex) {
+ super(chart, datasetIndex);
+ }
+
/**
* @private
*/
- _getValueScaleId: function() {
+ _getValueScaleId() {
return this._cachedMeta.xAxisID;
- },
+ }
/**
* @private
*/
- _getIndexScaleId: function() {
+ _getIndexScaleId() {
return this._cachedMeta.yAxisID;
}
-});
+}
+
+export default HorizontalBarController; | true |
Other | chartjs | Chart.js | 6affaa2a73429da1a1b990ff1c726dc317148931.json | Convert controllers to ES6 classes (#7061) | src/controllers/controller.line.js | @@ -26,47 +26,13 @@ defaults._set('line', {
}
});
-export default DatasetController.extend({
+class LineController extends DatasetController {
- datasetElementType: Line,
-
- dataElementType: Point,
-
- /**
- * @private
- */
- _datasetElementOptions: [
- 'backgroundColor',
- 'borderCapStyle',
- 'borderColor',
- 'borderDash',
- 'borderDashOffset',
- 'borderJoinStyle',
- 'borderWidth',
- 'capBezierPoints',
- 'cubicInterpolationMode',
- 'fill'
- ],
-
- /**
- * @private
- */
- _dataElementOptions: {
- backgroundColor: 'pointBackgroundColor',
- borderColor: 'pointBorderColor',
- borderWidth: 'pointBorderWidth',
- hitRadius: 'pointHitRadius',
- hoverHitRadius: 'pointHitRadius',
- hoverBackgroundColor: 'pointHoverBackgroundColor',
- hoverBorderColor: 'pointHoverBorderColor',
- hoverBorderWidth: 'pointHoverBorderWidth',
- hoverRadius: 'pointHoverRadius',
- pointStyle: 'pointStyle',
- radius: 'pointRadius',
- rotation: 'pointRotation'
- },
+ constructor(chart, datasetIndex) {
+ super(chart, datasetIndex);
+ }
- update: function(mode) {
+ update(mode) {
const me = this;
const meta = me._cachedMeta;
const line = meta.dataset;
@@ -89,9 +55,9 @@ export default DatasetController.extend({
if (meta.visible) {
me.updateElements(points, 0, mode);
}
- },
+ }
- updateElements: function(points, start, mode) {
+ updateElements(points, start, mode) {
const me = this;
const reset = mode === 'reset';
const {xScale, yScale, _stacked} = me._cachedMeta;
@@ -125,12 +91,12 @@ export default DatasetController.extend({
}
me._updateSharedOptions(sharedOptions, mode);
- },
+ }
/**
* @private
*/
- _resolveDatasetElementOptions: function() {
+ _resolveDatasetElementOptions() {
const me = this;
const config = me._config;
const options = me.chart.options;
@@ -145,12 +111,12 @@ export default DatasetController.extend({
values.steppedLine = resolve([config.steppedLine, lineOptions.stepped]);
return values;
- },
+ }
/**
* @private
*/
- _getMaxOverflow: function() {
+ _getMaxOverflow() {
const me = this;
const meta = me._cachedMeta;
const border = me._showLine && meta.dataset.options.borderWidth || 0;
@@ -161,9 +127,9 @@ export default DatasetController.extend({
const firstPoint = data[0].size();
const lastPoint = data[data.length - 1].size();
return Math.max(border, firstPoint, lastPoint) / 2;
- },
+ }
- draw: function() {
+ draw() {
const me = this;
const ctx = me._ctx;
const chart = me.chart;
@@ -191,5 +157,45 @@ export default DatasetController.extend({
for (i = 0, ilen = active.length; i < ilen; ++i) {
active[i].draw(ctx, area);
}
- },
-});
+ }
+}
+
+LineController.prototype.datasetElementType = Line;
+
+LineController.prototype.dataElementType = Point;
+
+/**
+ * @private
+ */
+LineController.prototype._datasetElementOptions = [
+ 'backgroundColor',
+ 'borderCapStyle',
+ 'borderColor',
+ 'borderDash',
+ 'borderDashOffset',
+ 'borderJoinStyle',
+ 'borderWidth',
+ 'capBezierPoints',
+ 'cubicInterpolationMode',
+ 'fill'
+];
+
+/**
+ * @private
+ */
+LineController.prototype._dataElementOptions = {
+ backgroundColor: 'pointBackgroundColor',
+ borderColor: 'pointBorderColor',
+ borderWidth: 'pointBorderWidth',
+ hitRadius: 'pointHitRadius',
+ hoverHitRadius: 'pointHitRadius',
+ hoverBackgroundColor: 'pointHoverBackgroundColor',
+ hoverBorderColor: 'pointHoverBorderColor',
+ hoverBorderWidth: 'pointHoverBorderWidth',
+ hoverRadius: 'pointHoverRadius',
+ pointStyle: 'pointStyle',
+ radius: 'pointRadius',
+ rotation: 'pointRotation'
+};
+
+export default LineController; | true |
Other | chartjs | Chart.js | 6affaa2a73429da1a1b990ff1c726dc317148931.json | Convert controllers to ES6 classes (#7061) | src/controllers/controller.polarArea.js | @@ -90,48 +90,37 @@ function getStartAngleRadians(deg) {
return toRadians(deg) - 0.5 * Math.PI;
}
-export default DatasetController.extend({
+class PolarAreaController extends DatasetController {
- dataElementType: Arc,
-
- /**
- * @private
- */
- _dataElementOptions: [
- 'backgroundColor',
- 'borderColor',
- 'borderWidth',
- 'borderAlign',
- 'hoverBackgroundColor',
- 'hoverBorderColor',
- 'hoverBorderWidth',
- ],
+ constructor(chart, datasetIndex) {
+ super(chart, datasetIndex);
+ }
/**
* @private
*/
- _getIndexScaleId: function() {
+ _getIndexScaleId() {
return this._cachedMeta.rAxisID;
- },
+ }
/**
* @private
*/
- _getValueScaleId: function() {
+ _getValueScaleId() {
return this._cachedMeta.rAxisID;
- },
+ }
- update: function(mode) {
+ update(mode) {
const arcs = this._cachedMeta.data;
this._updateRadius();
this.updateElements(arcs, 0, mode);
- },
+ }
/**
* @private
*/
- _updateRadius: function() {
+ _updateRadius() {
var me = this;
var chart = me.chart;
var chartArea = chart.chartArea;
@@ -144,9 +133,9 @@ export default DatasetController.extend({
me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
me.innerRadius = me.outerRadius - chart.radiusLength;
- },
+ }
- updateElements: function(arcs, start, mode) {
+ updateElements(arcs, start, mode) {
const me = this;
const reset = mode === 'reset';
const chart = me.chart;
@@ -195,9 +184,9 @@ export default DatasetController.extend({
me._updateElement(arc, index, properties, mode);
}
- },
+ }
- countVisibleElements: function() {
+ countVisibleElements() {
var dataset = this.getDataset();
var meta = this._cachedMeta;
var count = 0;
@@ -209,12 +198,12 @@ export default DatasetController.extend({
});
return count;
- },
+ }
/**
* @private
*/
- _computeAngle: function(index) {
+ _computeAngle(index) {
var me = this;
var meta = me._cachedMeta;
var count = meta.count;
@@ -237,4 +226,21 @@ export default DatasetController.extend({
(2 * Math.PI) / count
], context, index);
}
-});
+}
+
+PolarAreaController.prototype.dataElementType = Arc;
+
+/**
+ * @private
+ */
+PolarAreaController.prototype._dataElementOptions = [
+ 'backgroundColor',
+ 'borderColor',
+ 'borderWidth',
+ 'borderAlign',
+ 'hoverBackgroundColor',
+ 'hoverBorderColor',
+ 'hoverBorderWidth'
+];
+
+export default PolarAreaController; | true |
Other | chartjs | Chart.js | 6affaa2a73429da1a1b990ff1c726dc317148931.json | Convert controllers to ES6 classes (#7061) | src/controllers/controller.radar.js | @@ -20,60 +20,30 @@ defaults._set('radar', {
}
});
-export default DatasetController.extend({
- datasetElementType: Line,
+class RadarController extends DatasetController {
- dataElementType: Point,
-
- /**
- * @private
- */
- _datasetElementOptions: [
- 'backgroundColor',
- 'borderWidth',
- 'borderColor',
- 'borderCapStyle',
- 'borderDash',
- 'borderDashOffset',
- 'borderJoinStyle',
- 'fill'
- ],
-
- /**
- * @private
- */
- _dataElementOptions: {
- backgroundColor: 'pointBackgroundColor',
- borderColor: 'pointBorderColor',
- borderWidth: 'pointBorderWidth',
- hitRadius: 'pointHitRadius',
- hoverBackgroundColor: 'pointHoverBackgroundColor',
- hoverBorderColor: 'pointHoverBorderColor',
- hoverBorderWidth: 'pointHoverBorderWidth',
- hoverRadius: 'pointHoverRadius',
- pointStyle: 'pointStyle',
- radius: 'pointRadius',
- rotation: 'pointRotation'
- },
+ constructor(chart, datasetIndex) {
+ super(chart, datasetIndex);
+ }
/**
* @private
*/
- _getIndexScaleId: function() {
+ _getIndexScaleId() {
return this._cachedMeta.rAxisID;
- },
+ }
/**
* @private
*/
- _getValueScaleId: function() {
+ _getValueScaleId() {
return this._cachedMeta.rAxisID;
- },
+ }
/**
* @private
*/
- _getLabelAndValue: function(index) {
+ _getLabelAndValue(index) {
const me = this;
const vScale = me._cachedMeta.vScale;
const parsed = me._getParsed(index);
@@ -82,9 +52,9 @@ export default DatasetController.extend({
label: vScale._getLabels()[index],
value: '' + vScale.getLabelForValue(parsed[vScale.axis])
};
- },
+ }
- update: function(mode) {
+ update(mode) {
const me = this;
const meta = me._cachedMeta;
const line = meta.dataset;
@@ -103,9 +73,9 @@ export default DatasetController.extend({
me.updateElements(points, 0, mode);
line.updateControlPoints(me.chart.chartArea);
- },
+ }
- updateElements: function(points, start, mode) {
+ updateElements(points, start, mode) {
const me = this;
const dataset = me.getDataset();
const scale = me.chart.scales.r;
@@ -131,12 +101,12 @@ export default DatasetController.extend({
me._updateElement(point, index, properties, mode);
}
- },
+ }
/**
* @private
*/
- _resolveDatasetElementOptions: function() {
+ _resolveDatasetElementOptions() {
const me = this;
const config = me._config;
const options = me.chart.options;
@@ -147,4 +117,41 @@ export default DatasetController.extend({
return values;
}
-});
+}
+
+RadarController.prototype.datasetElementType = Line;
+
+RadarController.prototype.dataElementType = Point;
+
+/**
+ * @private
+ */
+RadarController.prototype._datasetElementOptions = [
+ 'backgroundColor',
+ 'borderWidth',
+ 'borderColor',
+ 'borderCapStyle',
+ 'borderDash',
+ 'borderDashOffset',
+ 'borderJoinStyle',
+ 'fill'
+];
+
+/**
+ * @private
+ */
+RadarController.prototype._dataElementOptions = {
+ backgroundColor: 'pointBackgroundColor',
+ borderColor: 'pointBorderColor',
+ borderWidth: 'pointBorderWidth',
+ hitRadius: 'pointHitRadius',
+ hoverBackgroundColor: 'pointHoverBackgroundColor',
+ hoverBorderColor: 'pointHoverBorderColor',
+ hoverBorderWidth: 'pointHoverBorderWidth',
+ hoverRadius: 'pointHoverRadius',
+ pointStyle: 'pointStyle',
+ radius: 'pointRadius',
+ rotation: 'pointRotation'
+};
+
+export default RadarController; | true |
Other | chartjs | Chart.js | 93757a53e5d47061e31190829c28b8f5e6e5681c.json | Fix legend title drawing + update sample (#7060) | samples/legend/title.html | @@ -2,7 +2,7 @@
<html>
<head>
- <title>Legend Positions</title>
+ <title>Legend Title Positions</title>
<script src="../../dist/Chart.min.js"></script>
<script src="../utils.js"></script>
<style> | true |
Other | chartjs | Chart.js | 93757a53e5d47061e31190829c28b8f5e6e5681c.json | Fix legend title drawing + update sample (#7060) | src/plugins/plugin.legend.js | @@ -513,7 +513,7 @@ class Legend extends Element {
return;
}
- const rtlHelper = getRtlAdapter(opts.rtl, me.left, me.minSize.width);
+ const rtlHelper = getRtlAdapter(opts.rtl, me.left, me._minSize.width);
const ctx = me.ctx;
const fontColor = valueOrDefault(titleOpts.fontColor, defaults.fontColor);
const position = titleOpts.position; | true |
Other | chartjs | Chart.js | 1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f.json | Fix some JSDoc errors (#7026)
* Fix some JSDoc errors
* Fix helpers.dom JSDoc errors
* Add scale JSDoc errors
* Address review comment
* Fix additional errors
* Document optional parameters
* JSDoc fixes for datasetController
* Remove undefined | src/core/core.controller.js | @@ -981,7 +981,7 @@ class Chart {
/**
* Handle an event
* @private
- * @param {IEvent} event the event to handle
+ * @param {IEvent} e the event to handle
* @return {boolean} true if the chart needs to re-render
*/
handleEvent(e) { | true |
Other | chartjs | Chart.js | 1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f.json | Fix some JSDoc errors (#7026)
* Fix some JSDoc errors
* Fix helpers.dom JSDoc errors
* Add scale JSDoc errors
* Address review comment
* Fix additional errors
* Document optional parameters
* JSDoc fixes for datasetController
* Remove undefined | src/core/core.datasetController.js | @@ -461,7 +461,7 @@ helpers.extend(DatasetController.prototype, {
// Re-sync meta data in case the user replaced the data array or if we missed
// any updates and so make sure that we handle number of datapoints changing.
- me.resyncElements(dataChanged | labelsChanged | scaleChanged | stackChanged);
+ me.resyncElements(dataChanged || labelsChanged || scaleChanged || stackChanged);
// if stack changed, update stack values for the whole dataset
if (stackChanged) {
@@ -783,7 +783,10 @@ helpers.extend(DatasetController.prototype, {
me._cacheScaleStackStatus();
},
- update: helpers.noop,
+ /**
+ * @param {string} mode
+ */
+ update: function(mode) {}, // eslint-disable-line no-unused-vars
draw: function() {
const ctx = this._ctx;
@@ -820,6 +823,7 @@ helpers.extend(DatasetController.prototype, {
* Returns a set of predefined style properties that should be used to represent the dataset
* or the data if the index is specified
* @param {number} index - data index
+ * @param {boolean} [active] - true if hover
* @return {IStyleInterface} style object
*/
getStyle: function(index, active) { | true |
Other | chartjs | Chart.js | 1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f.json | Fix some JSDoc errors (#7026)
* Fix some JSDoc errors
* Fix helpers.dom JSDoc errors
* Add scale JSDoc errors
* Address review comment
* Fix additional errors
* Document optional parameters
* JSDoc fixes for datasetController
* Remove undefined | src/core/core.interaction.js | @@ -6,7 +6,7 @@ import {_lookup, _rlookup} from '../helpers/helpers.collection';
/**
* Helper function to get relative position for an event
- * @param {Event|IEvent} event - The event to get the position for
+ * @param {Event|IEvent} e - The event to get the position for
* @param {Chart} chart - The chart
* @returns {object} the event position
*/
@@ -47,7 +47,7 @@ function evaluateAllVisibleItems(chart, handler) {
* @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
+ * @returns {{lo:number, hi:number}} indices to search data array between
*/
function binarySearch(metaset, axis, value, intersect) {
const {controller, data, _sorted} = metaset;
@@ -79,7 +79,7 @@ function binarySearch(metaset, axis, value, intersect) {
* @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
- * @param {boolean} intersect - consider intersecting items
+ * @param {boolean} [intersect] - consider intersecting items
*/
function optimizedEvaluateItems(chart, axis, position, handler, intersect) {
const metasets = chart._getSortedVisibleDatasetMetas();
@@ -140,8 +140,8 @@ function getIntersectItems(chart, position, axis) {
* Helper function to get the items nearest to the event position considering all visible items in the chart
* @param {Chart} chart - the chart to look at elements from
* @param {object} position - the point to be nearest to
- * @param {function} axis - the axes along which to measure distance
- * @param {boolean} intersect - if true, only consider items that intersect the position
+ * @param {string} axis - the axes along which to measure distance
+ * @param {boolean} [intersect] - if true, only consider items that intersect the position
* @return {ChartElement[]} the nearest items
*/
function getNearestItems(chart, position, axis, intersect) { | true |
Other | chartjs | Chart.js | 1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f.json | Fix some JSDoc errors (#7026)
* Fix some JSDoc errors
* Fix helpers.dom JSDoc errors
* Add scale JSDoc errors
* Address review comment
* Fix additional errors
* Document optional parameters
* JSDoc fixes for datasetController
* Remove undefined | src/core/core.scale.js | @@ -299,7 +299,7 @@ class Scale extends Element {
* Get the padding needed for the scale
* @method getPadding
* @private
- * @returns {Padding} the necessary padding
+ * @returns {object} the necessary padding
*/
getPadding() {
const me = this;
@@ -491,6 +491,9 @@ class Scale extends Element {
beforeBuildTicks() {
call(this.options.beforeBuildTicks, [this]);
}
+ /**
+ * @return {object[]} the ticks
+ */
buildTicks() {}
afterBuildTicks() {
call(this.options.afterBuildTicks, [this]);
@@ -800,17 +803,15 @@ class Scale extends Element {
* Returns the location of the given data point. Value can either be an index or a numerical value
* The coordinate (0, 0) is at the upper-left corner of the canvas
* @param value
- * @param index
- * @param datasetIndex
*/
- getPixelForValue() {}
+ getPixelForValue(value) {} // eslint-disable-line no-unused-vars
/**
* Used to get the data value from a given pixel. This is the inverse of getPixelForValue
* The coordinate (0, 0) is at the upper-left corner of the canvas
* @param pixel
*/
- getValueForPixel() {}
+ getValueForPixel(pixel) {} // eslint-disable-line no-unused-vars
/**
* Returns the location of the tick at the given index | true |
Other | chartjs | Chart.js | 1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f.json | Fix some JSDoc errors (#7026)
* Fix some JSDoc errors
* Fix helpers.dom JSDoc errors
* Add scale JSDoc errors
* Address review comment
* Fix additional errors
* Document optional parameters
* JSDoc fixes for datasetController
* Remove undefined | src/helpers/helpers.dom.js | @@ -39,6 +39,7 @@ function parseMaxStyle(styleValue, node, parentProperty) {
* @param {HTMLElement} domNode - the node to check the constraint on
* @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
* @param {string} percentageProperty - property of parent to use when calculating width as a percentage
+ * @return {number|undefined} number or undefined if no constraint
* @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
*/
function getConstraintDimension(domNode, maxStyle, percentageProperty) {
@@ -55,8 +56,6 @@ function getConstraintDimension(domNode, maxStyle, percentageProperty) {
hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
}
-
- return 'none';
}
export function getStyle(el, property) {
@@ -65,12 +64,12 @@ export function getStyle(el, property) {
document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
}
-// returns Number or undefined if no constraint
+/** @return {number|undefined} number or undefined if no constraint */
function getConstraintWidth(domNode) {
return getConstraintDimension(domNode, 'max-width', 'clientWidth');
}
-// returns Number or undefined if no constraint
+/** @return {number|undefined} number or undefined if no constraint */
function getConstraintHeight(domNode) {
return getConstraintDimension(domNode, 'max-height', 'clientHeight');
} | true |
Other | chartjs | Chart.js | 1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f.json | Fix some JSDoc errors (#7026)
* Fix some JSDoc errors
* Fix helpers.dom JSDoc errors
* Add scale JSDoc errors
* Address review comment
* Fix additional errors
* Document optional parameters
* JSDoc fixes for datasetController
* Remove undefined | src/platform/platform.base.js | @@ -16,15 +16,15 @@ export default class BasePlatform {
* @param {object} options - The chart options
* @returns {CanvasRenderingContext2D} context2d instance
*/
- acquireContext() {}
+ acquireContext(canvas, options) {} // eslint-disable-line no-unused-vars
/**
* Called at chart destruction time, releases any resources associated to the context
* previously returned by the acquireContext() method.
* @param {CanvasRenderingContext2D} context - The context2d instance
* @returns {boolean} true if the method succeeded, else false
*/
- releaseContext() {}
+ releaseContext(context) {} // eslint-disable-line no-unused-vars
/**
* Registers the specified listener on the given chart.
@@ -33,15 +33,15 @@ export default class BasePlatform {
* @param {function} listener - Receives a notification (an object that implements
* the {@link IEvent} interface) when an event of the specified type occurs.
*/
- addEventListener() {}
+ addEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars
/**
* Removes the specified listener previously registered with addEventListener.
* @param {Chart} chart - Chart from which to remove the listener
* @param {string} type - The ({@link IEvent}) type to remove
* @param {function} listener - The listener function to remove from the event target.
*/
- removeEventListener() {}
+ removeEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars
/**
* @returns {number} the current devicePixelRatio of the device this platform is connected to. | true |
Other | chartjs | Chart.js | 1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f.json | Fix some JSDoc errors (#7026)
* Fix some JSDoc errors
* Fix helpers.dom JSDoc errors
* Add scale JSDoc errors
* Address review comment
* Fix additional errors
* Document optional parameters
* JSDoc fixes for datasetController
* Remove undefined | src/plugins/plugin.filler.js | @@ -47,7 +47,7 @@ function parseFillOption(line) {
// @todo if (fill[0] === '#')
function decodeFill(line, index, count) {
const fill = parseFillOption(line);
- let target = parseFloat(fill, 10);
+ let target = parseFloat(fill);
if (isFinite(target) && Math.floor(target) === target) {
if (fill[0] === '-' || fill[0] === '+') { | true |
Other | chartjs | Chart.js | 1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f.json | Fix some JSDoc errors (#7026)
* Fix some JSDoc errors
* Fix helpers.dom JSDoc errors
* Add scale JSDoc errors
* Address review comment
* Fix additional errors
* Document optional parameters
* JSDoc fixes for datasetController
* Remove undefined | src/plugins/plugin.legend.js | @@ -83,7 +83,7 @@ defaults._set('legend', {
/**
* Helper function to get the box width based on the usePointStyle option
- * @param {object} labelopts - the label options on the legend
+ * @param {object} labelOpts - the label options on the legend
* @param {number} fontSize - the label font size
* @return {number} width of the color box area
*/
@@ -616,8 +616,8 @@ class Legend extends Element {
/**
* Handle an event
+ * @param {IEvent} e - The event to handle
* @private
- * @param {IEvent} event - The event to handle
*/
handleEvent(e) {
var me = this; | true |
Other | chartjs | Chart.js | 1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f.json | Fix some JSDoc errors (#7026)
* Fix some JSDoc errors
* Fix helpers.dom JSDoc errors
* Add scale JSDoc errors
* Address review comment
* Fix additional errors
* Document optional parameters
* JSDoc fixes for datasetController
* Remove undefined | src/plugins/plugin.tooltip.js | @@ -199,7 +199,7 @@ function pushOrConcat(base, toPush) {
/**
* Returns array of strings split by newline
- * @param {string} value - The value to split by newline.
+ * @param {string} str - The value to split by newline.
* @returns {string[]} value if newline present - Returned from String split() method
* @function
*/
@@ -959,7 +959,7 @@ class Tooltip extends Element {
/**
* Handle an event
* @private
- * @param {IEvent} event - The event to handle
+ * @param {IEvent} e - The event to handle
* @returns {boolean} true if the tooltip changed
*/
handleEvent(e) { | true |
Other | chartjs | Chart.js | 1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f.json | Fix some JSDoc errors (#7026)
* Fix some JSDoc errors
* Fix helpers.dom JSDoc errors
* Add scale JSDoc errors
* Address review comment
* Fix additional errors
* Document optional parameters
* JSDoc fixes for datasetController
* Remove undefined | src/scales/scale.linearbase.js | @@ -37,7 +37,7 @@ function niceNum(range, round) {
* Generate a set of linear ticks
* @param generationOptions the options used to generate the ticks
* @param dataRange the range of the data
- * @returns {number[]} array of tick values
+ * @returns {object[]} array of tick objects
*/
function generateTicks(generationOptions, dataRange) {
const ticks = []; | true |
Other | chartjs | Chart.js | 1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f.json | Fix some JSDoc errors (#7026)
* Fix some JSDoc errors
* Fix helpers.dom JSDoc errors
* Add scale JSDoc errors
* Address review comment
* Fix additional errors
* Document optional parameters
* JSDoc fixes for datasetController
* Remove undefined | src/scales/scale.logarithmic.js | @@ -19,7 +19,7 @@ function finiteOrDefault(value, def) {
* Generate a set of logarithmic ticks
* @param generationOptions the options used to generate the ticks
* @param dataRange the range of the data
- * @returns {number[]} array of tick values
+ * @returns {object[]} array of tick objects
*/
function generateTicks(generationOptions, dataRange) {
const endExp = Math.floor(log10(dataRange.max)); | true |
Other | chartjs | Chart.js | 1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f.json | Fix some JSDoc errors (#7026)
* Fix some JSDoc errors
* Fix helpers.dom JSDoc errors
* Add scale JSDoc errors
* Address review comment
* Fix additional errors
* Document optional parameters
* JSDoc fixes for datasetController
* Remove undefined | src/scales/scale.time.js | @@ -430,9 +430,9 @@ function getLabelBounds(scale) {
/**
* Return subset of `timestamps` between `min` and `max`.
* Timestamps are assumend to be in sorted order.
- * @param {int[]} timestamps - array of timestamps
- * @param {int} min - min value (timestamp)
- * @param {int} max - max value (timestamp)
+ * @param {number[]} timestamps - array of timestamps
+ * @param {number} min - min value (timestamp)
+ * @param {number} max - max value (timestamp)
*/
function filterBetween(timestamps, min, max) {
let start = 0; | true |
Other | chartjs | Chart.js | 7cd77e779d4131cce3f2ba4c758fff7ad5a1b96b.json | Update imports for elements (#7049) | src/elements/element.point.js | @@ -2,7 +2,7 @@
import defaults from '../core/core.defaults';
import Element from '../core/core.element';
-import helpers from '../helpers';
+import {_isPointInArea, drawPoint} from '../helpers/helpers.canvas';
const defaultColor = defaults.color;
@@ -70,11 +70,11 @@ class Point extends Element {
}
// Clipping for Points.
- if (chartArea === undefined || helpers.canvas._isPointInArea(me, chartArea)) {
+ if (chartArea === undefined || _isPointInArea(me, chartArea)) {
ctx.strokeStyle = options.borderColor;
ctx.lineWidth = options.borderWidth;
ctx.fillStyle = options.backgroundColor;
- helpers.canvas.drawPoint(ctx, options, me.x, me.y);
+ drawPoint(ctx, options, me.x, me.y);
}
}
| true |
Other | chartjs | Chart.js | 7cd77e779d4131cce3f2ba4c758fff7ad5a1b96b.json | Update imports for elements (#7049) | src/elements/element.rectangle.js | @@ -2,7 +2,7 @@
import defaults from '../core/core.defaults';
import Element from '../core/core.element';
-import helpers from '../helpers';
+import {isObject} from '../helpers/helpers.core';
const defaultColor = defaults.color;
@@ -79,7 +79,7 @@ function parseBorderWidth(bar, maxW, maxH) {
var skip = parseBorderSkipped(bar);
var t, r, b, l;
- if (helpers.isObject(value)) {
+ if (isObject(value)) {
t = +value.top || 0;
r = +value.right || 0;
b = +value.bottom || 0; | true |
Other | chartjs | Chart.js | 771fe520957199b32a26205c14f4816002842bcb.json | Update legend imports (#7048) | src/plugins/plugin.legend.js | @@ -2,11 +2,11 @@
import defaults from '../core/core.defaults';
import Element from '../core/core.element';
-import helpers from '../helpers';
import layouts from '../core/core.layouts';
-
-const getRtlHelper = helpers.rtl.getRtlAdapter;
-const valueOrDefault = helpers.valueOrDefault;
+import {drawPoint} from '../helpers/helpers.canvas';
+import {callback as call, extend, mergeIf, valueOrDefault} from '../helpers/helpers.core';
+import {_parseFont, toPadding} from '../helpers/helpers.options';
+import {getRtlAdapter, overrideTextDirection, restoreTextDirection} from '../helpers/helpers.rtl';
defaults._set('legend', {
display: true,
@@ -102,7 +102,7 @@ class Legend extends Element {
super();
const me = this;
- helpers.extend(me, config);
+ extend(me, config);
// Contains hit boxes for each dataset (in dataset order)
me.legendHitBoxes = [];
@@ -194,7 +194,7 @@ class Legend extends Element {
buildLabels() {
var me = this;
var labelOpts = me.options.labels || {};
- var legendItems = helpers.callback(labelOpts.generateLabels, [me.chart], me) || [];
+ var legendItems = call(labelOpts.generateLabels, [me.chart], me) || [];
if (labelOpts.filter) {
legendItems = legendItems.filter(function(item) {
@@ -222,7 +222,7 @@ class Legend extends Element {
const display = opts.display;
const ctx = me.ctx;
- const labelFont = helpers.options._parseFont(labelOpts);
+ const labelFont = _parseFont(labelOpts);
const fontSize = labelFont.size;
// Reset hit boxes
@@ -346,10 +346,10 @@ class Legend extends Element {
}
me._drawTitle();
- const rtlHelper = getRtlHelper(opts.rtl, me.left, me._minSize.width);
+ const rtlHelper = getRtlAdapter(opts.rtl, me.left, me._minSize.width);
const ctx = me.ctx;
const fontColor = valueOrDefault(labelOpts.fontColor, defaults.fontColor);
- const labelFont = helpers.options._parseFont(labelOpts);
+ const labelFont = _parseFont(labelOpts);
const fontSize = labelFont.size;
let cursor;
@@ -399,7 +399,7 @@ class Legend extends Element {
var centerY = y + fontSize / 2;
// Draw pointStyle as legend symbol
- helpers.canvas.drawPoint(ctx, drawOptions, centerX, centerY);
+ drawPoint(ctx, drawOptions, centerX, centerY);
} else {
// Draw box as legend symbol
ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
@@ -456,7 +456,7 @@ class Legend extends Element {
};
}
- helpers.rtl.overrideTextDirection(me.ctx, opts.textDirection);
+ overrideTextDirection(me.ctx, opts.textDirection);
var itemHeight = fontSize + labelOpts.padding;
me.legendItems.forEach(function(legendItem, i) {
@@ -499,21 +499,21 @@ class Legend extends Element {
}
});
- helpers.rtl.restoreTextDirection(me.ctx, opts.textDirection);
+ restoreTextDirection(me.ctx, opts.textDirection);
}
_drawTitle() {
const me = this;
const opts = me.options;
const titleOpts = opts.title;
- const titleFont = helpers.options._parseFont(titleOpts);
- const titlePadding = helpers.options.toPadding(titleOpts.padding);
+ const titleFont = _parseFont(titleOpts);
+ const titlePadding = toPadding(titleOpts.padding);
if (!titleOpts.display) {
return;
}
- const rtlHelper = getRtlHelper(opts.rtl, me.left, me.minSize.width);
+ const rtlHelper = getRtlAdapter(opts.rtl, me.left, me.minSize.width);
const ctx = me.ctx;
const fontColor = valueOrDefault(titleOpts.fontColor, defaults.fontColor);
const position = titleOpts.position;
@@ -586,8 +586,8 @@ class Legend extends Element {
_computeTitleHeight() {
const titleOpts = this.options.title;
- const titleFont = helpers.options._parseFont(titleOpts);
- const titlePadding = helpers.options.toPadding(titleOpts.padding);
+ const titleFont = _parseFont(titleOpts);
+ const titlePadding = toPadding(titleOpts.padding);
return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
}
@@ -698,7 +698,7 @@ export default {
var legend = chart.legend;
if (legendOpts) {
- helpers.mergeIf(legendOpts, defaults.legend);
+ mergeIf(legendOpts, defaults.legend);
if (legend) {
layouts.configure(chart, legend, legendOpts); | false |
Other | chartjs | Chart.js | 251f3832bc472f530747a66131200045c51032af.json | Remove extra call to _getLabelCapacity (#6999) | src/scales/scale.time.js | @@ -230,11 +230,13 @@ function determineMajorUnit(unit) {
* Important: this method can return ticks outside the min and max range, it's the
* responsibility of the calling code to clamp values if needed.
*/
-function generate(scale, min, max, capacity) {
+function generate(scale) {
const adapter = scale._adapter;
+ const min = scale.min;
+ const max = scale.max;
const options = scale.options;
const timeOpts = options.time;
- const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
+ const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, scale._getLabelCapacity(min));
const stepSize = resolve([timeOpts.stepSize, timeOpts.unitStepSize, 1]);
const weekday = minor === 'week' ? timeOpts.isoWeekday : false;
const ticks = [];
@@ -396,22 +398,15 @@ function getAllTimestamps(scale) {
function getTimestampsForTicks(scale) {
- const min = scale.min;
- const max = scale.max;
const options = scale.options;
- const capacity = scale._getLabelCapacity(min);
const source = options.ticks.source;
- let timestamps;
if (source === 'data' || (source === 'auto' && options.distribution === 'series')) {
- timestamps = getAllTimestamps(scale);
+ return getAllTimestamps(scale);
} else if (source === 'labels') {
- timestamps = getLabelTimestamps(scale);
- } else {
- timestamps = generate(scale, min, max, capacity, options);
+ return getLabelTimestamps(scale);
}
-
- return timestamps;
+ return generate(scale);
}
function getTimestampsForTable(scale) { | false |
Other | chartjs | Chart.js | 26536f8849335f17f3958d7eb544ad811732937e.json | Fix bug in opacity handling (#7047) | src/plugins/plugin.tooltip.js | @@ -925,7 +925,7 @@ class Tooltip extends Element {
};
// IE11/Edge does not like very small opacities, so snap to 0
- opacity = Math.abs(opacity < 1e-3) ? 0 : opacity;
+ opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
// Truthy/falsey value for empty tooltip
var hasTooltipContent = me.title.length || me.beforeBody.length || me.body.length || me.afterBody.length || me.footer.length; | false |
Other | chartjs | Chart.js | 13851c0209a1478184743d290b2ec07fc838a866.json | Remove unnecessary check for color library (#7043) | src/helpers/index.js | @@ -11,11 +11,7 @@ import * as options from './helpers.options';
import * as math from './helpers.math';
import * as rtl from './helpers.rtl';
-const colorHelper = !color ?
- function(value) {
- console.error('Color.js not found!');
- return value;
- } :
+const colorHelper =
function(value) {
if (value instanceof CanvasGradient || value instanceof CanvasPattern) {
// TODO: figure out what this should be. Previously returned | false |
Other | chartjs | Chart.js | a7cb59179a580f6a5c2865e0af716c3480a3b501.json | Fix typo in elements.line (#7040)
Fix typo in elements.line | src/elements/element.line.js | @@ -166,6 +166,11 @@ function fastPathSegment(ctx, line, segment, params) {
}
}
+/**
+ * @param {Line} line - the line
+ * @returns {function}
+ * @private
+ */
function _getSegmentMethod(line) {
const opts = line.options;
const borderDash = opts.borderDash && opts.borderDash.length;
@@ -271,7 +276,7 @@ class Line extends Element {
interpolated[property] = point[property];
result.push(interpolated);
}
- return result.lenght === 1 ? result[0] : result;
+ return result.length === 1 ? result[0] : result;
}
/** | false |
Other | chartjs | Chart.js | d449bbc83aa5ea94ad2912d593500e561d0d94bb.json | Remove unused helpers (#7039) | docs/getting-started/v3-migration.md | @@ -91,6 +91,9 @@ Animation system was completely rewritten in Chart.js v3. Each property can now
* `helpers.addEvent`
* `helpers.aliasPixel`
* `helpers.configMerge`
+* `helpers.findIndex`
+* `helpers.findNextWhere`
+* `helpers.findPreviousWhere`
* `helpers.indexOf`
* `helpers.lineTo`
* `helpers.longestText` was moved to the `helpers.canvas` namespace and made private | true |
Other | chartjs | Chart.js | d449bbc83aa5ea94ad2912d593500e561d0d94bb.json | Remove unused helpers (#7039) | src/helpers/index.js | @@ -36,43 +36,6 @@ export default {
math,
rtl,
- findIndex: Array.prototype.findIndex ?
- function(array, callback, scope) {
- return array.findIndex(callback, scope);
- } :
- function(array, callback, scope) {
- scope = scope === undefined ? array : scope;
- for (var i = 0, ilen = array.length; i < ilen; ++i) {
- if (callback.call(scope, array[i], i, array)) {
- return i;
- }
- }
- return -1;
- },
- findNextWhere: function(arrayToSearch, filterCallback, startIndex) {
- // Default to start of the array
- if (coreHelpers.isNullOrUndef(startIndex)) {
- startIndex = -1;
- }
- for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
- var currentItem = arrayToSearch[i];
- if (filterCallback(currentItem)) {
- return currentItem;
- }
- }
- },
- findPreviousWhere: function(arrayToSearch, filterCallback, startIndex) {
- // Default to end of the array
- if (coreHelpers.isNullOrUndef(startIndex)) {
- startIndex = arrayToSearch.length;
- }
- for (var i = startIndex - 1; i >= 0; i--) {
- var currentItem = arrayToSearch[i];
- if (filterCallback(currentItem)) {
- return currentItem;
- }
- }
- },
// Implementation of the nice number algorithm used in determining where axis labels will go
niceNum: function(range, round) {
var exponent = Math.floor(math.log10(range)); | true |
Other | chartjs | Chart.js | d449bbc83aa5ea94ad2912d593500e561d0d94bb.json | Remove unused helpers (#7039) | test/specs/core.helpers.tests.js | @@ -6,19 +6,6 @@ describe('Core helper tests', function() {
helpers = window.Chart.helpers;
});
- it('should filter an array', function() {
- var data = [-10, 0, 6, 0, 7];
- var callback = function(item) {
- return item > 2;
- };
- expect(helpers.findNextWhere(data, callback)).toEqual(6);
- expect(helpers.findNextWhere(data, callback, 2)).toBe(7);
- expect(helpers.findNextWhere(data, callback, 4)).toBe(undefined);
- expect(helpers.findPreviousWhere(data, callback)).toBe(7);
- expect(helpers.findPreviousWhere(data, callback, 3)).toBe(6);
- expect(helpers.findPreviousWhere(data, callback, 0)).toBe(undefined);
- });
-
it('should generate integer ids', function() {
var uid = helpers.uid();
expect(uid).toEqual(jasmine.any(Number)); | true |
Other | chartjs | Chart.js | 4462a2c950b989aabf6d5c50b20b6b79a9e6a2ba.json | Reduce requestAnimationFrame polyfill (#7033)
* Reduce requestAnimationFrame polyfill
* Remove another unnecessary polyfill | src/helpers/index.js | @@ -101,21 +101,14 @@ export default {
return niceFraction * Math.pow(10, exponent);
},
- // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
+ // Request animation polyfill
requestAnimFrame: (function() {
if (typeof window === 'undefined') {
return function(callback) {
callback();
};
}
- return window.requestAnimationFrame ||
- window.webkitRequestAnimationFrame ||
- window.mozRequestAnimationFrame ||
- window.oRequestAnimationFrame ||
- window.msRequestAnimationFrame ||
- function(callback) {
- return window.setTimeout(callback, 1000 / 60);
- };
+ return window.requestAnimationFrame;
}()),
// -- Canvas methods
fontString: function(pixelSize, fontStyle, fontFamily) { | false |
Other | chartjs | Chart.js | dac52d189e362fa6463bce2f3985b2cd934bb03d.json | Convert the DateAdapter to ES6 (#7032) | src/core/core.adapters.js | @@ -6,13 +6,13 @@
'use strict';
-import helpers from '../helpers';
+import {extend} from '../helpers/helpers.core';
+/**
+ * @return {*}
+ */
function abstract() {
- throw new Error(
- 'This method is not implemented: either no adapter can ' +
- 'be found or an incomplete integration was provided.'
- );
+ throw new Error('This method is not implemented: either no adapter can be found or an incomplete integration was provided.');
}
/**
@@ -24,85 +24,93 @@ function abstract() {
/**
* Currently supported unit string values.
- * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
+ * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')} Unit
* @memberof Chart._adapters._date
- * @name Unit
*/
-/**
- * @class
- */
-function DateAdapter(options) {
- this.options = options || {};
-}
+class DateAdapter {
+
+ constructor(options) {
+ this.options = options || {};
+ }
-helpers.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
/**
* Returns a map of time formats for the supported formatting units defined
* in Unit as well as 'datetime' representing a detailed date/time string.
* @returns {{string: string}}
*/
- formats: abstract,
+ formats() {
+ return abstract();
+ }
/**
* Parses the given `value` and return the associated timestamp.
* @param {any} value - the value to parse (usually comes from the data)
* @param {string} [format] - the expected data format
* @returns {(number|null)}
- * @function
*/
- parse: abstract,
+ parse(value, format) { // eslint-disable-line no-unused-vars
+ return abstract();
+ }
/**
* Returns the formatted date in the specified `format` for a given `timestamp`.
* @param {number} timestamp - the timestamp to format
* @param {string} format - the date/time token
* @return {string}
- * @function
*/
- format: abstract,
+ format(timestamp, format) { // eslint-disable-line no-unused-vars
+ return abstract();
+ }
/**
* Adds the specified `amount` of `unit` to the given `timestamp`.
* @param {number} timestamp - the input timestamp
* @param {number} amount - the amount to add
* @param {Unit} unit - the unit as string
* @return {number}
- * @function
*/
- add: abstract,
+ add(timestamp, amount, unit) { // eslint-disable-line no-unused-vars
+ return abstract();
+ }
/**
* Returns the number of `unit` between the given timestamps.
- * @param {number} max - the input timestamp (reference)
- * @param {number} min - the timestamp to substract
+ * @param {number} a - the input timestamp (reference)
+ * @param {number} b - the timestamp to subtract
* @param {Unit} unit - the unit as string
* @return {number}
- * @function
*/
- diff: abstract,
+ diff(a, b, unit) { // eslint-disable-line no-unused-vars
+ return abstract();
+ }
/**
* Returns start of `unit` for the given `timestamp`.
* @param {number} timestamp - the input timestamp
* @param {Unit} unit - the unit as string
* @param {number} [weekday] - the ISO day of the week with 1 being Monday
* and 7 being Sunday (only needed if param *unit* is `isoWeek`).
- * @function
+ * @return {number}
*/
- startOf: abstract,
+ startOf(timestamp, unit, weekday) { // eslint-disable-line no-unused-vars
+ return abstract();
+ }
/**
* Returns end of `unit` for the given `timestamp`.
* @param {number} timestamp - the input timestamp
* @param {Unit} unit - the unit as string
- * @function
+ * @return {number}
*/
- endOf: abstract
-});
+ endOf(timestamp, unit) { // eslint-disable-line no-unused-vars
+ return abstract();
+ }
+
+}
DateAdapter.override = function(members) {
- helpers.extend(DateAdapter.prototype, members);
+ extend(DateAdapter.prototype, members);
};
export default { | false |
Other | chartjs | Chart.js | c667a9ef8571d179a552f6013af2cc108f1d2ac5.json | Move text helpers and reduce scope of imports (#7028) | docs/getting-started/v3-migration.md | @@ -93,7 +93,9 @@ Animation system was completely rewritten in Chart.js v3. Each property can now
* `helpers.configMerge`
* `helpers.indexOf`
* `helpers.lineTo`
+* `helpers.longestText` was moved to the `helpers.canvas` namespace and made private
* `helpers.max`
+* `helpers.measureText` was moved to the `helpers.canvas` namespace and made private
* `helpers.min`
* `helpers.nextItem`
* `helpers.numberOfLabelLines` | true |
Other | chartjs | Chart.js | c667a9ef8571d179a552f6013af2cc108f1d2ac5.json | Move text helpers and reduce scope of imports (#7028) | src/core/core.scale.js | @@ -2,16 +2,12 @@
import defaults from './core.defaults';
import Element from './core.element';
-import helpers from '../helpers';
+import {_alignPixel, _measureText} from '../helpers/helpers.canvas';
+import {callback as call, each, extend, isArray, isFinite, isNullOrUndef, isObject, valueOrDefault} from '../helpers/helpers.core';
+import {_factorize, toDegrees, toRadians} from '../helpers/helpers.math';
+import {_parseFont, resolve, toPadding} from '../helpers/helpers.options';
import Ticks from './core.ticks';
-const alignPixel = helpers.canvas._alignPixel;
-const isArray = helpers.isArray;
-const isFinite = helpers.isFinite;
-const isNullOrUndef = helpers.isNullOrUndef;
-const valueOrDefault = helpers.valueOrDefault;
-const resolve = helpers.options.resolve;
-
defaults._set('scale', {
display: true,
offset: false,
@@ -107,7 +103,7 @@ function getPixelForGridLine(scale, index, offsetGridLines) {
}
function garbageCollect(caches, length) {
- helpers.each(caches, function(cache) {
+ each(caches, function(cache) {
var gc = cache.gc;
var gcLen = gc.length / 2;
var i;
@@ -129,8 +125,8 @@ function getScaleLabelHeight(options) {
return 0;
}
- const font = helpers.options._parseFont(options);
- const padding = helpers.options.toPadding(options.padding);
+ const font = _parseFont(options);
+ const padding = toPadding(options.padding);
return font.lineHeight + padding.height;
}
@@ -162,7 +158,7 @@ function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
return Math.max(spacing, 1);
}
- factors = helpers.math._factorize(evenMajorSpacing);
+ factors = _factorize(evenMajorSpacing);
for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
factor = factors[i];
if (factor > spacing) {
@@ -336,7 +332,7 @@ class Scale extends Element {
// Any function can be extended by the scale type
beforeUpdate() {
- helpers.callback(this.options.beforeUpdate, [this]);
+ call(this.options.beforeUpdate, [this]);
}
/**
@@ -360,7 +356,7 @@ class Scale extends Element {
// TODO: make maxWidth, maxHeight private
me.maxWidth = maxWidth;
me.maxHeight = maxHeight;
- me.margins = helpers.extend({
+ me.margins = extend({
left: 0,
right: 0,
top: 0,
@@ -448,13 +444,13 @@ class Scale extends Element {
}
afterUpdate() {
- helpers.callback(this.options.afterUpdate, [this]);
+ call(this.options.afterUpdate, [this]);
}
//
beforeSetDimensions() {
- helpers.callback(this.options.beforeSetDimensions, [this]);
+ call(this.options.beforeSetDimensions, [this]);
}
setDimensions() {
const me = this;
@@ -479,29 +475,29 @@ class Scale extends Element {
me.paddingBottom = 0;
}
afterSetDimensions() {
- helpers.callback(this.options.afterSetDimensions, [this]);
+ call(this.options.afterSetDimensions, [this]);
}
// Data limits
beforeDataLimits() {
- helpers.callback(this.options.beforeDataLimits, [this]);
+ call(this.options.beforeDataLimits, [this]);
}
determineDataLimits() {}
afterDataLimits() {
- helpers.callback(this.options.afterDataLimits, [this]);
+ call(this.options.afterDataLimits, [this]);
}
//
beforeBuildTicks() {
- helpers.callback(this.options.beforeBuildTicks, [this]);
+ call(this.options.beforeBuildTicks, [this]);
}
buildTicks() {}
afterBuildTicks() {
- helpers.callback(this.options.afterBuildTicks, [this]);
+ call(this.options.afterBuildTicks, [this]);
}
beforeTickToLabelConversion() {
- helpers.callback(this.options.beforeTickToLabelConversion, [this]);
+ call(this.options.beforeTickToLabelConversion, [this]);
}
/**
* Convert ticks to label strings
@@ -512,17 +508,17 @@ class Scale extends Element {
let i, ilen, tick;
for (i = 0, ilen = ticks.length; i < ilen; i++) {
tick = ticks[i];
- tick.label = helpers.callback(tickOpts.callback, [tick.value, i, ticks], me);
+ tick.label = call(tickOpts.callback, [tick.value, i, ticks], me);
}
}
afterTickToLabelConversion() {
- helpers.callback(this.options.afterTickToLabelConversion, [this]);
+ call(this.options.afterTickToLabelConversion, [this]);
}
//
beforeCalculateLabelRotation() {
- helpers.callback(this.options.beforeCalculateLabelRotation, [this]);
+ call(this.options.beforeCalculateLabelRotation, [this]);
}
calculateLabelRotation() {
const me = this;
@@ -554,7 +550,7 @@ class Scale extends Element {
maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)
- tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
- labelRotation = helpers.math.toDegrees(Math.min(
+ labelRotation = toDegrees(Math.min(
Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
));
@@ -564,13 +560,13 @@ class Scale extends Element {
me.labelRotation = labelRotation;
}
afterCalculateLabelRotation() {
- helpers.callback(this.options.afterCalculateLabelRotation, [this]);
+ call(this.options.afterCalculateLabelRotation, [this]);
}
//
beforeFit() {
- helpers.callback(this.options.beforeFit, [this]);
+ call(this.options.beforeFit, [this]);
}
fit() {
const me = this;
@@ -616,7 +612,7 @@ class Scale extends Element {
if (isHorizontal) {
// A horizontal axis is more constrained by the height.
const isRotated = me.labelRotation !== 0;
- const angleRadians = helpers.math.toRadians(me.labelRotation);
+ const angleRadians = toRadians(me.labelRotation);
const cosRotation = Math.cos(angleRadians);
const sinRotation = Math.sin(angleRadians);
@@ -689,7 +685,7 @@ class Scale extends Element {
}
afterFit() {
- helpers.callback(this.options.afterFit, [this]);
+ call(this.options.afterFit, [this]);
}
// Shared Methods
@@ -754,15 +750,15 @@ class Scale extends Element {
width = height = 0;
// Undefined labels and arrays should not be measured
if (!isNullOrUndef(label) && !isArray(label)) {
- width = helpers.measureText(ctx, cache.data, cache.gc, width, label);
+ width = _measureText(ctx, cache.data, cache.gc, width, label);
height = lineHeight;
} else if (isArray(label)) {
// if it is an array let's measure each element
for (j = 0, jlen = label.length; j < jlen; ++j) {
nestedLabel = label[j];
// Undefined labels and arrays should not be measured
if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
- width = helpers.measureText(ctx, cache.data, cache.gc, width, nestedLabel);
+ width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);
height += lineHeight;
}
}
@@ -892,11 +888,11 @@ class Scale extends Element {
if (numMajorIndices > 0) {
let i, ilen;
const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
- skip(ticks, newTicks, spacing, helpers.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
+ skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
}
- skip(ticks, newTicks, spacing, last, helpers.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
+ skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
return newTicks;
}
skip(ticks, newTicks, spacing);
@@ -911,7 +907,7 @@ class Scale extends Element {
const optionTicks = me.options.ticks;
// Calculate space needed by label in axis direction.
- const rot = helpers.math.toRadians(me.labelRotation);
+ const rot = toRadians(me.labelRotation);
const cos = Math.abs(Math.cos(rot));
const sin = Math.abs(Math.sin(rot));
@@ -962,7 +958,7 @@ class Scale extends Element {
const axisWidth = gridLines.drawBorder ? resolve([gridLines.borderWidth, gridLines.lineWidth, 0], context, 0) : 0;
const axisHalfWidth = axisWidth / 2;
const alignBorderValue = function(pixel) {
- return alignPixel(chart, pixel, axisWidth);
+ return _alignPixel(chart, pixel, axisWidth);
};
let borderValue, i, tick, lineValue, alignedLineValue;
let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
@@ -994,7 +990,7 @@ class Scale extends Element {
} else if (axis === 'x') {
if (position === 'center') {
borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2);
- } else if (helpers.isObject(position)) {
+ } else if (isObject(position)) {
const positionAxisID = Object.keys(position)[0];
const value = position[positionAxisID];
borderValue = alignBorderValue(me.chart.scales[positionAxisID].getPixelForValue(value));
@@ -1007,7 +1003,7 @@ class Scale extends Element {
} else if (axis === 'y') {
if (position === 'center') {
borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
- } else if (helpers.isObject(position)) {
+ } else if (isObject(position)) {
const positionAxisID = Object.keys(position)[0];
const value = position[positionAxisID];
borderValue = alignBorderValue(me.chart.scales[positionAxisID].getPixelForValue(value));
@@ -1039,7 +1035,7 @@ class Scale extends Element {
continue;
}
- alignedLineValue = alignPixel(chart, lineValue, lineWidth);
+ alignedLineValue = _alignPixel(chart, lineValue, lineWidth);
if (isHorizontal) {
tx1 = tx2 = x1 = x2 = alignedLineValue;
@@ -1082,7 +1078,7 @@ class Scale extends Element {
const ticks = me.ticks;
const tickPadding = optionTicks.padding;
const tl = getTickMarkLength(options.gridLines);
- const rotation = -helpers.math.toRadians(me.labelRotation);
+ const rotation = -toRadians(me.labelRotation);
const items = [];
let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
@@ -1101,7 +1097,7 @@ class Scale extends Element {
} else if (axis === 'x') {
if (position === 'center') {
y = ((chartArea.top + chartArea.bottom) / 2) + tl + tickPadding;
- } else if (helpers.isObject(position)) {
+ } else if (isObject(position)) {
const positionAxisID = Object.keys(position)[0];
const value = position[positionAxisID];
y = me.chart.scales[positionAxisID].getPixelForValue(value) + tl + tickPadding;
@@ -1110,7 +1106,7 @@ class Scale extends Element {
} else if (axis === 'y') {
if (position === 'center') {
x = ((chartArea.left + chartArea.right) / 2) - tl - tickPadding;
- } else if (helpers.isObject(position)) {
+ } else if (isObject(position)) {
const positionAxisID = Object.keys(position)[0];
const value = position[positionAxisID];
x = me.chart.scales[positionAxisID].getPixelForValue(value);
@@ -1216,12 +1212,12 @@ class Scale extends Element {
let x1, x2, y1, y2;
if (me.isHorizontal()) {
- x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
- x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
+ x1 = _alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
+ x2 = _alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
y1 = y2 = borderValue;
} else {
- y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
- y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
+ y1 = _alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
+ y2 = _alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
x1 = x2 = borderValue;
}
@@ -1303,8 +1299,8 @@ class Scale extends Element {
}
const scaleLabelFontColor = valueOrDefault(scaleLabel.fontColor, defaults.fontColor);
- const scaleLabelFont = helpers.options._parseFont(scaleLabel);
- const scaleLabelPadding = helpers.options.toPadding(scaleLabel.padding);
+ const scaleLabelFont = _parseFont(scaleLabel);
+ const scaleLabelPadding = toPadding(scaleLabel.padding);
const halfLineHeight = scaleLabelFont.lineHeight / 2;
const scaleLabelAlign = scaleLabel.align;
const position = options.position;
@@ -1436,7 +1432,7 @@ class Scale extends Element {
tick: me.ticks[index],
index: index
};
- return helpers.extend(helpers.options._parseFont({
+ return extend(_parseFont({
fontFamily: resolve([options.fontFamily], context),
fontSize: resolve([options.fontSize], context),
fontStyle: resolve([options.fontStyle], context), | true |
Other | chartjs | Chart.js | c667a9ef8571d179a552f6013af2cc108f1d2ac5.json | Move text helpers and reduce scope of imports (#7028) | src/core/core.ticks.js | @@ -1,7 +1,7 @@
'use strict';
-import helpers from '../helpers';
-const math = helpers.math;
+import {isArray} from '../helpers/helpers.core';
+import {log10} from '../helpers/helpers.math';
/**
* Namespace to hold static tick generation functions
@@ -20,15 +20,15 @@ export default {
* @return {string|string[]} the label to display
*/
values: function(value) {
- return helpers.isArray(value) ? value : '' + value;
+ return isArray(value) ? value : '' + value;
},
/**
* Formatter for linear numeric ticks
* @method Chart.Ticks.formatters.linear
* @param tickValue {number} the value to be formatted
* @param index {number} the position of the tickValue parameter in the ticks array
- * @param ticks {number[]} the list of ticks being converted
+ * @param ticks {object[]} the list of ticks being converted
* @return {string} string representation of the tickValue parameter
*/
linear: function(tickValue, index, ticks) {
@@ -43,13 +43,13 @@ export default {
}
}
- var logDelta = math.log10(Math.abs(delta));
+ var logDelta = log10(Math.abs(delta));
var tickString = '';
if (tickValue !== 0) {
var maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));
if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
- var logTick = math.log10(Math.abs(tickValue));
+ var logTick = log10(Math.abs(tickValue));
var numExponential = Math.floor(logTick) - Math.floor(logDelta);
numExponential = Math.max(Math.min(numExponential, 20), 0);
tickString = tickValue.toExponential(numExponential); | true |
Other | chartjs | Chart.js | c667a9ef8571d179a552f6013af2cc108f1d2ac5.json | Move text helpers and reduce scope of imports (#7028) | src/helpers/helpers.canvas.js | @@ -1,5 +1,7 @@
'use strict';
+import {isArray} from './helpers.core';
+
const PI = Math.PI;
const RAD_PER_DEG = PI / 180;
const DOUBLE_PI = PI * 2;
@@ -10,6 +12,69 @@ const TWO_THIRDS_PI = PI * 2 / 3;
/**
* @namespace Chart.helpers.canvas
*/
+
+/**
+ * @private
+ */
+export function _measureText(ctx, data, gc, longest, string) {
+ let textWidth = data[string];
+ if (!textWidth) {
+ textWidth = data[string] = ctx.measureText(string).width;
+ gc.push(string);
+ }
+ if (textWidth > longest) {
+ longest = textWidth;
+ }
+ return longest;
+}
+
+/**
+ * @private
+ */
+export function _longestText(ctx, font, arrayOfThings, cache) {
+ cache = cache || {};
+ var data = cache.data = cache.data || {};
+ var gc = cache.garbageCollect = cache.garbageCollect || [];
+
+ if (cache.font !== font) {
+ data = cache.data = {};
+ gc = cache.garbageCollect = [];
+ cache.font = font;
+ }
+
+ ctx.font = font;
+ var longest = 0;
+ var ilen = arrayOfThings.length;
+ var i, j, jlen, thing, nestedThing;
+ for (i = 0; i < ilen; i++) {
+ thing = arrayOfThings[i];
+
+ // Undefined strings and arrays should not be measured
+ if (thing !== undefined && thing !== null && isArray(thing) !== true) {
+ longest = _measureText(ctx, data, gc, longest, thing);
+ } else if (isArray(thing)) {
+ // if it is an array lets measure each element
+ // to do maybe simplify this function a bit so we can do this more recursively?
+ for (j = 0, jlen = thing.length; j < jlen; j++) {
+ nestedThing = thing[j];
+ // Undefined strings and arrays should not be measured
+ if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) {
+ longest = _measureText(ctx, data, gc, longest, nestedThing);
+ }
+ }
+ }
+ }
+
+ var gcLen = gc.length / 2;
+ if (gcLen > arrayOfThings.length) {
+ for (i = 0; i < gcLen; i++) {
+ delete data[gc[i]];
+ }
+ gc.splice(0, gcLen);
+ }
+ return longest;
+}
+
/**
* Returns the aligned pixel value to avoid anti-aliasing blur
* @param {Chart} chart - The chart instance. | true |
Other | chartjs | Chart.js | c667a9ef8571d179a552f6013af2cc108f1d2ac5.json | Move text helpers and reduce scope of imports (#7028) | src/helpers/index.js | @@ -26,18 +26,6 @@ const colorHelper = !color ?
return color(value);
};
-function measureText(ctx, data, gc, longest, string) {
- var textWidth = data[string];
- if (!textWidth) {
- textWidth = data[string] = ctx.measureText(string).width;
- gc.push(string);
- }
- if (textWidth > longest) {
- longest = textWidth;
- }
- return longest;
-}
-
export default {
...coreHelpers,
canvas,
@@ -133,50 +121,6 @@ export default {
fontString: function(pixelSize, fontStyle, fontFamily) {
return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
},
- longestText: function(ctx, font, arrayOfThings, cache) {
- cache = cache || {};
- var data = cache.data = cache.data || {};
- var gc = cache.garbageCollect = cache.garbageCollect || [];
-
- if (cache.font !== font) {
- data = cache.data = {};
- gc = cache.garbageCollect = [];
- cache.font = font;
- }
-
- ctx.font = font;
- var longest = 0;
- var ilen = arrayOfThings.length;
- var i, j, jlen, thing, nestedThing;
- for (i = 0; i < ilen; i++) {
- thing = arrayOfThings[i];
-
- // Undefined strings and arrays should not be measured
- if (thing !== undefined && thing !== null && coreHelpers.isArray(thing) !== true) {
- longest = measureText(ctx, data, gc, longest, thing);
- } else if (coreHelpers.isArray(thing)) {
- // if it is an array lets measure each element
- // to do maybe simplify this function a bit so we can do this more recursively?
- for (j = 0, jlen = thing.length; j < jlen; j++) {
- nestedThing = thing[j];
- // Undefined strings and arrays should not be measured
- if (nestedThing !== undefined && nestedThing !== null && !coreHelpers.isArray(nestedThing)) {
- longest = measureText(ctx, data, gc, longest, nestedThing);
- }
- }
- }
- }
-
- var gcLen = gc.length / 2;
- if (gcLen > arrayOfThings.length) {
- for (i = 0; i < gcLen; i++) {
- delete data[gc[i]];
- }
- gc.splice(0, gcLen);
- }
- return longest;
- },
- measureText,
color: colorHelper,
getHoverColor: function(colorValue) {
return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ? | true |
Other | chartjs | Chart.js | c667a9ef8571d179a552f6013af2cc108f1d2ac5.json | Move text helpers and reduce scope of imports (#7028) | src/scales/scale.radialLinear.js | @@ -2,6 +2,7 @@
import defaults from '../core/core.defaults';
import helpers from '../helpers/index';
+import {_longestText} from '../helpers/helpers.canvas';
import {isNumber, toDegrees, toRadians, _normalizeAngle} from '../helpers/helpers.math';
import LinearScaleBase from './scale.linearbase';
import Ticks from '../core/core.ticks';
@@ -72,7 +73,7 @@ function getTickBackdropHeight(opts) {
function measureLabelSize(ctx, lineHeight, label) {
if (helpers.isArray(label)) {
return {
- w: helpers.longestText(ctx, ctx.font, label),
+ w: _longestText(ctx, ctx.font, label),
h: label.length * lineHeight
};
} | true |
Other | chartjs | Chart.js | c667a9ef8571d179a552f6013af2cc108f1d2ac5.json | Move text helpers and reduce scope of imports (#7028) | test/specs/core.helpers.tests.js | @@ -27,57 +27,6 @@ describe('Core helper tests', function() {
expect(helpers.uid()).toBe(uid + 3);
});
- it('should return the width of the longest text in an Array and 2D Array', function() {
- var context = window.createMockContext();
- var font = "normal 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
- var arrayOfThings1D = ['FooBar', 'Bar'];
- var arrayOfThings2D = [['FooBar_1', 'Bar_2'], 'Foo_1'];
-
-
- // Regardless 'FooBar' is the longest label it should return (characters * 10)
- expect(helpers.longestText(context, font, arrayOfThings1D, {})).toEqual(60);
- expect(helpers.longestText(context, font, arrayOfThings2D, {})).toEqual(80);
- // We check to make sure we made the right calls to the canvas.
- expect(context.getCalls()).toEqual([{
- name: 'measureText',
- args: ['FooBar']
- }, {
- name: 'measureText',
- args: ['Bar']
- }, {
- name: 'measureText',
- args: ['FooBar_1']
- }, {
- name: 'measureText',
- args: ['Bar_2']
- }, {
- name: 'measureText',
- args: ['Foo_1']
- }]);
- });
-
- it('compare text with current longest and update', function() {
- var context = window.createMockContext();
- var data = {};
- var gc = [];
- var longest = 70;
-
- expect(helpers.measureText(context, data, gc, longest, 'foobar')).toEqual(70);
- expect(helpers.measureText(context, data, gc, longest, 'foobar_')).toEqual(70);
- expect(helpers.measureText(context, data, gc, longest, 'foobar_1')).toEqual(80);
- // We check to make sure we made the right calls to the canvas.
- expect(context.getCalls()).toEqual([{
- name: 'measureText',
- args: ['foobar']
- }, {
- name: 'measureText',
- args: ['foobar_']
- }, {
- name: 'measureText',
- args: ['foobar_1']
- }]);
- });
-
describe('Color helper', function() {
function isColorInstance(obj) {
return typeof obj === 'object' && Object.prototype.hasOwnProperty.call(obj, 'values') && Object.prototype.hasOwnProperty.call(obj.values, 'rgb'); | true |
Other | chartjs | Chart.js | c667a9ef8571d179a552f6013af2cc108f1d2ac5.json | Move text helpers and reduce scope of imports (#7028) | test/specs/helpers.canvas.tests.js | @@ -36,4 +36,55 @@ describe('Chart.helpers.canvas', function() {
expect(isPointInArea({x: 0, y: 256.5}, area)).toBe(false);
});
});
+
+ it('should return the width of the longest text in an Array and 2D Array', function() {
+ var context = window.createMockContext();
+ var font = "normal 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
+ var arrayOfThings1D = ['FooBar', 'Bar'];
+ var arrayOfThings2D = [['FooBar_1', 'Bar_2'], 'Foo_1'];
+
+
+ // Regardless 'FooBar' is the longest label it should return (characters * 10)
+ expect(helpers.canvas._longestText(context, font, arrayOfThings1D, {})).toEqual(60);
+ expect(helpers.canvas._longestText(context, font, arrayOfThings2D, {})).toEqual(80);
+ // We check to make sure we made the right calls to the canvas.
+ expect(context.getCalls()).toEqual([{
+ name: 'measureText',
+ args: ['FooBar']
+ }, {
+ name: 'measureText',
+ args: ['Bar']
+ }, {
+ name: 'measureText',
+ args: ['FooBar_1']
+ }, {
+ name: 'measureText',
+ args: ['Bar_2']
+ }, {
+ name: 'measureText',
+ args: ['Foo_1']
+ }]);
+ });
+
+ it('compare text with current longest and update', function() {
+ var context = window.createMockContext();
+ var data = {};
+ var gc = [];
+ var longest = 70;
+
+ expect(helpers.canvas._measureText(context, data, gc, longest, 'foobar')).toEqual(70);
+ expect(helpers.canvas._measureText(context, data, gc, longest, 'foobar_')).toEqual(70);
+ expect(helpers.canvas._measureText(context, data, gc, longest, 'foobar_1')).toEqual(80);
+ // We check to make sure we made the right calls to the canvas.
+ expect(context.getCalls()).toEqual([{
+ name: 'measureText',
+ args: ['foobar']
+ }, {
+ name: 'measureText',
+ args: ['foobar_']
+ }, {
+ name: 'measureText',
+ args: ['foobar_1']
+ }]);
+ });
}); | true |
Other | chartjs | Chart.js | aefbd6f9f34a325a36c2c57c96904f15d06c3d51.json | Remove unused variable (#7031) | src/scales/scale.time.js | @@ -609,7 +609,6 @@ class TimeScale extends Scale {
: determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
: determineMajorUnit(me._unit);
- me._numIndices = ticks.length;
me._table = buildLookupTable(getTimestampsForTable(me), min, max, distribution);
me._offsets = computeOffsets(me._table, ticks, min, max, options);
| false |
Other | chartjs | Chart.js | cb6d7f80d133f159df866548be72c642e6f82c62.json | Fix binarySearch for empty dataset (#7023) | src/core/core.interaction.js | @@ -52,7 +52,7 @@ function evaluateAllVisibleItems(chart, handler) {
function binarySearch(metaset, axis, value, intersect) {
const {controller, data, _sorted} = metaset;
const iScale = controller._cachedMeta.iScale;
- if (iScale && axis === iScale.axis && _sorted) {
+ if (iScale && axis === iScale.axis && _sorted && data.length) {
const lookupMethod = iScale._reversePixels ? _rlookup : _lookup;
if (!intersect) {
return lookupMethod(data, axis, value); | false |
Other | chartjs | Chart.js | fe3931b0775a91b1661df8ca708c572d571f4b73.json | Reduce scope of imports (#7000) | src/controllers/controller.bar.js | @@ -2,7 +2,7 @@
import DatasetController from '../core/core.datasetController';
import defaults from '../core/core.defaults';
-import elements from '../elements';
+import Rectangle from '../elements/element.rectangle';
import helpers from '../helpers';
const valueOrDefault = helpers.valueOrDefault;
@@ -184,7 +184,7 @@ function isFloatBar(custom) {
export default DatasetController.extend({
- dataElementType: elements.Rectangle,
+ dataElementType: Rectangle,
/**
* @private | true |
Other | chartjs | Chart.js | fe3931b0775a91b1661df8ca708c572d571f4b73.json | Reduce scope of imports (#7000) | src/controllers/controller.bubble.js | @@ -2,7 +2,7 @@
import DatasetController from '../core/core.datasetController';
import defaults from '../core/core.defaults';
-import elements from '../elements';
+import Point from '../elements/element.point';
import helpers from '../helpers';
const resolve = helpers.options.resolve;
@@ -38,7 +38,7 @@ export default DatasetController.extend({
/**
* @protected
*/
- dataElementType: elements.Point,
+ dataElementType: Point,
/**
* @private | true |
Other | chartjs | Chart.js | fe3931b0775a91b1661df8ca708c572d571f4b73.json | Reduce scope of imports (#7000) | src/controllers/controller.doughnut.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 valueOrDefault = helpers.valueOrDefault;
@@ -100,7 +100,7 @@ defaults._set('doughnut', {
export default DatasetController.extend({
- dataElementType: elements.Arc,
+ dataElementType: Arc,
linkScales: helpers.noop,
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.