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
51b051f766c309fd04fbd94556ec5c738c6d153f.json
Improve issue templates (#10038) * Make issue templates fancier * should be valid yml now * remove title field * remove reproducable sample for docs * add example back to docs, change link for plugin and add TS link for TS issues * wrong labels, forgot type: in front of it * implement feedback * gramar, missing word
.github/ISSUE_TEMPLATE/DOCS.md
@@ -1,25 +0,0 @@ ---- -name: Documentation -about: Are the docs lacking or missing something? -labels: 'type: documentation' ---- - -Documentation Is: - -<!-- Please place an x (no spaces!) in all [ ] that apply --> - -- [ ] Missing or needed -- [ ] Confusing -- [ ] Not Sure? - -### Please Explain in Detail... - - -### Your Proposal for Changes - - -### Example -<!-- - Provide a link to a live example demonstrating the issue or feature to be documented: - https://codepen.io/pen?template=wvezeOq --->
true
Other
chartjs
Chart.js
51b051f766c309fd04fbd94556ec5c738c6d153f.json
Improve issue templates (#10038) * Make issue templates fancier * should be valid yml now * remove title field * remove reproducable sample for docs * add example back to docs, change link for plugin and add TS link for TS issues * wrong labels, forgot type: in front of it * implement feedback * gramar, missing word
.github/ISSUE_TEMPLATE/FEATURE.md
@@ -1,25 +0,0 @@ ---- -name: Feature Request -about: Suggest an idea -labels: 'type: enhancement' ---- - -<!-- - Most features should start as plugins outside of Chart.js - (https://www.chartjs.org/docs/#advanced-usage-creating-plugins). - Please consider whether your changes are useful for all users, or if this is - specific to your usecase and a Chart.js plugin would be more appropriate. - - Need help or tech support? Please don't open an issue! - Head to https://stackoverflow.com/questions/tagged/chart.js ---> - -### Feature Proposal -<!-- Tell us how it should work --> - -### Feature Use Case -<!-- What are you trying to accomplish? --> -<!-- Providing context helps us come up with a solution that is most useful in the real world --> - -## Possible Implementation -<!-- Not obligatory, but suggest ideas for how to implement the addition or change -->
true
Other
chartjs
Chart.js
51b051f766c309fd04fbd94556ec5c738c6d153f.json
Improve issue templates (#10038) * Make issue templates fancier * should be valid yml now * remove title field * remove reproducable sample for docs * add example back to docs, change link for plugin and add TS link for TS issues * wrong labels, forgot type: in front of it * implement feedback * gramar, missing word
.github/ISSUE_TEMPLATE/SUPPORT.md
@@ -1,27 +0,0 @@ ---- -name: Support, Help, and Advice -about: Need help or support? Head to https://stackoverflow.com/questions/tagged/chart.js -labels: 'type: support' ---- - -<!-- - Hey there! - - If you need help or tech support then this is not the place to ask. Please post - a question to https://stackoverflow.com/questions/tagged/chart.js or head over - to our Slack workspace at https://chartjs-slack.herokuapp.com/. - - You maximize your chances of having your question answered if you follow - StackOverflow's guidelines: https://stackoverflow.com/help/how-to-ask. - If your question was not answered on StackOverflow, that does not mean you - should post it here. If you do, it will be immediately closed. - - Chart.js users vastly outnumber our small number of volunteer maintainers and - we try to help as many users as we can, but we may not get to every question. - Chart.js is a community project. You can contribute towards the goal of helping - every user by asking good questions, answering questions on StackOverflow - or Slack, creating an issue or pull request for the documentation, or otherwise - contributing to the project: - - https://www.chartjs.org/docs/latest/developers/contributing.html --->
true
Other
chartjs
Chart.js
51b051f766c309fd04fbd94556ec5c738c6d153f.json
Improve issue templates (#10038) * Make issue templates fancier * should be valid yml now * remove title field * remove reproducable sample for docs * add example back to docs, change link for plugin and add TS link for TS issues * wrong labels, forgot type: in front of it * implement feedback * gramar, missing word
.github/ISSUE_TEMPLATE/bug.yml
@@ -0,0 +1,84 @@ +name: Bug Report +description: Something went awry +labels: ["type: bug"] +body: + - type: markdown + attributes: + value: | + Need help or support? + Please don't open an issue! Head to https://stackoverflow.com/questions/tagged/chart.js. + + - type: markdown + attributes: + value: "Bug reports MUST be submitted with an interactive example: https://codepen.io/pen?template=BapRepQ." + + - type: markdown + attributes: + value: Chart.js versions lower then 3.x are NOT supported anymore, new issues will be disregarded. + + - type: textarea + attributes: + label: Expected behavior + description: Tell us what should happen. + validations: + required: true + + - type: textarea + attributes: + label: Current behavior + description: Tell us what happens instead of the expected behavior. + validations: + required: true + + - type: input + attributes: + label: Reproducible sample + description: | + Please provide issue reproduction. + You can use [this codepen](https://codepen.io/pen?template=BapRepQ) to make a reproducible sample. + + Major framework wrappers for chart.js templates: + [vue-chart-3 sandbox (Vue)](https://codesandbox.io/s/vue-chart-3-chart-js-issue-template-bpg7k?file=/src/App.vue) + [ng2-charts sandbox (Angular)](https://codesandbox.io/s/ng2charts-chart-js-issue-template-fhezt?file=/src/app/app.component.ts) + [react-chartjs-2 sandbox (React)](https://codesandbox.io/s/react-chartjs-2-chart-js-issue-template-cg7b5?file=/src/App.tsx) + + For typescript issues you can make use of [this TS Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAbzgYQBYENZwL5wGZQQhwDkAxhrAHQBWAziQNwCwAUGwG6ZxkwAecALxwAJhDIBXEAFMAdjCoBzaTACiAG2kz5AIQCeASREAKAEQg9aTDFMBKOOjpwAEgBUAsgBlk6WVzoaWnIwLKxcUHAWVljCstIA7iiUMMa8fAA0iGxwOXAwemDSAFyk6sBxJOnZuSLoMOglCNW5ueroAEbS6nQlANqmAErSIqaZpjrqEtKjcKYAml3qEPEzpgDiUNJyqwAKElBgmqsA8lC+yqYAulWsLS219XQqPXC9Tbd3n22d6iUkAMRwCB4OAANQgMGkDBun0+DwarwAjAAmTKIgCcmQAzJkAKyZVFwLHXZp3bCXUnYGG5CBgGDACCyF7vT50MjoTTM0ktPiNbl3fk5KmCuB6PkfWFwEXYfkyiU4NjYWyMIA) to make a reproducible sample. + + If filing a bug against `master`, you may reference the latest code via + https://www.chartjs.org/dist/master/chart.min.js (changing the filename to + point at the file you need as appropriate). Do not rely on these files for + production purposes as they may be removed at any time. + validations: + required: true + + - type: textarea + attributes: + label: Optional extra steps/info to reproduce + + - type: textarea + attributes: + label: Possible solution + description: If you have suggestions on a fix for the bug. + + - type: textarea + attributes: + label: Context + description: | + How has this issue affected you? What are you trying to accomplish? + Providing context helps us come up with a solution that is most useful in the real world. + + - type: input + attributes: + label: chart.js version + description: Which version of `chart.js` are you using? + placeholder: "v0.0.0" + validations: + required: true + + - type: input + attributes: + label: Browser name and version + + - type: input + attributes: + label: Link to your project
true
Other
chartjs
Chart.js
51b051f766c309fd04fbd94556ec5c738c6d153f.json
Improve issue templates (#10038) * Make issue templates fancier * should be valid yml now * remove title field * remove reproducable sample for docs * add example back to docs, change link for plugin and add TS link for TS issues * wrong labels, forgot type: in front of it * implement feedback * gramar, missing word
.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Support, Help, and Advice + url: https://stackoverflow.com/questions/tagged/chart.js + about: Need help or support? Head to https://stackoverflow.com/questions/tagged/chart.js
true
Other
chartjs
Chart.js
51b051f766c309fd04fbd94556ec5c738c6d153f.json
Improve issue templates (#10038) * Make issue templates fancier * should be valid yml now * remove title field * remove reproducable sample for docs * add example back to docs, change link for plugin and add TS link for TS issues * wrong labels, forgot type: in front of it * implement feedback * gramar, missing word
.github/ISSUE_TEMPLATE/docs.yml
@@ -0,0 +1,31 @@ +name: Documentation +description: Are the docs lacking or missing something? +labels: ["type: documentation"] +body: + - type: checkboxes + attributes: + label: "Documentation Is:" + options: + - label: Missing or needed? + - label: Confusing + - label: Not sure? + + - type: textarea + attributes: + label: Please Explain in Detail... + validations: + required: true + + - type: textarea + attributes: + label: Your Proposal for Changes + validations: + required: true + + - type: input + attributes: + label: Example + description: | + Provide a link to a live example demonstrating the issue or feature to be documented: + Normal: https://codepen.io/pen?template=BapRepQ + TS: [TS Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAbzgYQBYENZwL5wGZQQhwDkAxhrAHQBWAziQNwCwAUGwG6ZxkwAecALxwAJhDIBXEAFMAdjCoBzaTACiAG2kz5AIQCeASREAKAEQg9aTDFMBKOOjpwAEgBUAsgBlk6WVzoaWnIwLKxcUHAWVljCstIA7iiUMMa8fAA0iGxwOXAwemDSAFyk6sBxJOnZuSLoMOglCNW5ueroAEbS6nQlANqmAErSIqaZpjrqEtKjcKYAml3qEPEzpgDiUNJyqwAKElBgmqsA8lC+yqYAulWsLS219XQqPXC9Tbd3n22d6iUkAMRwCB4OAANQgMGkDBun0+DwarwAjAAmTKIgCcmQAzJkAKyZVFwLHXZp3bCXUnYGG5CBgGDACCyF7vT50MjoTTM0ktPiNbl3fk5KmCuB6PkfWFwEXYfkyiU4NjYWyMIA)
true
Other
chartjs
Chart.js
51b051f766c309fd04fbd94556ec5c738c6d153f.json
Improve issue templates (#10038) * Make issue templates fancier * should be valid yml now * remove title field * remove reproducable sample for docs * add example back to docs, change link for plugin and add TS link for TS issues * wrong labels, forgot type: in front of it * implement feedback * gramar, missing word
.github/ISSUE_TEMPLATE/feature.yml
@@ -0,0 +1,28 @@ +name: Feature Request +description: Suggest an idea +labels: ["type: enhancement"] +body: + - type: markdown + attributes: + value: | + Most features should start as plugins outside of Chart.js + (https://www.chartjs.org/docs/latest/developers/plugins.html). + Please consider whether your changes are useful for all users, or if this is + specific to your usecase and a Chart.js plugin would be more appropriate. + + Need help or tech support? Please don't open an issue! + Head to https://stackoverflow.com/questions/tagged/chart.js + + - type: textarea + attributes: + label: Feature Proposal + description: | + What are you trying to accomplish? + Providing context helps us come up with a solution that is most useful in the real world + validations: + required: true + + - type: textarea + attributes: + label: Possible Implementation + description: Not obligatory, but suggest ideas for how to implement the addition or change
true
Other
chartjs
Chart.js
f1c99316a714df4637e3d983184c2b680cba2ae5.json
radialLinear: Hide pointLabels of hidden data (#10018) * radialLinear: Hide pointLabels of hidden data * filter after map
src/scales/scale.radialLinear.js
@@ -86,7 +86,7 @@ function fitWithPointLabels(scale) { const labelSizes = []; const padding = []; - const valueCount = scale.getLabels().length; + const valueCount = scale._pointLabels.length; for (let i = 0; i < valueCount; i++) { const opts = scale.options.pointLabels.setContext(scale.getPointLabelContext(i)); padding[i] = opts.padding; @@ -129,7 +129,7 @@ function fitWithPointLabels(scale) { function buildPointLabelItems(scale, labelSizes, padding) { const items = []; - const valueCount = scale.getLabels().length; + const valueCount = scale._pointLabels.length; const opts = scale.options; const tickBackdropHeight = getTickBackdropHeight(opts); const outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max); @@ -321,10 +321,12 @@ export default class RadialLinearScale extends LinearScaleBase { LinearScaleBase.prototype.generateTickLabels.call(this, ticks); // Point labels - this._pointLabels = this.getLabels().map((value, index) => { - const label = callCallback(this.options.pointLabels.callback, [value, index], this); - return label || label === 0 ? label : ''; - }); + this._pointLabels = this.getLabels() + .map((value, index) => { + const label = callCallback(this.options.pointLabels.callback, [value, index], this); + return label || label === 0 ? label : ''; + }) + .filter((v, i) => this.chart.getDataVisibility(i)); } fit() { @@ -369,7 +371,7 @@ export default class RadialLinearScale extends LinearScaleBase { } getIndexAngle(index) { - const angleMultiplier = TAU / this.getLabels().length; + const angleMultiplier = TAU / this._pointLabels.length; const startAngle = this.options.startAngle || 0; return _normalizeAngle(index * angleMultiplier + toRadians(startAngle)); } @@ -441,7 +443,7 @@ export default class RadialLinearScale extends LinearScaleBase { const ctx = this.ctx; ctx.save(); ctx.beginPath(); - pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this.getLabels().length); + pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length); ctx.closePath(); ctx.fillStyle = backgroundColor; ctx.fill(); @@ -456,7 +458,7 @@ export default class RadialLinearScale extends LinearScaleBase { const ctx = this.ctx; const opts = this.options; const {angleLines, grid} = opts; - const labelCount = this.getLabels().length; + const labelCount = this._pointLabels.length; let i, offset, position; @@ -477,7 +479,7 @@ export default class RadialLinearScale extends LinearScaleBase { if (angleLines.display) { ctx.save(); - for (i = this.getLabels().length - 1; i >= 0; i--) { + for (i = labelCount - 1; i >= 0; i--) { const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i)); const {color, lineWidth} = optsAtIndex;
true
Other
chartjs
Chart.js
f1c99316a714df4637e3d983184c2b680cba2ae5.json
radialLinear: Hide pointLabels of hidden data (#10018) * radialLinear: Hide pointLabels of hidden data * filter after map
test/specs/scale.radialLinear.tests.js
@@ -369,6 +369,22 @@ describe('Test the radial linear scale', function() { expect(chart.scales.r._pointLabels).toEqual([0, '', '', '', '', '']); }); + it('Should build point labels considering hidden data', function() { + const chart = window.acquireChart({ + type: 'polarArea', + data: { + datasets: [{ + data: [10, 5, 0, 25, 78, 20] + }], + labels: ['a', 'b', 'c', 'd', 'e', 'f'] + } + }); + chart.toggleDataVisibility(3); + chart.update(); + + expect(chart.scales.r._pointLabels).toEqual(['a', 'b', 'c', 'e', 'f']); + }); + it('should correctly set the center point', function() { var chart = window.acquireChart({ type: 'radar',
true
Other
chartjs
Chart.js
5bea389c42b949ca6ebdabf1706295d126ea5f4b.json
Add random seed reporting to test runs (#9977)
karma.conf.js
@@ -1,3 +1,4 @@ +const jasmineSeedReporter = require('./test/seed-reporter'); const commonjs = require('@rollup/plugin-commonjs'); const istanbul = require('rollup-plugin-istanbul'); const json = require('@rollup/plugin-json'); @@ -30,7 +31,8 @@ module.exports = function(karma) { karma.set({ frameworks: ['jasmine'], - reporters: ['spec', 'kjhtml'], + plugins: ['karma-*', jasmineSeedReporter], + reporters: ['spec', 'kjhtml', 'jasmine-seed'], browsers: (args.browsers || 'chrome,firefox').split(','), logLevel: karma.LOG_INFO,
true
Other
chartjs
Chart.js
5bea389c42b949ca6ebdabf1706295d126ea5f4b.json
Add random seed reporting to test runs (#9977)
test/seed-reporter.js
@@ -0,0 +1,13 @@ +const SeedReporter = function(baseReporterDecorator) { + baseReporterDecorator(this); + + this.onBrowserComplete = function(browser, result) { + if (result.order && result.order.random && result.order.seed) { + this.write('%s: Randomized with seed %s\n', browser, result.order.seed); + } + }; +}; + +module.exports = { + 'reporter:jasmine-seed': ['type', SeedReporter] +};
true
Other
chartjs
Chart.js
ba6b446b043f8806a2c9a7420516c9b0934b6c3d.json
Limit active element changes to chartArea (#9970) * Limit active element changes to chartArea * CC, remove duplicate ChartEvent interface * CC2
src/core/core.controller.js
@@ -7,14 +7,14 @@ import PluginService from './core.plugins'; import registry from './core.registry'; import Config, {determineAxis, getIndexAxis} from './core.config'; import {retinaScale, _isDomSupported} from '../helpers/helpers.dom'; -import {each, callback as callCallback, uid, valueOrDefault, _elementsEqual, isNullOrUndef, setsEqual, defined, isFunction} from '../helpers/helpers.core'; +import {each, callback as callCallback, uid, valueOrDefault, _elementsEqual, isNullOrUndef, setsEqual, defined, isFunction, _isClickEvent} from '../helpers/helpers.core'; import {clearCanvas, clipArea, createContext, unclipArea, _isPointInArea} from '../helpers'; // @ts-ignore import {version} from '../../package.json'; import {debounce} from '../helpers/helpers.extras'; /** - * @typedef { import("../platform/platform.base").ChartEvent } ChartEvent + * @typedef { import('../../types/index.esm').ChartEvent } ChartEvent */ const KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea']; @@ -83,6 +83,22 @@ function moveNumericKeys(obj, start, move) { } } +/** + * @param {ChartEvent} e + * @param {ChartEvent|null} lastEvent + * @param {boolean} inChartArea + * @param {boolean} isClick + * @returns {ChartEvent|null} + */ +function determineLastEvent(e, lastEvent, inChartArea, isClick) { + if (!inChartArea || e.type === 'mouseout') { + return null; + } + if (isClick) { + return lastEvent; + } + return e; +} class Chart { @@ -1109,14 +1125,19 @@ class Chart { * @private */ _eventHandler(e, replay) { - const args = {event: e, replay, cancelable: true}; + const args = { + event: e, + replay, + cancelable: true, + inChartArea: _isPointInArea(e, this.chartArea, this._minPadding) + }; const eventFilter = (plugin) => (plugin.options.events || this.options.events).includes(e.native.type); if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) { return; } - const changed = this._handleEvent(e, replay); + const changed = this._handleEvent(e, replay, args.inChartArea); args.cancelable = false; this.notifyPlugins('afterEvent', args, eventFilter); @@ -1132,12 +1153,12 @@ class Chart { * Handle an event * @param {ChartEvent} e the event to handle * @param {boolean} [replay] - true if the event was replayed by `update` + * @param {boolean} [inChartArea] - true if the event is inside chartArea * @return {boolean} true if the chart needs to re-render * @private */ - _handleEvent(e, replay) { + _handleEvent(e, replay, inChartArea) { const {_active: lastActive = [], options} = this; - const hoverOptions = options.hover; // If the event is replayed from `update`, we should evaluate with the final positions. // @@ -1153,30 +1174,24 @@ class Chart { // This is done so we do not have to evaluate the active elements each animation frame // - it would be expensive. const useFinalPosition = replay; + const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition); + const isClick = _isClickEvent(e); + const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick); - let active = []; - let changed = false; - let lastEvent = null; + if (inChartArea) { + // Set _lastEvent to null while we are processing the event handlers. + // This prevents recursion if the handler calls chart.update() + this._lastEvent = null; - // Find Active Elements for hover and tooltips - if (e.type !== 'mouseout') { - active = this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition); - lastEvent = e.type === 'click' ? this._lastEvent : e; - } - // Set _lastEvent to null while we are processing the event handlers. - // This prevents recursion if the handler calls chart.update() - this._lastEvent = null; - - if (_isPointInArea(e, this.chartArea, this._minPadding)) { // Invoke onHover hook callCallback(options.onHover, [e, active, this], this); - if (e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu') { + if (isClick) { callCallback(options.onClick, [e, active, this], this); } } - changed = !_elementsEqual(active, lastActive); + const changed = !_elementsEqual(active, lastActive); if (changed || replay) { this._active = active; this._updateHoverStyles(active, lastActive, replay); @@ -1186,6 +1201,28 @@ class Chart { return changed; } + + /** + * @param {ChartEvent} e - The event + * @param {import('../../types/index.esm').ActiveElement[]} lastActive - Previously active elements + * @param {boolean} inChartArea - Is the envent inside chartArea + * @param {boolean} useFinalPosition - Should the evaluation be done with current or final (after animation) element positions + * @returns {import('../../types/index.esm').ActiveElement[]} - The active elements + * @pravate + */ + _getActiveElements(e, lastActive, inChartArea, useFinalPosition) { + if (e.type === 'mouseout') { + return []; + } + + if (!inChartArea) { + // Let user control the active elements outside chartArea. Eg. using Legend. + return lastActive; + } + + const hoverOptions = this.options.hover; + return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition); + } } // @ts-ignore
true
Other
chartjs
Chart.js
ba6b446b043f8806a2c9a7420516c9b0934b6c3d.json
Limit active element changes to chartArea (#9970) * Limit active element changes to chartArea * CC, remove duplicate ChartEvent interface * CC2
src/core/core.interaction.js
@@ -5,7 +5,7 @@ import {_angleBetween, getAngleFromPoint} from '../helpers/helpers.math'; /** * @typedef { import("./core.controller").default } Chart - * @typedef { import("../platform/platform.base").ChartEvent } ChartEvent + * @typedef { import("../../types/index.esm").ChartEvent } ChartEvent * @typedef {{axis?: string, intersect?: boolean}} InteractionOptions * @typedef {{datasetIndex: number, index: number, element: import("./core.element").default}} InteractionItem */
true
Other
chartjs
Chart.js
ba6b446b043f8806a2c9a7420516c9b0934b6c3d.json
Limit active element changes to chartArea (#9970) * Limit active element changes to chartArea * CC, remove duplicate ChartEvent interface * CC2
src/core/core.plugins.js
@@ -3,7 +3,7 @@ import {callback as callCallback, isNullOrUndef, valueOrDefault} from '../helper /** * @typedef { import("./core.controller").default } Chart - * @typedef { import("../platform/platform.base").ChartEvent } ChartEvent + * @typedef { import("../../types/index.esm").ChartEvent } ChartEvent * @typedef { import("../plugins/plugin.tooltip").default } Tooltip */
true
Other
chartjs
Chart.js
ba6b446b043f8806a2c9a7420516c9b0934b6c3d.json
Limit active element changes to chartArea (#9970) * Limit active element changes to chartArea * CC, remove duplicate ChartEvent interface * CC2
src/helpers/helpers.core.js
@@ -340,3 +340,12 @@ export const setsEqual = (a, b) => { return true; }; + +/** + * @param {import('../../types/index.esm').ChartEvent} e - The event + * @returns {boolean} + * @private + */ +export function _isClickEvent(e) { + return e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu'; +}
true
Other
chartjs
Chart.js
ba6b446b043f8806a2c9a7420516c9b0934b6c3d.json
Limit active element changes to chartArea (#9970) * Limit active element changes to chartArea * CC, remove duplicate ChartEvent interface * CC2
src/platform/platform.base.js
@@ -81,14 +81,3 @@ export default class BasePlatform { // no-op } } - -/** - * @interface ChartEvent - * @typedef {object} ChartEvent - * @prop {string} type - The event type name, possible values are: - * 'contextmenu', 'mouseenter', 'mousedown', 'mousemove', 'mouseup', 'mouseout', - * 'click', 'dblclick', 'keydown', 'keypress', 'keyup' and 'resize' - * @prop {*} native - The original native event (null for emulated events, e.g. 'resize') - * @prop {number} x - The mouse x position, relative to the canvas (null for incompatible events) - * @prop {number} y - The mouse y position, relative to the canvas (null for incompatible events) - */
true
Other
chartjs
Chart.js
ba6b446b043f8806a2c9a7420516c9b0934b6c3d.json
Limit active element changes to chartArea (#9970) * Limit active element changes to chartArea * CC, remove duplicate ChartEvent interface * CC2
src/plugins/plugin.legend.js
@@ -10,7 +10,7 @@ import { import {_toLeftRightCenter, _alignStartEnd, _textX} from '../helpers/helpers.extras'; import {toTRBLCorners} from '../helpers/helpers.options'; /** - * @typedef { import("../platform/platform.base").ChartEvent } ChartEvent + * @typedef { import("../../types/index.esm").ChartEvent } ChartEvent */ const getBoxSize = (labelOpts, fontSize) => {
true
Other
chartjs
Chart.js
ba6b446b043f8806a2c9a7420516c9b0934b6c3d.json
Limit active element changes to chartArea (#9970) * Limit active element changes to chartArea * CC, remove duplicate ChartEvent interface * CC2
src/plugins/plugin.tooltip.js
@@ -9,7 +9,7 @@ import {createContext, drawPoint} from '../helpers'; /** * @typedef { import("../platform/platform.base").Chart } Chart - * @typedef { import("../platform/platform.base").ChartEvent } ChartEvent + * @typedef { import("../../types/index.esm").ChartEvent } ChartEvent * @typedef { import("../../types/index.esm").ActiveElement } ActiveElement */ @@ -1012,29 +1012,21 @@ export class Tooltip extends Element { * Handle an event * @param {ChartEvent} e - The event to handle * @param {boolean} [replay] - This is a replayed event (from update) + * @param {boolean} [inChartArea] - The event is indide chartArea * @returns {boolean} true if the tooltip changed */ - handleEvent(e, replay) { + handleEvent(e, replay, inChartArea = true) { const options = this.options; const lastActive = this._active || []; - let changed = false; - let active = []; - - // Find Active Elements for tooltips - if (e.type !== 'mouseout') { - active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay); - if (options.reverse) { - active.reverse(); - } - } + const active = this._getActiveElements(e, lastActive, replay, inChartArea); // When there are multiple items shown, but the tooltip position is nearest mode // an update may need to be made because our position may have changed even though // the items are the same as before. const positionChanged = this._positionChanged(active, e); // Remember Last Actives - changed = replay || !_elementsEqual(active, lastActive) || positionChanged; + const changed = replay || !_elementsEqual(active, lastActive) || positionChanged; // Only handle target event on tooltip change if (changed) { @@ -1053,6 +1045,37 @@ export class Tooltip extends Element { return changed; } + /** + * Helper for determining the active elements for event + * @param {ChartEvent} e - The event to handle + * @param {Element[]} lastActive - Previously active elements + * @param {boolean} [replay] - This is a replayed event (from update) + * @param {boolean} [inChartArea] - The event is indide chartArea + * @returns {Element[]} - Active elements + * @private + */ + _getActiveElements(e, lastActive, replay, inChartArea) { + const options = this.options; + + if (e.type === 'mouseout') { + return []; + } + + if (!inChartArea) { + // Let user control the active elements outside chartArea. Eg. using Legend. + return lastActive; + } + + // Find Active Elements for tooltips + const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay); + + if (options.reverse) { + active.reverse(); + } + + return active; + } + /** * Determine if the active elements + event combination changes the * tooltip position @@ -1117,7 +1140,7 @@ export default { if (chart.tooltip) { // If the event is replayed from `update`, we should evaluate with the final positions. const useFinalPosition = args.replay; - if (chart.tooltip.handleEvent(args.event, useFinalPosition)) { + if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) { // notify chart about the change, so it will render args.changed = true; }
true
Other
chartjs
Chart.js
ba6b446b043f8806a2c9a7420516c9b0934b6c3d.json
Limit active element changes to chartArea (#9970) * Limit active element changes to chartArea * CC, remove duplicate ChartEvent interface * CC2
test/specs/core.controller.tests.js
@@ -361,6 +361,39 @@ describe('Chart', function() { await jasmine.triggerMouseEvent(chart, 'mousemove', point); expect(chart.getActiveElements()).toEqual([]); }); + + it('should not change the active elements when outside chartArea, except for mouseout', async function() { + var chart = acquireChart({ + type: 'line', + data: { + labels: ['A', 'B', 'C', 'D'], + datasets: [{ + data: [10, 20, 30, 100], + hoverRadius: 0 + }], + }, + options: { + scales: { + x: {display: false}, + y: {display: false} + }, + layout: { + padding: 5 + } + } + }); + + var point = chart.getDatasetMeta(0).data[0]; + + await jasmine.triggerMouseEvent(chart, 'mousemove', {x: point.x, y: point.y}); + expect(chart.getActiveElements()).toEqual([{datasetIndex: 0, index: 0, element: point}]); + + await jasmine.triggerMouseEvent(chart, 'mousemove', {x: 1, y: 1}); + expect(chart.getActiveElements()).toEqual([{datasetIndex: 0, index: 0, element: point}]); + + await jasmine.triggerMouseEvent(chart, 'mouseout', {x: 1, y: 1}); + expect(chart.tooltip.getActiveElements()).toEqual([]); + }); }); describe('when merging scale options', function() {
true
Other
chartjs
Chart.js
ba6b446b043f8806a2c9a7420516c9b0934b6c3d.json
Limit active element changes to chartArea (#9970) * Limit active element changes to chartArea * CC, remove duplicate ChartEvent interface * CC2
test/specs/plugin.tooltip.tests.js
@@ -1556,6 +1556,38 @@ describe('Plugin.Tooltip', function() { expect(chart.tooltip.getActiveElements()[0].element).toBe(meta.data[0]); }); + it('should not change the active elements on events outside chartArea, except for mouseout', async function() { + var chart = acquireChart({ + type: 'line', + data: { + labels: ['A', 'B', 'C', 'D'], + datasets: [{ + data: [10, 20, 30, 100] + }], + }, + options: { + scales: { + x: {display: false}, + y: {display: false} + }, + layout: { + padding: 5 + } + } + }); + + var point = chart.getDatasetMeta(0).data[0]; + + await jasmine.triggerMouseEvent(chart, 'mousemove', {x: point.x, y: point.y}); + expect(chart.tooltip.getActiveElements()).toEqual([{datasetIndex: 0, index: 0, element: point}]); + + await jasmine.triggerMouseEvent(chart, 'mousemove', {x: 1, y: 1}); + expect(chart.tooltip.getActiveElements()).toEqual([{datasetIndex: 0, index: 0, element: point}]); + + await jasmine.triggerMouseEvent(chart, 'mouseout', {x: 1, y: 1}); + expect(chart.tooltip.getActiveElements()).toEqual([]); + }); + it('should update active elements when datasets are removed and added', async function() { var dataset = { label: 'Dataset 1',
true
Other
chartjs
Chart.js
ba6b446b043f8806a2c9a7420516c9b0934b6c3d.json
Limit active element changes to chartArea (#9970) * Limit active element changes to chartArea * CC, remove duplicate ChartEvent interface * CC2
types/index.esm.d.ts
@@ -1031,20 +1031,22 @@ export interface Plugin<TType extends ChartType = ChartType, O = AnyObject> exte * @param {object} args - The call arguments. * @param {ChartEvent} args.event - The event object. * @param {boolean} args.replay - True if this event is replayed from `Chart.update` + * @param {boolean} args.inChartArea - The event position is inside chartArea * @param {object} options - The plugin options. */ - beforeEvent?(chart: Chart, args: { event: ChartEvent, replay: boolean, cancelable: true }, options: O): boolean | void; + beforeEvent?(chart: Chart, args: { event: ChartEvent, replay: boolean, cancelable: true, inChartArea: boolean }, options: O): boolean | void; /** * @desc Called after the `event` has been consumed. Note that this hook * will not be called if the `event` has been previously discarded. * @param {Chart} chart - The chart instance. * @param {object} args - The call arguments. * @param {ChartEvent} args.event - The event object. * @param {boolean} args.replay - True if this event is replayed from `Chart.update` + * @param {boolean} args.inChartArea - The event position is inside chartArea * @param {boolean} [args.changed] - Set to true if the plugin needs a render. Should only be changed to true, because this args object is passed through all plugins. * @param {object} options - The plugin options. */ - afterEvent?(chart: Chart, args: { event: ChartEvent, replay: boolean, changed?: boolean, cancelable: false }, options: O): void; + afterEvent?(chart: Chart, args: { event: ChartEvent, replay: boolean, changed?: boolean, cancelable: false, inChartArea: boolean }, options: O): void; /** * @desc Called after the chart as been resized. * @param {Chart} chart - The chart instance.
true
Other
chartjs
Chart.js
d2d5f49953c130253c06621476e0eecdff4544d0.json
Pass object from array as value to _fallback (#9969) * Pass object from array as value to _fallback * cleanup * reduce changes * reduce even more changes
src/helpers/helpers.config.js
@@ -250,12 +250,12 @@ function resolveFallback(fallback, prop, value) { const getScope = (key, parent) => key === true ? parent : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined; -function addScopes(set, parentScopes, key, parentFallback) { +function addScopes(set, parentScopes, key, parentFallback, value) { for (const parent of parentScopes) { const scope = getScope(key, parent); if (scope) { set.add(scope); - const fallback = resolveFallback(scope._fallback, key, scope); + const fallback = resolveFallback(scope._fallback, key, value); if (defined(fallback) && fallback !== key && fallback !== parentFallback) { // When we reach the descriptor that defines a new _fallback, return that. // The fallback will resume to that new scope. @@ -276,12 +276,12 @@ function createSubResolver(parentScopes, resolver, prop, value) { const allScopes = [...parentScopes, ...rootScopes]; const set = new Set(); set.add(value); - let key = addScopesFromKey(set, allScopes, prop, fallback || prop); + let key = addScopesFromKey(set, allScopes, prop, fallback || prop, value); if (key === null) { return false; } if (defined(fallback) && fallback !== prop) { - key = addScopesFromKey(set, allScopes, fallback, key); + key = addScopesFromKey(set, allScopes, fallback, key, value); if (key === null) { return false; } @@ -290,9 +290,9 @@ function createSubResolver(parentScopes, resolver, prop, value) { () => subGetTarget(resolver, prop, value)); } -function addScopesFromKey(set, allScopes, key, fallback) { +function addScopesFromKey(set, allScopes, key, fallback, item) { while (key) { - key = addScopes(set, allScopes, key, fallback); + key = addScopes(set, allScopes, key, fallback, item); } return key; }
true
Other
chartjs
Chart.js
d2d5f49953c130253c06621476e0eecdff4544d0.json
Pass object from array as value to _fallback (#9969) * Pass object from array as value to _fallback * cleanup * reduce changes * reduce even more changes
test/specs/helpers.config.tests.js
@@ -654,6 +654,46 @@ describe('Chart.helpers.config', function() { }); }); + it('should call _fallback with proper value from array when descriptor is object', function() { + const spy = jasmine.createSpy('fallback'); + const descriptors = { + items: { + _fallback: spy + } + }; + const options = { + items: [{test: true}] + }; + const resolver = _createResolver([options, descriptors]); + const opts = _attachContext(resolver, {dymmy: true}); + const item0 = opts.items[0]; + expect(item0.test).toEqual(true); + expect(spy).toHaveBeenCalledWith('items', options.items[0]); + }); + + it('should call _fallback with proper value from array when descriptor and defaults are objects', function() { + const spy = jasmine.createSpy('fallback'); + const descriptors = { + items: { + _fallback: spy + } + }; + const defaults = { + items: { + type: 'defaultType' + } + }; + const options = { + items: [{test: true}] + }; + const resolver = _createResolver([options, defaults, descriptors]); + const opts = _attachContext(resolver, {dymmy: true}); + const item0 = opts.items[0]; + console.warn(opts._proxy._scopes); + expect(item0.test).toEqual(true); + expect(spy).toHaveBeenCalledWith('items', options.items[0]); + }); + it('should support overriding options', function() { const options = { fn1: ctx => ctx.index,
true
Other
chartjs
Chart.js
957ca837d5b5d03f10cdf4b91f67e3d1f3570d9b.json
Specify UTC time zone for the test suite (#9945) The controller.bar/not-grouped/on-time test was failing on my computer because the date ranges happen to cross the end of Daylight Saving Time in the U.S., so chart was generated with one more hour of time than the test fixture expected. Using moment-timezone to specify a fixed time zone with no DST seemed like the most robust fix. (Alternatively, I could pick a date range that doesn't change DST; that ought to work.)
karma.conf.js
@@ -82,6 +82,7 @@ module.exports = function(karma) { {pattern: 'test/fixtures/**/*.json', included: false}, {pattern: 'test/fixtures/**/*.png', included: false}, 'node_modules/moment/min/moment.min.js', + 'node_modules/moment-timezone/builds/moment-timezone-with-data.min.js', {pattern: 'test/index.js', watched: false}, {pattern: 'test/BasicChartWebWorker.js', included: false}, {pattern: 'src/index.js', watched: false},
true
Other
chartjs
Chart.js
957ca837d5b5d03f10cdf4b91f67e3d1f3570d9b.json
Specify UTC time zone for the test suite (#9945) The controller.bar/not-grouped/on-time test was failing on my computer because the date ranges happen to cross the end of Daylight Saving Time in the U.S., so chart was generated with one more hour of time than the test fixture expected. Using moment-timezone to specify a fixed time zone with no DST seemed like the most robust fix. (Alternatively, I could pick a date range that doesn't change DST; that ought to work.)
package-lock.json
@@ -47,6 +47,7 @@ "luxon": "^1.26.0", "markdown-it-include": "^2.0.0", "moment": "^2.29.1", + "moment-timezone": "^0.5.34", "pixelmatch": "^5.2.1", "rollup": "^2.44.0", "rollup-plugin-analyzer": "^4.0.0", @@ -11743,6 +11744,18 @@ "node": "*" } }, + "node_modules/moment-timezone": { + "version": "0.5.34", + "resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.34.tgz", + "integrity": "sha512-3zAEHh2hKUs3EXLESx/wsgw6IQdusOT8Bxm3D9UrHPQR7zlMmzwybC8zHEM1tQ4LJwP7fcxrWr8tuBg05fFCbg==", + "dev": true, + "dependencies": { + "moment": ">= 2.9.0" + }, + "engines": { + "node": "*" + } + }, "node_modules/move-concurrently": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/move-concurrently/-/move-concurrently-1.0.1.tgz", @@ -28426,6 +28439,15 @@ "integrity": "sha512-kHmoybcPV8Sqy59DwNDY3Jefr64lK/by/da0ViFcuA4DH0vQg5Q6Ze5VimxkfQNSC+Mls/Kx53s7TjP1RhFEDQ==", "dev": true }, + "moment-timezone": { + "version": "0.5.34", + "resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.34.tgz", + "integrity": "sha512-3zAEHh2hKUs3EXLESx/wsgw6IQdusOT8Bxm3D9UrHPQR7zlMmzwybC8zHEM1tQ4LJwP7fcxrWr8tuBg05fFCbg==", + "dev": true, + "requires": { + "moment": ">= 2.9.0" + } + }, "move-concurrently": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/move-concurrently/-/move-concurrently-1.0.1.tgz",
true
Other
chartjs
Chart.js
957ca837d5b5d03f10cdf4b91f67e3d1f3570d9b.json
Specify UTC time zone for the test suite (#9945) The controller.bar/not-grouped/on-time test was failing on my computer because the date ranges happen to cross the end of Daylight Saving Time in the U.S., so chart was generated with one more hour of time than the test fixture expected. Using moment-timezone to specify a fixed time zone with no DST seemed like the most robust fix. (Alternatively, I could pick a date range that doesn't change DST; that ought to work.)
package.json
@@ -87,6 +87,7 @@ "luxon": "^1.26.0", "markdown-it-include": "^2.0.0", "moment": "^2.29.1", + "moment-timezone": "^0.5.34", "pixelmatch": "^5.2.1", "rollup": "^2.44.0", "rollup-plugin-analyzer": "^4.0.0",
true
Other
chartjs
Chart.js
957ca837d5b5d03f10cdf4b91f67e3d1f3570d9b.json
Specify UTC time zone for the test suite (#9945) The controller.bar/not-grouped/on-time test was failing on my computer because the date ranges happen to cross the end of Daylight Saving Time in the U.S., so chart was generated with one more hour of time than the test fixture expected. Using moment-timezone to specify a fixed time zone with no DST seemed like the most robust fix. (Alternatively, I could pick a date range that doesn't change DST; that ought to work.)
test/index.js
@@ -18,6 +18,10 @@ jasmine.fixture = { jasmine.triggerMouseEvent = triggerMouseEvent; +// Set a fixed time zone (and, in particular, disable Daylight Saving Time) for +// more stable test results. +window.moment.tz.setDefault('Etc/UTC'); + beforeEach(function() { addMatchers(); });
true
Other
chartjs
Chart.js
957ca837d5b5d03f10cdf4b91f67e3d1f3570d9b.json
Specify UTC time zone for the test suite (#9945) The controller.bar/not-grouped/on-time test was failing on my computer because the date ranges happen to cross the end of Daylight Saving Time in the U.S., so chart was generated with one more hour of time than the test fixture expected. Using moment-timezone to specify a fixed time zone with no DST seemed like the most robust fix. (Alternatively, I could pick a date range that doesn't change DST; that ought to work.)
test/specs/scale.time.tests.js
@@ -450,8 +450,11 @@ describe('Time scale tests', function() { datasets: [{ xAxisID: 'x', data: [ - {t: +new Date('2018-01-08 05:14:23.234'), y: 10}, - {t: +new Date('2018-01-09 06:17:43.426'), y: 3} + // Normally (at least with the moment.js adapter), times would be in + // the user's local time zone. To allow for more stable tests, our + // tests/index.js sets moment.js to use UTC; use `Z` here to match. + {t: +new Date('2018-01-08 05:14:23.234Z'), y: 10}, + {t: +new Date('2018-01-09 06:17:43.426Z'), y: 3} ] }], }, @@ -1175,7 +1178,7 @@ describe('Time scale tests', function() { } }); - // NOTE: built-in adapter uses moment + // NOTE: the test suite is configured to use moment var expected = { datetime: 'MMM D, YYYY, h:mm:ss a', millisecond: 'h:mm:ss.SSS a', @@ -1213,7 +1216,7 @@ describe('Time scale tests', function() { } }); - // NOTE: built-in adapter uses moment + // NOTE: the test suite is configured to use moment var expected = { datetime: 'MMM D, YYYY, h:mm:ss a', millisecond: 'foo',
true
Other
chartjs
Chart.js
7784fbfded3c01b61bb553b7fc769c12e6513884.json
Support "r" axis for non-intersecting interaction (#9919) * Support "r" axis for non-intersecting interaction * Extract some interaction functionality * Remove whitespace and semicolons * WIP: add interaction test * Update documentation * Fix test * Add another test * Update axis params * Add additional axis check to binary search * Update axis type
docs/configuration/interactions.md
@@ -6,7 +6,7 @@ Namespace: `options.interaction`, the global interaction configuration is at `Ch | ---- | ---- | ------- | ----------- | `mode` | `string` | `'nearest'` | Sets which elements appear in the interaction. See [Interaction Modes](#modes) for details. | `intersect` | `boolean` | `true` | if true, the interaction mode only applies when the mouse position intersects an item on the chart. -| `axis` | `string` | `'x'` | Can be set to `'x'`, `'y'`, or `'xy'` to define which directions are used in calculating distances. Defaults to `'x'` for `'index'` mode and `'xy'` in `dataset` and `'nearest'` modes. +| `axis` | `string` | `'x'` | Can be set to `'x'`, `'y'`, `'xy'` or `'r'` to define which directions are used in calculating distances. Defaults to `'x'` for `'index'` mode and `'xy'` in `dataset` and `'nearest'` modes. By default, these options apply to both the hover and tooltip interactions. The same options can be set in the `options.hover` namespace, in which case they will only affect the hover interaction. Similarly, the options can be set in the `options.plugins.tooltip` namespace to independently configure the tooltip interactions.
true
Other
chartjs
Chart.js
7784fbfded3c01b61bb553b7fc769c12e6513884.json
Support "r" axis for non-intersecting interaction (#9919) * Support "r" axis for non-intersecting interaction * Extract some interaction functionality * Remove whitespace and semicolons * WIP: add interaction test * Update documentation * Fix test * Add another test * Update axis params * Add additional axis check to binary search * Update axis type
src/core/core.interaction.js
@@ -1,6 +1,7 @@ import {_isPointInArea} from '../helpers/helpers.canvas'; import {_lookupByKey, _rlookupByKey} from '../helpers/helpers.collection'; import {getRelativePosition as helpersGetRelativePosition} from '../helpers/helpers.dom'; +import {_angleBetween, getAngleFromPoint} from '../helpers/helpers.math'; /** * @typedef { import("./core.controller").default } Chart @@ -49,15 +50,15 @@ function evaluateAllVisibleItems(chart, handler) { /** * Helper function to do binary search when possible * @param {object} metaset - the dataset meta - * @param {string} axis - the axis mide. x|y|xy + * @param {string} axis - the axis mode. x|y|xy|r * @param {number} value - the value to find * @param {boolean} [intersect] - should the element intersect * @returns {{lo:number, hi:number}} indices to search data array between */ function binarySearch(metaset, axis, value, intersect) { const {controller, data, _sorted} = metaset; const iScale = controller._cachedMeta.iScale; - if (iScale && axis === iScale.axis && _sorted && data.length) { + if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) { const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey; if (!intersect) { return lookupMethod(data, axis, value); @@ -81,7 +82,7 @@ function binarySearch(metaset, axis, value, intersect) { /** * Helper function to get items using binary search, when the data is sorted. * @param {Chart} chart - the chart - * @param {string} axis - the axis mode. x|y|xy + * @param {string} axis - the axis mode. x|y|xy|r * @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 @@ -104,7 +105,7 @@ function optimizedEvaluateItems(chart, axis, position, handler, intersect) { /** * Get a distance metric function for two points based on the * axis mode setting - * @param {string} axis - the axis mode. x|y|xy + * @param {string} axis - the axis mode. x|y|xy|r */ function getDistanceMetricForAxis(axis) { const useX = axis.indexOf('x') !== -1; @@ -121,7 +122,7 @@ function getDistanceMetricForAxis(axis) { * Helper function to get the items that intersect the event position * @param {Chart} chart - the chart * @param {object} position - the point to be nearest to - * @param {string} axis - the axis mode. x|y|xy + * @param {string} axis - the axis mode. x|y|xy|r * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position * @return {InteractionItem[]} the nearest items */ @@ -143,32 +144,55 @@ function getIntersectItems(chart, position, axis, useFinalPosition) { } /** - * Helper function to get the items nearest to the event position considering all visible items in the chart + * Helper function to get the items nearest to the event position for a radial chart * @param {Chart} chart - the chart to look at elements from * @param {object} position - the point to be nearest to * @param {string} axis - the axes along which to measure distance - * @param {boolean} [intersect] - if true, only consider items that intersect the position * @param {boolean} [useFinalPosition] - use the elements animation target instead of current position * @return {InteractionItem[]} the nearest items */ -function getNearestItems(chart, position, axis, intersect, useFinalPosition) { - const distanceMetric = getDistanceMetricForAxis(axis); - let minDistance = Number.POSITIVE_INFINITY; +function getNearestRadialItems(chart, position, axis, useFinalPosition) { let items = []; - if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) { - return items; + function evaluationFunc(element, datasetIndex, index) { + const {startAngle, endAngle} = element.getProps(['startAngle', 'endAngle'], useFinalPosition); + const {angle} = getAngleFromPoint(element, {x: position.x, y: position.y}); + + if (_angleBetween(angle, startAngle, endAngle)) { + items.push({element, datasetIndex, index}); + } } - const evaluationFunc = function(element, datasetIndex, index) { - if (intersect && !element.inRange(position.x, position.y, useFinalPosition)) { + optimizedEvaluateItems(chart, axis, position, evaluationFunc); + return items; +} + +/** + * Helper function to get the items nearest to the event position for a cartesian chart + * @param {Chart} chart - the chart to look at elements from + * @param {object} position - the point to be nearest to + * @param {string} axis - the axes along which to measure distance + * @param {boolean} [intersect] - if true, only consider items that intersect the position + * @param {boolean} [useFinalPosition] - use the elements animation target instead of current position + * @return {InteractionItem[]} the nearest items + */ +function getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition) { + let items = []; + const distanceMetric = getDistanceMetricForAxis(axis); + let minDistance = Number.POSITIVE_INFINITY; + + function evaluationFunc(element, datasetIndex, index) { + const inRange = element.inRange(position.x, position.y, useFinalPosition); + if (intersect && !inRange) { return; } const center = element.getCenterPoint(useFinalPosition); - if (!_isPointInArea(center, chart.chartArea, chart._minPadding) && !element.inRange(position.x, position.y, useFinalPosition)) { + const pointInArea = _isPointInArea(center, chart.chartArea, chart._minPadding); + if (!pointInArea && !inRange) { return; } + const distance = distanceMetric(position, center); if (distance < minDistance) { items = [{element, datasetIndex, index}]; @@ -177,12 +201,31 @@ function getNearestItems(chart, position, axis, intersect, useFinalPosition) { // Can have multiple items at the same distance in which case we sort by size items.push({element, datasetIndex, index}); } - }; + } optimizedEvaluateItems(chart, axis, position, evaluationFunc); return items; } +/** + * 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 {string} axis - the axes along which to measure distance + * @param {boolean} [intersect] - if true, only consider items that intersect the position + * @param {boolean} [useFinalPosition] - use the elements animation target instead of current position + * @return {InteractionItem[]} the nearest items + */ +function getNearestItems(chart, position, axis, intersect, useFinalPosition) { + if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) { + return []; + } + + return axis === 'r' && !intersect + ? getNearestRadialItems(chart, position, axis, useFinalPosition) + : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition); +} + function getAxisItems(chart, e, options, useFinalPosition) { const position = getRelativePosition(e, chart); const items = [];
true
Other
chartjs
Chart.js
7784fbfded3c01b61bb553b7fc769c12e6513884.json
Support "r" axis for non-intersecting interaction (#9919) * Support "r" axis for non-intersecting interaction * Extract some interaction functionality * Remove whitespace and semicolons * WIP: add interaction test * Update documentation * Fix test * Add another test * Update axis params * Add additional axis check to binary search * Update axis type
test/specs/core.interaction.tests.js
@@ -325,7 +325,7 @@ describe('Core.Interaction', function() { describe('nearest mode', function() { describe('intersect: false', function() { beforeEach(function() { - this.chart = window.acquireChart({ + this.lineChart = window.acquireChart({ type: 'line', data: { datasets: [{ @@ -344,11 +344,27 @@ describe('Core.Interaction', function() { labels: ['Point 1', 'Point 2', 'Point 3'] } }); + this.polarChart = window.acquireChart({ + type: 'polarArea', + data: { + datasets: [{ + data: [1, 9, 5] + }], + labels: ['Point 1', 'Point 2', 'Point 3'] + }, + options: { + plugins: { + legend: { + display: false + }, + }, + } + }); }); describe('axis: xy', function() { it ('should return the nearest item', function() { - var chart = this.chart; + var chart = this.lineChart; var evt = { type: 'click', chart: chart, @@ -364,7 +380,7 @@ describe('Core.Interaction', function() { }); it ('should return all items at the same nearest distance', function() { - var chart = this.chart; + var chart = this.lineChart; var meta0 = chart.getDatasetMeta(0); var meta1 = chart.getDatasetMeta(1); @@ -390,7 +406,7 @@ describe('Core.Interaction', function() { describe('axis: x', function() { it ('should return all items at current x', function() { - var chart = this.chart; + var chart = this.lineChart; var meta0 = chart.getDatasetMeta(0); var meta1 = chart.getDatasetMeta(1); @@ -414,7 +430,7 @@ describe('Core.Interaction', function() { }); it ('should return all items at nearest x-distance', function() { - var chart = this.chart; + var chart = this.lineChart; var meta0 = chart.getDatasetMeta(0); var meta1 = chart.getDatasetMeta(1); @@ -440,7 +456,7 @@ describe('Core.Interaction', function() { describe('axis: y', function() { it ('should return item with value 30', function() { - var chart = this.chart; + var chart = this.lineChart; var meta0 = chart.getDatasetMeta(0); // 'Point 1', y = 30 @@ -463,7 +479,7 @@ describe('Core.Interaction', function() { }); it ('should return all items at value 40', function() { - var chart = this.chart; + var chart = this.lineChart; var meta0 = chart.getDatasetMeta(0); var meta1 = chart.getDatasetMeta(1); @@ -486,6 +502,40 @@ describe('Core.Interaction', function() { expect(elements).toEqual([meta0.data[1], meta1.data[0], meta1.data[1], meta1.data[2]]); }); }); + + describe('axis: r', function() { + it ('should return item with value 9', function() { + var chart = this.polarChart; + var meta0 = chart.getDatasetMeta(0); + + var evt = { + type: 'click', + chart: chart, + native: true, // Needed, otherwise assumed to be a DOM event + x: chart.width / 2, + y: chart.height / 2 + 5, + }; + + var elements = Chart.Interaction.modes.nearest(chart, evt, {axis: 'r'}).map(item => item.element); + expect(elements).toEqual([meta0.data[1]]); + }); + + it ('should return item with value 1 when clicked outside of it', function() { + var chart = this.polarChart; + var meta0 = chart.getDatasetMeta(0); + + var evt = { + type: 'click', + chart: chart, + native: true, // Needed, otherwise assumed to be a DOM event + x: chart.width, + y: 0, + }; + + var elements = Chart.Interaction.modes.nearest(chart, evt, {axis: 'r', intersect: false}).map(item => item.element); + expect(elements).toEqual([meta0.data[0]]); + }); + }); }); describe('intersect: true', function() {
true
Other
chartjs
Chart.js
7784fbfded3c01b61bb553b7fc769c12e6513884.json
Support "r" axis for non-intersecting interaction (#9919) * Support "r" axis for non-intersecting interaction * Extract some interaction functionality * Remove whitespace and semicolons * WIP: add interaction test * Update documentation * Fix test * Add another test * Update axis params * Add additional axis check to binary search * Update axis type
types/index.esm.d.ts
@@ -1391,9 +1391,9 @@ export interface CoreInteractionOptions { intersect: boolean; /** - * Can be set to 'x', 'y', or 'xy' to define which directions are used in calculating distances. Defaults to 'x' for 'index' mode and 'xy' in dataset and 'nearest' modes. + * Can be set to 'x', 'y', 'xy' or 'r' to define which directions are used in calculating distances. Defaults to 'x' for 'index' mode and 'xy' in dataset and 'nearest' modes. */ - axis: 'x' | 'y' | 'xy'; + axis: 'x' | 'y' | 'xy' | 'r'; } export interface CoreChartOptions<TType extends ChartType> extends ParsingOptions, AnimationOptions<TType> {
true
Other
chartjs
Chart.js
42e85942a852d3082907e0a8eafb75d3b15e554a.json
Add notes about more specific options for axes (#9923)
docs/axes/cartesian/index.md
@@ -192,6 +192,10 @@ module.exports = { ## Common Configuration +:::tip Note +These are only the common options supported by all cartesian axes. Please see the specific axis documentation for all the available options for that axis. +::: + !!!include(axes/cartesian/_common.md)!!! !!!include(axes/_common.md)!!! @@ -221,6 +225,10 @@ The `bounds` property controls the scale boundary strategy (bypassed by `min`/`m ### Tick Configuration +:::tip Note +These are only the common tick options supported by all cartesian axes. Please see specific axis documentation for all of the available options for that axis. +::: + !!!include(axes/cartesian/_common_ticks.md)!!! !!!include(axes/_common_ticks.md)!!! @@ -285,8 +293,9 @@ module.exports = { :::tip Note The `crossAlign` setting is only effective when these preconditions are met: - * tick rotation is `0` - * axis position is `'top'`, '`left'`, `'bottom'` or `'right'` + +* tick rotation is `0` +* axis position is `'top'`, '`left'`, `'bottom'` or `'right'` ::: ### Axis ID
true
Other
chartjs
Chart.js
42e85942a852d3082907e0a8eafb75d3b15e554a.json
Add notes about more specific options for axes (#9923)
docs/axes/index.md
@@ -93,10 +93,18 @@ let chart = new Chart(ctx, { ## Common Configuration +:::tip Note +These are only the common options supported by all axes. Please see specific axis documentation for all of the available options for that axis. +::: + !!!include(axes/_common.md)!!! ## Tick Configuration +:::tip Note +These are only the common tick options supported by all axes. Please see specific axis documentation for all of the available tick options for that axis. +::: + !!!include(axes/_common_ticks.md)!!! ## Axis Range Settings
true
Other
chartjs
Chart.js
5e5339d01ce0c5b6a28e96624e0d81b71d459d72.json
Update stale documentation for axis titles (#9683) * Update stale documentation for axis titles (#9682) Updated the documentation for the types on axis labels. In the corresponding `index.esm.d.ts` file, put JSDoc descriptions for the properties to match the now-updated documentation. * Clean up axis title labels documentation (#9682) Inserted extra information in the documentation for the type of the padding, inserted missing full stops. In the type file, added JSDoc for undocumented properties. * Update docs/axes/labelling.md * Update types/index.esm.d.ts Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
docs/axes/labelling.md
@@ -13,7 +13,7 @@ Namespace: `options.scales[scaleId].title`, it defines options for the scale tit | `text` | `string`\|`string[]` | `''` | The text for the title. (i.e. "# of People" or "Response Choices"). | `color` | [`Color`](../general/colors.md) | `Chart.defaults.color` | Color of label. | `font` | `Font` | `Chart.defaults.font` | See [Fonts](../general/fonts.md) -| `padding` | [`Padding`](../general/padding.md) | `4` | Padding to apply around scale labels. Only `top` and `bottom` are implemented. +| `padding` | [`Padding`](../general/padding.md) | `4` | Padding to apply around scale labels. Only `top`, `bottom` and `y` are implemented. ## Creating Custom Tick Formats
true
Other
chartjs
Chart.js
5e5339d01ce0c5b6a28e96624e0d81b71d459d72.json
Update stale documentation for axis titles (#9683) * Update stale documentation for axis titles (#9682) Updated the documentation for the types on axis labels. In the corresponding `index.esm.d.ts` file, put JSDoc descriptions for the properties to match the now-updated documentation. * Clean up axis title labels documentation (#9682) Inserted extra information in the documentation for the type of the padding, inserted missing full stops. In the type file, added JSDoc for undocumented properties. * Update docs/axes/labelling.md * Update types/index.esm.d.ts Co-authored-by: Jukka Kurkela <jukka.kurkela@gmail.com>
types/index.esm.d.ts
@@ -2937,15 +2937,26 @@ export interface CartesianScaleOptions extends CoreScaleOptions { grid: GridLineOptions; + /** Options for the scale title. */ title: { + /** If true, displays the axis title. */ display: boolean; + /** Alignment of the axis title. */ align: 'start' | 'center' | 'end'; + /** The text for the title, e.g. "# of People" or "Response Choices". */ text: string | string[]; + /** Color of the axis label. */ color: Color; + /** Information about the axis title font. */ font: FontSpec; + /** Padding to apply around scale labels. */ padding: number | { + /** Padding on the (relative) top side of this axis label. */ top: number; + /** Padding on the (relative) bottom side of this axis label. */ bottom: number; + /** This is a shorthand for defining top/bottom to the same values. */ + y: number; }; };
true
Other
chartjs
Chart.js
bccb1276f023448e2539a49c879c7a97bd83f763.json
Detect detach/attach in same observation (#9876) * Detect detach/attach in same observation * Missing `!`, better tests * reduce duplication
src/platform/platform.dom.js
@@ -114,15 +114,24 @@ function fromNativeEvent(event, chart) { }; } +function nodeListContains(nodeList, canvas) { + for (const node of nodeList) { + if (node === canvas || node.contains(canvas)) { + return true; + } + } +} + function createAttachObserver(chart, type, listener) { const canvas = chart.canvas; const observer = new MutationObserver(entries => { + let trigger = false; for (const entry of entries) { - for (const node of entry.addedNodes) { - if (node === canvas || node.contains(canvas)) { - return listener(); - } - } + trigger = trigger || nodeListContains(entry.addedNodes, canvas); + trigger = trigger && !nodeListContains(entry.removedNodes, canvas); + } + if (trigger) { + listener(); } }); observer.observe(document, {childList: true, subtree: true}); @@ -132,12 +141,13 @@ function createAttachObserver(chart, type, listener) { function createDetachObserver(chart, type, listener) { const canvas = chart.canvas; const observer = new MutationObserver(entries => { + let trigger = false; for (const entry of entries) { - for (const node of entry.removedNodes) { - if (node === canvas || node.contains(canvas)) { - return listener(); - } - } + trigger = trigger || nodeListContains(entry.removedNodes, canvas); + trigger = trigger && !nodeListContains(entry.addedNodes, canvas); + } + if (trigger) { + listener(); } }); observer.observe(document, {childList: true, subtree: true});
true
Other
chartjs
Chart.js
bccb1276f023448e2539a49c879c7a97bd83f763.json
Detect detach/attach in same observation (#9876) * Detect detach/attach in same observation * Missing `!`, better tests * reduce duplication
test/specs/core.controller.tests.js
@@ -1078,6 +1078,108 @@ describe('Chart', function() { }, 0); }); + // https://github.com/chartjs/Chart.js/issues/9875 + it('should detect detach/attach in series', function(done) { + var chart = acquireChart({ + options: { + responsive: true, + maintainAspectRatio: false + } + }, { + canvas: { + style: '' + }, + wrapper: { + style: 'width: 320px; height: 350px' + } + }); + + var wrapper = chart.canvas.parentNode; + var parent = wrapper.parentNode; + + waitForResize(chart, function() { + expect(chart).toBeChartOfSize({ + dw: 320, dh: 350, + rw: 320, rh: 350, + }); + + done(); + }); + + parent.removeChild(wrapper); + parent.appendChild(wrapper); + }); + + it('should detect detach/attach/detach in series', function(done) { + var chart = acquireChart({ + options: { + responsive: true, + maintainAspectRatio: false + } + }, { + canvas: { + style: '' + }, + wrapper: { + style: 'width: 320px; height: 350px' + } + }); + + var wrapper = chart.canvas.parentNode; + var parent = wrapper.parentNode; + + waitForResize(chart, function() { + fail(); + }); + + parent.removeChild(wrapper); + parent.appendChild(wrapper); + parent.removeChild(wrapper); + + setTimeout(function() { + expect(chart.attached).toBeFalse(); + done(); + }, 100); + }); + + it('should detect attach/detach in series', function(done) { + var chart = acquireChart({ + options: { + responsive: true, + maintainAspectRatio: false + } + }, { + canvas: { + style: '' + }, + wrapper: { + style: 'width: 320px; height: 350px' + } + }); + + var wrapper = chart.canvas.parentNode; + var parent = wrapper.parentNode; + + parent.removeChild(wrapper); + + setTimeout(function() { + expect(chart.attached).toBeFalse(); + + waitForResize(chart, function() { + fail(); + }); + + parent.appendChild(wrapper); + parent.removeChild(wrapper); + + setTimeout(function() { + expect(chart.attached).toBeFalse(); + + done(); + }, 100); + }, 100); + }); + // https://github.com/chartjs/Chart.js/issues/4737 it('should resize the canvas when re-creating the chart', function(done) { var chart = acquireChart({
true
Other
chartjs
Chart.js
1107073a9802fd8893e2ee3fa369c5d65beabb48.json
Fix a typo in index.md (#9900) Fix a typo
docs/developers/index.md
@@ -43,7 +43,7 @@ Version 3 has a largely different API than earlier versions. Most earlier version options have current equivalents or are the same. -Please note - documentation for previous versions are available online or in the GitHub repo. +Please note - documentation for previous versions is available online or in the GitHub repo. - [2.9.4 Documentation](https://www.chartjs.org/docs/2.9.4/) - [1.x Documentation](https://github.com/chartjs/Chart.js/tree/v1.1.1/docs)
false
Other
chartjs
Chart.js
51762aece5a08f8961989c367a87be2ff2a52174.json
docs: Add a link to front-end integrations (#9866)
docs/index.md
@@ -6,6 +6,8 @@ You can get the latest version of Chart.js from [npm](https://npmjs.com/package/chart.js), the [GitHub releases](https://github.com/chartjs/Chart.js/releases/latest), or use a [Chart.js CDN](https://www.jsdelivr.com/package/npm/chart.js). Detailed installation instructions can be found on the [installation](./getting-started/installation.md) page. +If you're using a front-end framework (e.g., React, Angular, or Vue), please check [available integrations](https://github.com/chartjs/awesome#integrations). + ## Creating a Chart It's easy to get started with Chart.js. All that's required is the script included in your page along with a single `<canvas>` node to render the chart.
false
Other
chartjs
Chart.js
838d40b2c832e8ae1a8caeeba508714d7b647581.json
Synchronize data visibility with data changes (#9857) * Synchronize data visibility with data changes * avoid babel spread bug * Simpler? * one more * simple enough, cc?
src/core/core.controller.js
@@ -69,6 +69,21 @@ const getChart = (key) => { return Object.values(instances).filter((c) => c.canvas === canvas).pop(); }; +function moveNumericKeys(obj, start, move) { + const keys = Object.keys(obj); + for (const key of keys) { + const intKey = +key; + if (intKey >= start) { + const value = obj[key]; + delete obj[key]; + if (move > 0 || intKey > start) { + obj[intKey + move] = value; + } + } + } +} + + class Chart { // eslint-disable-next-line max-statements @@ -123,6 +138,7 @@ class Chart { this._animationsDisabled = undefined; this.$context = undefined; this._doResize = debounce(mode => this.update(mode), options.resizeDelay || 0); + this._dataChanges = []; // Add the chart instance to the global namespace instances[this.id] = this; @@ -424,24 +440,11 @@ class Chart { config.update(); const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext()); - - each(this.scales, (scale) => { - layouts.removeBox(this, scale); - }); - const animsDisabled = this._animationsDisabled = !options.animation; - this.ensureScalesHaveIDs(); - this.buildOrUpdateScales(); - - const existingEvents = new Set(Object.keys(this._listeners)); - const newEvents = new Set(options.events); - - if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) { - // The configured events have changed. Rebind. - this.unbindEvents(); - this.bindEvents(); - } + this._updateScales(); + this._checkEventBindings(); + this._updateHiddenIndices(); // plugins options references might have change, let's invalidate the cache // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167 @@ -493,6 +496,73 @@ class Chart { this.render(); } + /** + * @private + */ + _updateScales() { + each(this.scales, (scale) => { + layouts.removeBox(this, scale); + }); + + this.ensureScalesHaveIDs(); + this.buildOrUpdateScales(); + } + + /** + * @private + */ + _checkEventBindings() { + const options = this.options; + const existingEvents = new Set(Object.keys(this._listeners)); + const newEvents = new Set(options.events); + + if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) { + // The configured events have changed. Rebind. + this.unbindEvents(); + this.bindEvents(); + } + } + + /** + * @private + */ + _updateHiddenIndices() { + const {_hiddenIndices} = this; + const changes = this._getUniformDataChanges() || []; + for (const {method, start, count} of changes) { + const move = method === '_removeElements' ? -count : count; + moveNumericKeys(_hiddenIndices, start, move); + } + } + + /** + * @private + */ + _getUniformDataChanges() { + const _dataChanges = this._dataChanges; + if (!_dataChanges || !_dataChanges.length) { + return; + } + + this._dataChanges = []; + const datasetCount = this.data.datasets.length; + const makeSet = (idx) => new Set( + _dataChanges + .filter(c => c[0] === idx) + .map((c, i) => i + ',' + c.splice(1).join(',')) + ); + + const changeSet = makeSet(0); + for (let i = 1; i < datasetCount; i++) { + if (!setsEqual(changeSet, makeSet(i))) { + return; + } + } + return Array.from(changeSet) + .map(c => c.split(',')) + .map(a => ({method: a[1], start: +a[2], count: +a[3]})); + } + /** * Updates the chart layout unless a plugin returns `false` to the `beforeLayout` * hook, in which case, plugins will not be called on `afterLayout`.
true
Other
chartjs
Chart.js
838d40b2c832e8ae1a8caeeba508714d7b647581.json
Synchronize data visibility with data changes (#9857) * Synchronize data visibility with data changes * avoid babel spread bug * Simpler? * one more * simple enough, cc?
src/core/core.datasetController.js
@@ -982,16 +982,19 @@ export default class DatasetController { meta.data.splice(start, count); } + /** + * @private + */ _sync(args) { if (this._parsing) { this._syncList.push(args); } else { const [method, arg1, arg2] = args; this[method](arg1, arg2); } + this.chart._dataChanges.push([this.index, ...args]); } - /** * @private */ @@ -1018,8 +1021,13 @@ export default class DatasetController { * @private */ _onDataSplice(start, count) { - this._sync(['_removeElements', start, count]); - this._sync(['_insertElements', start, arguments.length - 2]); + if (count) { + this._sync(['_removeElements', start, count]); + } + const newCount = arguments.length - 2; + if (newCount) { + this._sync(['_insertElements', start, newCount]); + } } /**
true
Other
chartjs
Chart.js
838d40b2c832e8ae1a8caeeba508714d7b647581.json
Synchronize data visibility with data changes (#9857) * Synchronize data visibility with data changes * avoid babel spread bug * Simpler? * one more * simple enough, cc?
test/specs/core.controller.tests.js
@@ -1966,6 +1966,99 @@ describe('Chart', function() { chart.update(); expect(chart.getDataVisibility(1)).toBe(false); }); + + it('should maintain data visibility indices when data changes', function() { + var chart = acquireChart({ + type: 'pie', + data: { + labels: ['0', '1', '2', '3'], + datasets: [{ + data: [0, 1, 2, 3] + }, { + data: [0, 1, 2, 3] + }] + } + }); + + chart.toggleDataVisibility(3); + + chart.data.labels.splice(1, 1); + chart.data.datasets[0].data.splice(1, 1); + chart.data.datasets[1].data.splice(1, 1); + chart.update(); + + expect(chart.getDataVisibility(0)).toBe(true); + expect(chart.getDataVisibility(1)).toBe(true); + expect(chart.getDataVisibility(2)).toBe(false); + + chart.data.labels.unshift('-1', '-2'); + chart.data.datasets[0].data.unshift(-1, -2); + chart.data.datasets[1].data.unshift(-1, -2); + chart.update(); + + expect(chart.getDataVisibility(0)).toBe(true); + expect(chart.getDataVisibility(1)).toBe(true); + expect(chart.getDataVisibility(2)).toBe(true); + expect(chart.getDataVisibility(3)).toBe(true); + expect(chart.getDataVisibility(4)).toBe(false); + + chart.data.labels.shift(); + chart.data.datasets[0].data.shift(); + chart.data.datasets[1].data.shift(); + chart.update(); + + expect(chart.getDataVisibility(0)).toBe(true); + expect(chart.getDataVisibility(1)).toBe(true); + expect(chart.getDataVisibility(2)).toBe(true); + expect(chart.getDataVisibility(3)).toBe(false); + + chart.data.labels.pop(); + chart.data.datasets[0].data.pop(); + chart.data.datasets[1].data.pop(); + chart.update(); + + expect(chart.getDataVisibility(0)).toBe(true); + expect(chart.getDataVisibility(1)).toBe(true); + expect(chart.getDataVisibility(2)).toBe(true); + expect(chart.getDataVisibility(3)).toBe(true); + + chart.toggleDataVisibility(1); + chart.data.labels.splice(1, 0, 'b'); + chart.data.datasets[0].data.splice(1, 0, 1); + chart.data.datasets[1].data.splice(1, 0, 1); + chart.update(); + + expect(chart.getDataVisibility(0)).toBe(true); + expect(chart.getDataVisibility(1)).toBe(true); + expect(chart.getDataVisibility(2)).toBe(false); + expect(chart.getDataVisibility(3)).toBe(true); + }); + + it('should leave data visibility indices intact when data changes in non-uniform way', function() { + var chart = acquireChart({ + type: 'pie', + data: { + labels: ['0', '1', '2', '3'], + datasets: [{ + data: [0, 1, 2, 3] + }, { + data: [0, 1, 2, 3] + }] + } + }); + + chart.toggleDataVisibility(0); + + chart.data.labels.push('a'); + chart.data.datasets[0].data.pop(); + chart.data.datasets[1].data.push(5); + chart.update(); + + expect(chart.getDataVisibility(0)).toBe(false); + expect(chart.getDataVisibility(1)).toBe(true); + expect(chart.getDataVisibility(2)).toBe(true); + expect(chart.getDataVisibility(3)).toBe(true); + }); }); describe('isDatasetVisible', function() {
true
Other
chartjs
Chart.js
0c5db4973e29d3f77f8bf45bbee8170a86608ed1.json
Fix inRange for full circle arc (#9871) * Update misleading sample comment * Fix inRange for full circle arc
src/elements/element.arc.js
@@ -1,6 +1,6 @@ import Element from '../core/core.element'; -import {_angleBetween, getAngleFromPoint, TAU, HALF_PI} from '../helpers/index'; -import {PI, _limitValue} from '../helpers/helpers.math'; +import {_angleBetween, getAngleFromPoint, TAU, HALF_PI, valueOrDefault} from '../helpers/index'; +import {PI, _isBetween, _limitValue} from '../helpers/helpers.math'; import {_readValueToProps} from '../helpers/helpers.options'; function clipArc(ctx, element, endAngle) { @@ -282,8 +282,9 @@ export default class ArcElement extends Element { 'circumference' ], useFinalPosition); const rAdjust = this.options.spacing / 2; - const betweenAngles = circumference >= TAU || _angleBetween(angle, startAngle, endAngle); - const withinRadius = (distance >= innerRadius + rAdjust && distance <= outerRadius + rAdjust); + const _circumference = valueOrDefault(circumference, endAngle - startAngle); + const betweenAngles = _circumference >= TAU || _angleBetween(angle, startAngle, endAngle); + const withinRadius = _isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust); return (betweenAngles && withinRadius); }
true
Other
chartjs
Chart.js
0c5db4973e29d3f77f8bf45bbee8170a86608ed1.json
Fix inRange for full circle arc (#9871) * Update misleading sample comment * Fix inRange for full circle arc
src/elements/element.bar.js
@@ -1,5 +1,5 @@ import Element from '../core/core.element'; -import {isObject, _limitValue} from '../helpers'; +import {isObject, _isBetween, _limitValue} from '../helpers'; import {addRoundedRectPath} from '../helpers/helpers.canvas'; import {toTRBL, toTRBLCorners} from '../helpers/helpers.options'; @@ -105,8 +105,8 @@ function inRange(bar, x, y, useFinalPosition) { const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition); return bounds - && (skipX || x >= bounds.left && x <= bounds.right) - && (skipY || y >= bounds.top && y <= bounds.bottom); + && (skipX || _isBetween(x, bounds.left, bounds.right)) + && (skipY || _isBetween(y, bounds.top, bounds.bottom)); } function hasRadius(radius) {
true
Other
chartjs
Chart.js
0c5db4973e29d3f77f8bf45bbee8170a86608ed1.json
Fix inRange for full circle arc (#9871) * Update misleading sample comment * Fix inRange for full circle arc
src/helpers/helpers.math.js
@@ -173,6 +173,21 @@ export function _limitValue(value, min, max) { return Math.max(min, Math.min(max, value)); } +/** + * @param {number} value + * @private + */ export function _int16Range(value) { return _limitValue(value, -32768, 32767); } + +/** + * @param {number} value + * @param {number} start + * @param {number} end + * @param {number} [epsilon] + * @private + */ +export function _isBetween(value, start, end, epsilon = 1e-6) { + return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon; +}
true
Other
chartjs
Chart.js
0c5db4973e29d3f77f8bf45bbee8170a86608ed1.json
Fix inRange for full circle arc (#9871) * Update misleading sample comment * Fix inRange for full circle arc
src/helpers/helpers.segment.js
@@ -1,4 +1,4 @@ -import {_angleBetween, _angleDiff, _normalizeAngle} from './helpers.math'; +import {_angleBetween, _angleDiff, _isBetween, _normalizeAngle} from './helpers.math'; import {createContext} from './helpers.options'; /** @@ -16,7 +16,7 @@ function propertyFn(property) { }; } return { - between: (n, s, e) => n >= Math.min(s, e) && n <= Math.max(e, s), + between: _isBetween, compare: (a, b) => a - b, normalize: x => x };
true
Other
chartjs
Chart.js
0c5db4973e29d3f77f8bf45bbee8170a86608ed1.json
Fix inRange for full circle arc (#9871) * Update misleading sample comment * Fix inRange for full circle arc
src/plugins/plugin.filler.js
@@ -8,7 +8,7 @@ import LineElement from '../elements/element.line'; import {_boundSegment, _boundSegments} from '../helpers/helpers.segment'; import {clipArea, unclipArea} from '../helpers/helpers.canvas'; import {isArray, isFinite, isObject, valueOrDefault} from '../helpers/helpers.core'; -import {TAU, _normalizeAngle} from '../helpers/helpers.math'; +import {TAU, _isBetween, _normalizeAngle} from '../helpers/helpers.math'; /** * @typedef { import('../core/core.controller').default } Chart @@ -293,7 +293,7 @@ function findPoint(line, sourcePoint, property) { const segment = segments[i]; const firstValue = linePoints[segment.start][property]; const lastValue = linePoints[segment.end][property]; - if (pointValue >= firstValue && pointValue <= lastValue) { + if (_isBetween(pointValue, firstValue, lastValue)) { first = pointValue === firstValue; last = pointValue === lastValue; break;
true
Other
chartjs
Chart.js
0c5db4973e29d3f77f8bf45bbee8170a86608ed1.json
Fix inRange for full circle arc (#9871) * Update misleading sample comment * Fix inRange for full circle arc
src/plugins/plugin.legend.js
@@ -5,7 +5,7 @@ import {addRoundedRectPath, drawPoint, renderText} from '../helpers/helpers.canv import { callback as call, valueOrDefault, toFont, toPadding, getRtlAdapter, overrideTextDirection, restoreTextDirection, - clipArea, unclipArea + clipArea, unclipArea, _isBetween } from '../helpers/index'; import {_toLeftRightCenter, _alignStartEnd, _textX} from '../helpers/helpers.extras'; import {toTRBLCorners} from '../helpers/helpers.options'; @@ -493,13 +493,15 @@ export class Legend extends Element { _getLegendItemAt(x, y) { let i, hitBox, lh; - if (x >= this.left && x <= this.right && y >= this.top && y <= this.bottom) { + if (_isBetween(x, this.left, this.right) + && _isBetween(y, this.top, this.bottom)) { // See if we are touching one of the dataset boxes lh = this.legendHitBoxes; for (i = 0; i < lh.length; ++i) { hitBox = lh[i]; - if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) { + if (_isBetween(x, hitBox.left, hitBox.left + hitBox.width) + && _isBetween(y, hitBox.top, hitBox.top + hitBox.height)) { // Touching an element return this.legendItems[i]; }
true
Other
chartjs
Chart.js
0c5db4973e29d3f77f8bf45bbee8170a86608ed1.json
Fix inRange for full circle arc (#9871) * Update misleading sample comment * Fix inRange for full circle arc
test/specs/element.arc.tests.js
@@ -23,6 +23,39 @@ describe('Arc element tests', function() { expect(arc.inRange(-1.0 * Math.sqrt(7), Math.sqrt(7))).toBe(false); }); + it ('should determine if in range when full circle', function() { + // Mock out the arc as if the controller put it there + var arc = new Chart.elements.ArcElement({ + startAngle: 0, + endAngle: Math.PI * 2, + x: 0, + y: 0, + innerRadius: 5, + outerRadius: 10, + options: { + spacing: 0, + offset: 0, + } + }); + + for (const radius of [5, 7.5, 10]) { + for (let angle = 0; angle <= 360; angle += 22.5) { + const rad = angle / 180 * Math.PI; + const x = Math.sin(rad) * radius; + const y = Math.cos(rad) * radius; + expect(arc.inRange(x, y)).withContext(`radius: ${radius}, angle: ${angle}`).toBeTrue(); + } + } + for (const radius of [4, 11]) { + for (let angle = 0; angle <= 360; angle += 22.5) { + const rad = angle / 180 * Math.PI; + const x = Math.sin(rad) * radius; + const y = Math.cos(rad) * radius; + expect(arc.inRange(x, y)).withContext(`radius: ${radius}, angle: ${angle}`).toBeFalse(); + } + } + }); + it ('should include spacing for in range check', function() { // Mock out the arc as if the controller put it there var arc = new Chart.elements.ArcElement({
true
Other
chartjs
Chart.js
c8b885dd3e35632df407df4bd463d9a5cc90280b.json
Prevent proxying CanvasGradient in Node platform (#9861)
src/helpers/helpers.config.js
@@ -178,7 +178,8 @@ export function _descriptors(proxy, defaults = {scriptable: true, indexable: tru } const readKey = (prefix, name) => prefix ? prefix + _capitalize(name) : name; -const needsSubResolver = (prop, value) => isObject(value) && prop !== 'adapters'; +const needsSubResolver = (prop, value) => isObject(value) && prop !== 'adapters' && + (Object.getPrototypeOf(value) === null || value.constructor === Object); function _cached(target, prop, resolve) { if (Object.prototype.hasOwnProperty.call(target, prop)) { @@ -218,7 +219,7 @@ function _resolveScriptable(prop, value, target, receiver) { _stack.add(prop); value = value(_context, _subProxy || receiver); _stack.delete(prop); - if (isObject(value)) { + if (needsSubResolver(prop, value)) { // When scriptable option returns an object, create a resolver on that. value = createSubResolver(_proxy._scopes, _proxy, prop, value); }
true
Other
chartjs
Chart.js
c8b885dd3e35632df407df4bd463d9a5cc90280b.json
Prevent proxying CanvasGradient in Node platform (#9861)
test/specs/helpers.config.tests.js
@@ -752,6 +752,29 @@ describe('Chart.helpers.config', function() { expect(fn()).toEqual('ok'); }); + it('should not create proxy for objects with custom constructor', function() { + class MyClass { + constructor() { + this.string = 'test string'; + } + method(arg) { + return arg === undefined ? 'ok' : 'fail'; + } + } + + const defaults = { + test: new MyClass() + }; + + const resolver = _createResolver([{}, defaults]); + const opts = _attachContext(resolver, {index: 1}); + const fn = opts.test.method; + expect(typeof fn).toBe('function'); + expect(fn()).toEqual('ok'); + expect(opts.test.string).toEqual('test string'); + expect(opts.test.constructor).toEqual(MyClass); + }); + it('should properly set value to object in array of objects', function() { const defaults = {}; const options = {
true
Other
chartjs
Chart.js
359d1716834d3454ada84c5e7128c1d9b813a70c.json
update animation event to include inital variable (#9834)
types/animation.d.ts
@@ -12,6 +12,7 @@ export class Animation { export interface AnimationEvent { chart: Chart; numSteps: number; + initial: boolean; currentState: number; }
false
Other
chartjs
Chart.js
7966227df36fdb3a79f35ac238ea8b5c84b3f3a8.json
Pass number format to tooltip (#9831)
src/scales/scale.linearbase.js
@@ -312,6 +312,6 @@ export default class LinearScaleBase extends Scale { } getLabelForValue(value) { - return formatNumber(value, this.chart.options.locale); + return formatNumber(value, this.chart.options.locale, this.options.ticks.format); } }
true
Other
chartjs
Chart.js
7966227df36fdb3a79f35ac238ea8b5c84b3f3a8.json
Pass number format to tooltip (#9831)
src/scales/scale.logarithmic.js
@@ -146,7 +146,9 @@ export default class LogarithmicScale extends Scale { * @return {string} */ getLabelForValue(value) { - return value === undefined ? '0' : formatNumber(value, this.chart.options.locale); + return value === undefined + ? '0' + : formatNumber(value, this.chart.options.locale, this.options.ticks.format); } /**
true
Other
chartjs
Chart.js
6961bd6baf49df8bcd5f0614a1ffb80808db6ef5.json
Use const/let in time scale (#6806)
src/scales/scale.time.js
@@ -65,9 +65,9 @@ function sorter(a, b) { } function arrayUnique(items) { - var hash = {}; - var out = []; - var i, ilen, item; + const hash = {}; + const out = []; + let i, ilen, item; for (i = 0, ilen = items.length; i < ilen; ++i) { item = items[i]; @@ -103,9 +103,9 @@ function buildLookupTable(timestamps, min, max, distribution) { ]; } - var table = []; - var items = [min]; - var i, ilen, prev, curr, next; + const table = []; + const items = [min]; + let i, ilen, prev, curr, next; for (i = 0, ilen = timestamps.length; i < ilen; ++i) { curr = timestamps[i]; @@ -132,9 +132,9 @@ function buildLookupTable(timestamps, min, max, distribution) { // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/ function lookup(table, key, value) { - var lo = 0; - var hi = table.length - 1; - var mid, i0, i1; + let lo = 0; + let hi = table.length - 1; + let mid, i0, i1; while (lo >= 0 && lo <= hi) { mid = (lo + hi) >> 1; @@ -164,15 +164,15 @@ function lookup(table, key, value) { * index [0, 1] or [n - 1, n] are used for the interpolation. */ function interpolate(table, skey, sval, tkey) { - var range = lookup(table, skey, sval); + const range = lookup(table, skey, sval); // Note: the lookup table ALWAYS contains at least 2 items (min and max) - var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo; - var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi; + const prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo; + const next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi; - var span = next[skey] - prev[skey]; - var ratio = span ? (sval - prev[skey]) / span : 0; - var offset = (next[tkey] - prev[tkey]) * ratio; + const span = next[skey] - prev[skey]; + const ratio = span ? (sval - prev[skey]) / span : 0; + const offset = (next[tkey] - prev[tkey]) * ratio; return prev[tkey] + offset; } @@ -182,10 +182,10 @@ function parse(scale, input) { return null; } - var adapter = scale._adapter; - var options = scale.options.time; - var parser = options.parser; - var value = input; + const adapter = scale._adapter; + const options = scale.options.time; + const parser = options.parser; + let value = input; if (typeof parser === 'function') { value = parser(value); @@ -213,8 +213,8 @@ function parse(scale, input) { * Figures out what unit results in an appropriate number of auto-generated ticks */ function determineUnitForAutoTicks(minUnit, min, max, capacity) { - var ilen = UNITS.length; - var i, interval, factor; + const ilen = UNITS.length; + let i, interval, factor; for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) { interval = INTERVALS[UNITS[i]]; @@ -232,7 +232,7 @@ function determineUnitForAutoTicks(minUnit, min, max, capacity) { * Figures out what unit to format a set of ticks with */ function determineUnitForFormatting(scale, numTicks, minUnit, min, max) { - var i, unit; + let i, unit; for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) { unit = UNITS[i]; @@ -259,15 +259,15 @@ function determineMajorUnit(unit) { * responsibility of the calling code to clamp values if needed. */ function generate(scale, min, max, capacity) { - var adapter = scale._adapter; - var options = scale.options; - var timeOpts = options.time; - var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity); - var stepSize = resolve([timeOpts.stepSize, timeOpts.unitStepSize, 1]); - var weekday = minor === 'week' ? timeOpts.isoWeekday : false; - var first = min; - var ticks = []; - var time; + const adapter = scale._adapter; + const options = scale.options; + const timeOpts = options.time; + const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity); + const stepSize = resolve([timeOpts.stepSize, timeOpts.unitStepSize, 1]); + const weekday = minor === 'week' ? timeOpts.isoWeekday : false; + const ticks = []; + let first = min; + let time; // For 'week' unit, handle the first day of week option if (weekday) { @@ -300,9 +300,9 @@ function generate(scale, min, max, capacity) { * Offsets are added when the `offset` option is true. */ function computeOffsets(table, ticks, min, max, options) { - var start = 0; - var end = 0; - var first, last; + let start = 0; + let end = 0; + let first, last; if (options.offset && ticks.length) { first = interpolate(table, 'time', ticks[0], 'pos'); @@ -323,10 +323,10 @@ function computeOffsets(table, ticks, min, max, options) { } function setMajorTicks(scale, ticks, map, majorUnit) { - var adapter = scale._adapter; - var first = +adapter.startOf(ticks[0].value, majorUnit); - var last = ticks[ticks.length - 1].value; - var major, index; + const adapter = scale._adapter; + const first = +adapter.startOf(ticks[0].value, majorUnit); + const last = ticks[ticks.length - 1].value; + let major, index; for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) { index = map[major]; @@ -338,10 +338,10 @@ function setMajorTicks(scale, ticks, map, majorUnit) { } function ticksFromTimestamps(scale, values, majorUnit) { - var ticks = []; - var map = {}; - var ilen = values.length; - var i, value; + const ticks = []; + const map = {}; + const ilen = values.length; + let i, value; for (i = 0; i < ilen; ++i) { value = values[i]; @@ -424,12 +424,12 @@ function getAllTimestamps(scale) { function getTimestampsForTicks(scale) { - var min = scale.min; - var max = scale.max; - var options = scale.options; - var capacity = scale._getLabelCapacity(min); - var source = options.ticks.source; - var timestamps; + 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); @@ -449,9 +449,9 @@ function getTimestampsForTable(scale) { } function getLabelBounds(scale) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - var arr = getLabelTimestamps(scale); + const arr = getLabelTimestamps(scale); + let min = Number.POSITIVE_INFINITY; + let max = Number.NEGATIVE_INFINITY; if (arr.length) { min = arr[0]; @@ -468,8 +468,8 @@ function getLabelBounds(scale) { * @param {int} max - max value (timestamp) */ function filterBetween(timestamps, min, max) { - var start = 0; - var end = timestamps.length - 1; + let start = 0; + let end = timestamps.length - 1; while (start < end && timestamps[start] < min) { start++; @@ -558,10 +558,10 @@ class TimeScale extends Scale { constructor(props) { super(props); - var me = this; - var options = me.options; - var time = options.time || (options.time = {}); - var adapter = me._adapter = new adapters._date(options.adapters.date); + const me = this; + const options = me.options; + const time = options.time || (options.time = {}); + const adapter = me._adapter = new adapters._date(options.adapters.date); me._cache = {}; @@ -575,11 +575,11 @@ class TimeScale extends Scale { } determineDataLimits() { - var me = this; - var options = me.options; - var adapter = me._adapter; - var unit = options.time.unit || 'day'; - var {min, max, minDefined, maxDefined} = me._getUserBounds(); + const me = this; + const options = me.options; + const adapter = me._adapter; + const unit = options.time.unit || 'day'; + let {min, max, minDefined, maxDefined} = me._getUserBounds(); function _applyBounds(bounds) { if (!minDefined && !isNaN(bounds.min)) { @@ -611,25 +611,23 @@ class TimeScale extends Scale { } buildTicks() { - var me = this; - var options = me.options; - var timeOpts = options.time; - var tickOpts = options.ticks; - var distribution = options.distribution; - var ticks = []; - var min, max, timestamps; + const me = this; + const options = me.options; + const timeOpts = options.time; + const tickOpts = options.ticks; + const distribution = options.distribution; - timestamps = getTimestampsForTicks(me); + const timestamps = getTimestampsForTicks(me); if (options.bounds === 'ticks' && timestamps.length) { me.min = me._userMin || timestamps[0]; me.max = me._userMax || timestamps[timestamps.length - 1]; } - min = me.min; - max = me.max; + const min = me.min; + const max = me.max; - ticks = filterBetween(timestamps, min, max); + const ticks = filterBetween(timestamps, min, max); // PRIVATE // determineUnitForFormatting relies on the number of ticks so we don't use it when @@ -650,9 +648,9 @@ class TimeScale extends Scale { } getLabelForValue(value) { - var me = this; - var adapter = me._adapter; - var timeOpts = me.options.time; + const me = this; + const adapter = me._adapter; + const timeOpts = me.options.time; if (timeOpts.tooltipFormat) { return adapter.format(value, timeOpts.tooltipFormat); @@ -665,19 +663,19 @@ class TimeScale extends Scale { * @private */ _tickFormatFunction(time, index, ticks, format) { - var me = this; - var adapter = me._adapter; - var options = me.options; - var formats = options.time.displayFormats; - var minorFormat = formats[me._unit]; - var majorUnit = me._majorUnit; - var majorFormat = formats[majorUnit]; - var tick = ticks[index]; - var tickOpts = options.ticks; - var major = majorUnit && majorFormat && tick && tick.major; - var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat); - var nestedTickOpts = major ? tickOpts.major : tickOpts.minor; - var formatter = resolve([ + const me = this; + const adapter = me._adapter; + const options = me.options; + const formats = options.time.displayFormats; + const minorFormat = formats[me._unit]; + const majorUnit = me._majorUnit; + const majorFormat = formats[majorUnit]; + const tick = ticks[index]; + const tickOpts = options.ticks; + const major = majorUnit && majorFormat && tick && tick.major; + const label = adapter.format(time, format ? format : major ? majorFormat : minorFormat); + const nestedTickOpts = major ? tickOpts.major : tickOpts.minor; + const formatter = resolve([ nestedTickOpts.callback, tickOpts.callback ]); @@ -686,7 +684,7 @@ class TimeScale extends Scale { } generateTickLabels(ticks) { - var i, ilen, tick; + let i, ilen, tick; for (i = 0, ilen = ticks.length; i < ilen; ++i) { tick = ticks[i]; @@ -698,37 +696,37 @@ class TimeScale extends Scale { * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC) */ getPixelForValue(value) { - var me = this; - var offsets = me._offsets; - var pos = interpolate(me._table, 'time', value, 'pos'); + const me = this; + const offsets = me._offsets; + const pos = interpolate(me._table, 'time', value, 'pos'); return me.getPixelForDecimal((offsets.start + pos) * offsets.factor); } getPixelForTick(index) { - var ticks = this.getTicks(); + const ticks = this.getTicks(); return index >= 0 && index < ticks.length ? this.getPixelForValue(ticks[index].value) : null; } getValueForPixel(pixel) { - var me = this; - var offsets = me._offsets; - var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end; + const me = this; + const offsets = me._offsets; + const pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end; return interpolate(me._table, 'pos', pos, 'time'); } /** * @private */ _getLabelSize(label) { - var me = this; - var ticksOpts = me.options.ticks; - var tickLabelWidth = me.ctx.measureText(label).width; - var angle = helpers.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation); - var cosRotation = Math.cos(angle); - var sinRotation = Math.sin(angle); - var tickFontSize = valueOrDefault(ticksOpts.fontSize, defaults.global.defaultFontSize); + const me = this; + const ticksOpts = me.options.ticks; + const tickLabelWidth = me.ctx.measureText(label).width; + const angle = helpers.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation); + const cosRotation = Math.cos(angle); + const sinRotation = Math.sin(angle); + const tickFontSize = valueOrDefault(ticksOpts.fontSize, defaults.global.defaultFontSize); return { w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation), @@ -740,15 +738,15 @@ class TimeScale extends Scale { * @private */ _getLabelCapacity(exampleTime) { - var me = this; - var timeOpts = me.options.time; - var displayFormats = timeOpts.displayFormats; + const me = this; + const timeOpts = me.options.time; + const displayFormats = timeOpts.displayFormats; // pick the longest format (milliseconds) for guestimation - var format = displayFormats[timeOpts.unit] || displayFormats.millisecond; - var exampleLabel = me._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format); - var size = me._getLabelSize(exampleLabel); - var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h); + const format = displayFormats[timeOpts.unit] || displayFormats.millisecond; + const exampleLabel = me._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format); + const size = me._getLabelSize(exampleLabel); + let capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h); if (me.options.offset) { capacity--;
false
Other
chartjs
Chart.js
5a99dff5f7eeaa3c59ae9c473ccbe6738f289593.json
Convert src/helpers to use ES6 exports (#6797) * Canvas helpers exported * Easing helpers use exports * Math helper uses export * Linting * RTL options use export * Allow object spread operator * Rest of helpers use `export`
.eslintrc.yml
@@ -5,7 +5,7 @@ env: node: true parserOptions: - ecmaVersion: 6 + ecmaVersion: 2018 sourceType: 'module' plugins: ['html']
true
Other
chartjs
Chart.js
5a99dff5f7eeaa3c59ae9c473ccbe6738f289593.json
Convert src/helpers to use ES6 exports (#6797) * Canvas helpers exported * Easing helpers use exports * Math helper uses export * Linting * RTL options use export * Allow object spread operator * Rest of helpers use `export`
src/helpers/helpers.canvas.js
@@ -10,193 +10,191 @@ const TWO_THIRDS_PI = PI * 2 / 3; /** * @namespace Chart.helpers.canvas */ -module.exports = { - /** - * Returns the aligned pixel value to avoid anti-aliasing blur - * @param {Chart} chart - The chart instance. - * @param {number} pixel - A pixel value. - * @param {number} width - The width of the element. - * @returns {number} The aligned pixel value. - * @private - */ - _alignPixel: function(chart, pixel, width) { - const devicePixelRatio = chart.currentDevicePixelRatio; - const halfWidth = width / 2; - return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth; - }, - - /** - * Clears the entire canvas associated to the given `chart`. - * @param {Chart} chart - The chart for which to clear the canvas. - */ - clear: function(chart) { - chart.ctx.clearRect(0, 0, chart.width, chart.height); - }, +/** + * Returns the aligned pixel value to avoid anti-aliasing blur + * @param {Chart} chart - The chart instance. + * @param {number} pixel - A pixel value. + * @param {number} width - The width of the element. + * @returns {number} The aligned pixel value. + * @private + */ +export function _alignPixel(chart, pixel, width) { + const devicePixelRatio = chart.currentDevicePixelRatio; + const halfWidth = width / 2; + return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth; +} - drawPoint: function(ctx, style, radius, x, y, rotation) { - var type, xOffset, yOffset, size, cornerRadius; - var rad = (rotation || 0) * RAD_PER_DEG; +/** + * Clears the entire canvas associated to the given `chart`. + * @param {Chart} chart - The chart for which to clear the canvas. + */ +export function clear(chart) { + chart.ctx.clearRect(0, 0, chart.width, chart.height); +} - if (style && typeof style === 'object') { - type = style.toString(); - if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') { - ctx.save(); - ctx.translate(x, y); - ctx.rotate(rad); - ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height); - ctx.restore(); - return; - } - } +export function drawPoint(ctx, style, radius, x, y, rotation) { + var type, xOffset, yOffset, size, cornerRadius; + var rad = (rotation || 0) * RAD_PER_DEG; - if (isNaN(radius) || radius <= 0) { + if (style && typeof style === 'object') { + type = style.toString(); + if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') { + ctx.save(); + ctx.translate(x, y); + ctx.rotate(rad); + ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height); + ctx.restore(); return; } + } - ctx.beginPath(); + if (isNaN(radius) || radius <= 0) { + return; + } - switch (style) { - // Default includes circle - default: - ctx.arc(x, y, radius, 0, DOUBLE_PI); - ctx.closePath(); - break; - case 'triangle': - ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); - rad += TWO_THIRDS_PI; - ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); - rad += TWO_THIRDS_PI; - ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); - ctx.closePath(); - break; - case 'rectRounded': - // NOTE: the rounded rect implementation changed to use `arc` instead of - // `quadraticCurveTo` since it generates better results when rect is - // almost a circle. 0.516 (instead of 0.5) produces results with visually - // closer proportion to the previous impl and it is inscribed in the - // circle with `radius`. For more details, see the following PRs: - // https://github.com/chartjs/Chart.js/issues/5597 - // https://github.com/chartjs/Chart.js/issues/5858 - cornerRadius = radius * 0.516; - size = radius - cornerRadius; - xOffset = Math.cos(rad + QUARTER_PI) * size; - yOffset = Math.sin(rad + QUARTER_PI) * size; - ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI); - ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad); - ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI); - ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI); - ctx.closePath(); - break; - case 'rect': - if (!rotation) { - size = Math.SQRT1_2 * radius; - ctx.rect(x - size, y - size, 2 * size, 2 * size); - break; - } - rad += QUARTER_PI; - /* falls through */ - case 'rectRot': - xOffset = Math.cos(rad) * radius; - yOffset = Math.sin(rad) * radius; - ctx.moveTo(x - xOffset, y - yOffset); - ctx.lineTo(x + yOffset, y - xOffset); - ctx.lineTo(x + xOffset, y + yOffset); - ctx.lineTo(x - yOffset, y + xOffset); - ctx.closePath(); - break; - case 'crossRot': - rad += QUARTER_PI; - /* falls through */ - case 'cross': - xOffset = Math.cos(rad) * radius; - yOffset = Math.sin(rad) * radius; - ctx.moveTo(x - xOffset, y - yOffset); - ctx.lineTo(x + xOffset, y + yOffset); - ctx.moveTo(x + yOffset, y - xOffset); - ctx.lineTo(x - yOffset, y + xOffset); - break; - case 'star': - xOffset = Math.cos(rad) * radius; - yOffset = Math.sin(rad) * radius; - ctx.moveTo(x - xOffset, y - yOffset); - ctx.lineTo(x + xOffset, y + yOffset); - ctx.moveTo(x + yOffset, y - xOffset); - ctx.lineTo(x - yOffset, y + xOffset); - rad += QUARTER_PI; - xOffset = Math.cos(rad) * radius; - yOffset = Math.sin(rad) * radius; - ctx.moveTo(x - xOffset, y - yOffset); - ctx.lineTo(x + xOffset, y + yOffset); - ctx.moveTo(x + yOffset, y - xOffset); - ctx.lineTo(x - yOffset, y + xOffset); - break; - case 'line': - xOffset = Math.cos(rad) * radius; - yOffset = Math.sin(rad) * radius; - ctx.moveTo(x - xOffset, y - yOffset); - ctx.lineTo(x + xOffset, y + yOffset); - break; - case 'dash': - ctx.moveTo(x, y); - ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius); + ctx.beginPath(); + + switch (style) { + // Default includes circle + default: + ctx.arc(x, y, radius, 0, DOUBLE_PI); + ctx.closePath(); + break; + case 'triangle': + ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); + rad += TWO_THIRDS_PI; + ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); + rad += TWO_THIRDS_PI; + ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); + ctx.closePath(); + break; + case 'rectRounded': + // NOTE: the rounded rect implementation changed to use `arc` instead of + // `quadraticCurveTo` since it generates better results when rect is + // almost a circle. 0.516 (instead of 0.5) produces results with visually + // closer proportion to the previous impl and it is inscribed in the + // circle with `radius`. For more details, see the following PRs: + // https://github.com/chartjs/Chart.js/issues/5597 + // https://github.com/chartjs/Chart.js/issues/5858 + cornerRadius = radius * 0.516; + size = radius - cornerRadius; + xOffset = Math.cos(rad + QUARTER_PI) * size; + yOffset = Math.sin(rad + QUARTER_PI) * size; + ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI); + ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad); + ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI); + ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI); + ctx.closePath(); + break; + case 'rect': + if (!rotation) { + size = Math.SQRT1_2 * radius; + ctx.rect(x - size, y - size, 2 * size, 2 * size); break; } + rad += QUARTER_PI; + /* falls through */ + case 'rectRot': + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + yOffset, y - xOffset); + ctx.lineTo(x + xOffset, y + yOffset); + ctx.lineTo(x - yOffset, y + xOffset); + ctx.closePath(); + break; + case 'crossRot': + rad += QUARTER_PI; + /* falls through */ + case 'cross': + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + xOffset, y + yOffset); + ctx.moveTo(x + yOffset, y - xOffset); + ctx.lineTo(x - yOffset, y + xOffset); + break; + case 'star': + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + xOffset, y + yOffset); + ctx.moveTo(x + yOffset, y - xOffset); + ctx.lineTo(x - yOffset, y + xOffset); + rad += QUARTER_PI; + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + xOffset, y + yOffset); + ctx.moveTo(x + yOffset, y - xOffset); + ctx.lineTo(x - yOffset, y + xOffset); + break; + case 'line': + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + xOffset, y + yOffset); + break; + case 'dash': + ctx.moveTo(x, y); + ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius); + break; + } - ctx.fill(); - ctx.stroke(); - }, + ctx.fill(); + ctx.stroke(); +} - /** - * Returns true if the point is inside the rectangle - * @param {object} point - The point to test - * @param {object} area - The rectangle - * @returns {boolean} - * @private - */ - _isPointInArea: function(point, area) { - var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error. +/** + * Returns true if the point is inside the rectangle + * @param {object} point - The point to test + * @param {object} area - The rectangle + * @returns {boolean} + * @private + */ +export function _isPointInArea(point, area) { + var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error. - return point.x > area.left - epsilon && point.x < area.right + epsilon && - point.y > area.top - epsilon && point.y < area.bottom + epsilon; - }, + return point.x > area.left - epsilon && point.x < area.right + epsilon && + point.y > area.top - epsilon && point.y < area.bottom + epsilon; +} - clipArea: function(ctx, area) { - ctx.save(); - ctx.beginPath(); - ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); - ctx.clip(); - }, +export function clipArea(ctx, area) { + ctx.save(); + ctx.beginPath(); + ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); + ctx.clip(); +} - unclipArea: function(ctx) { - ctx.restore(); - }, +export function unclipArea(ctx) { + ctx.restore(); +} - /** - * @private - */ - _steppedLineTo: function(ctx, previous, target, flip, mode) { - if (mode === 'middle') { - const midpoint = (previous.x + target.x) / 2.0; - ctx.lineTo(midpoint, flip ? target.y : previous.y); - ctx.lineTo(midpoint, flip ? previous.y : target.y); - } else if ((mode === 'after' && !flip) || (mode !== 'after' && flip)) { - ctx.lineTo(previous.x, target.y); - } else { - ctx.lineTo(target.x, previous.y); - } - ctx.lineTo(target.x, target.y); - }, - - /** - * @private - */ - _bezierCurveTo: function(ctx, previous, target, flip) { - ctx.bezierCurveTo( - flip ? previous.controlPointPreviousX : previous.controlPointNextX, - flip ? previous.controlPointPreviousY : previous.controlPointNextY, - flip ? target.controlPointNextX : target.controlPointPreviousX, - flip ? target.controlPointNextY : target.controlPointPreviousY, - target.x, - target.y); +/** + * @private + */ +export function _steppedLineTo(ctx, previous, target, flip, mode) { + if (mode === 'middle') { + const midpoint = (previous.x + target.x) / 2.0; + ctx.lineTo(midpoint, flip ? target.y : previous.y); + ctx.lineTo(midpoint, flip ? previous.y : target.y); + } else if ((mode === 'after' && !flip) || (mode !== 'after' && flip)) { + ctx.lineTo(previous.x, target.y); + } else { + ctx.lineTo(target.x, previous.y); } -}; + ctx.lineTo(target.x, target.y); +} + +/** + * @private + */ +export function _bezierCurveTo(ctx, previous, target, flip) { + ctx.bezierCurveTo( + flip ? previous.controlPointPreviousX : previous.controlPointNextX, + flip ? previous.controlPointPreviousY : previous.controlPointNextY, + flip ? target.controlPointNextX : target.controlPointPreviousX, + flip ? target.controlPointNextY : target.controlPointPreviousY, + target.x, + target.y); +}
true
Other
chartjs
Chart.js
5a99dff5f7eeaa3c59ae9c473ccbe6738f289593.json
Convert src/helpers to use ES6 exports (#6797) * Canvas helpers exported * Easing helpers use exports * Math helper uses export * Linting * RTL options use export * Allow object spread operator * Rest of helpers use `export`
src/helpers/helpers.core.js
@@ -3,342 +3,343 @@ /** * @namespace Chart.helpers */ -var helpers = { - /** - * An empty function that can be used, for example, for optional callback. - */ - noop: function() {}, - - /** - * Returns a unique id, sequentially generated from a global variable. - * @returns {number} - * @function - */ - uid: (function() { - var id = 0; - return function() { - return id++; - }; - }()), - - /** - * Returns true if `value` is neither null nor undefined, else returns false. - * @param {*} value - The value to test. - * @returns {boolean} - * @since 2.7.0 - */ - isNullOrUndef: function(value) { - return value === null || typeof value === 'undefined'; - }, - - /** - * Returns true if `value` is an array (including typed arrays), else returns false. - * @param {*} value - The value to test. - * @returns {boolean} - * @function - */ - isArray: function(value) { - if (Array.isArray && Array.isArray(value)) { - return true; - } - var type = Object.prototype.toString.call(value); - if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') { - return true; - } - return false; - }, - - /** - * Returns true if `value` is an object (excluding null), else returns false. - * @param {*} value - The value to test. - * @returns {boolean} - * @since 2.7.0 - */ - isObject: function(value) { - return value !== null && Object.prototype.toString.call(value) === '[object Object]'; - }, - - /** - * Returns true if `value` is a finite number, else returns false - * @param {*} value - The value to test. - * @returns {boolean} - */ - isFinite: function(value) { - return (typeof value === 'number' || value instanceof Number) && isFinite(value); - }, - - /** - * Returns `value` if defined, else returns `defaultValue`. - * @param {*} value - The value to return if defined. - * @param {*} defaultValue - The value to return if `value` is undefined. - * @returns {*} - */ - valueOrDefault: function(value, defaultValue) { - return typeof value === 'undefined' ? defaultValue : value; - }, - - /** - * Returns value at the given `index` in array if defined, else returns `defaultValue`. - * @param {Array} value - The array to lookup for value at `index`. - * @param {number} index - The index in `value` to lookup for value. - * @param {*} defaultValue - The value to return if `value[index]` is undefined. - * @returns {*} - */ - valueAtIndexOrDefault: function(value, index, defaultValue) { - return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue); - }, - - /** - * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the - * value returned by `fn`. If `fn` is not a function, this method returns undefined. - * @param {function} fn - The function to call. - * @param {Array|undefined|null} args - The arguments with which `fn` should be called. - * @param {object} [thisArg] - The value of `this` provided for the call to `fn`. - * @returns {*} - */ - callback: function(fn, args, thisArg) { - if (fn && typeof fn.call === 'function') { - return fn.apply(thisArg, args); - } - }, - - /** - * Note(SB) for performance sake, this method should only be used when loopable type - * is unknown or in none intensive code (not called often and small loopable). Else - * it's preferable to use a regular for() loop and save extra function calls. - * @param {object|Array} loopable - The object or array to be iterated. - * @param {function} fn - The function to call for each item. - * @param {object} [thisArg] - The value of `this` provided for the call to `fn`. - * @param {boolean} [reverse] - If true, iterates backward on the loopable. - */ - each: function(loopable, fn, thisArg, reverse) { - var i, len, keys; - if (helpers.isArray(loopable)) { - len = loopable.length; - if (reverse) { - for (i = len - 1; i >= 0; i--) { - fn.call(thisArg, loopable[i], i); - } - } else { - for (i = 0; i < len; i++) { - fn.call(thisArg, loopable[i], i); - } +/** + * An empty function that can be used, for example, for optional callback. + */ +export function noop() {} + +/** + * Returns a unique id, sequentially generated from a global variable. + * @returns {number} + * @function + */ +export const uid = (function() { + var id = 0; + return function() { + return id++; + }; +}()); + +/** + * Returns true if `value` is neither null nor undefined, else returns false. + * @param {*} value - The value to test. + * @returns {boolean} + * @since 2.7.0 + */ +export function isNullOrUndef(value) { + return value === null || typeof value === 'undefined'; +} + +/** + * Returns true if `value` is an array (including typed arrays), else returns false. + * @param {*} value - The value to test. + * @returns {boolean} + * @function + */ +export function isArray(value) { + if (Array.isArray && Array.isArray(value)) { + return true; + } + var type = Object.prototype.toString.call(value); + if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') { + return true; + } + return false; +} + +/** + * Returns true if `value` is an object (excluding null), else returns false. + * @param {*} value - The value to test. + * @returns {boolean} + * @since 2.7.0 + */ +export function isObject(value) { + return value !== null && Object.prototype.toString.call(value) === '[object Object]'; +} + +/** + * Returns true if `value` is a finite number, else returns false + * @param {*} value - The value to test. + * @returns {boolean} + */ +const isNumberFinite = (value) => { + return (typeof value === 'number' || value instanceof Number) && isFinite(value); +}; +export { + isNumberFinite as isFinite, +}; + +/** + * Returns `value` if defined, else returns `defaultValue`. + * @param {*} value - The value to return if defined. + * @param {*} defaultValue - The value to return if `value` is undefined. + * @returns {*} + */ +export function valueOrDefault(value, defaultValue) { + return typeof value === 'undefined' ? defaultValue : value; +} + +/** + * Returns value at the given `index` in array if defined, else returns `defaultValue`. + * @param {Array} value - The array to lookup for value at `index`. + * @param {number} index - The index in `value` to lookup for value. + * @param {*} defaultValue - The value to return if `value[index]` is undefined. + * @returns {*} + */ +export function valueAtIndexOrDefault(value, index, defaultValue) { + return valueOrDefault(isArray(value) ? value[index] : value, defaultValue); +} + +/** + * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the + * value returned by `fn`. If `fn` is not a function, this method returns undefined. + * @param {function} fn - The function to call. + * @param {Array|undefined|null} args - The arguments with which `fn` should be called. + * @param {object} [thisArg] - The value of `this` provided for the call to `fn`. + * @returns {*} + */ +export function callback(fn, args, thisArg) { + if (fn && typeof fn.call === 'function') { + return fn.apply(thisArg, args); + } +} + +/** + * Note(SB) for performance sake, this method should only be used when loopable type + * is unknown or in none intensive code (not called often and small loopable). Else + * it's preferable to use a regular for() loop and save extra function calls. + * @param {object|Array} loopable - The object or array to be iterated. + * @param {function} fn - The function to call for each item. + * @param {object} [thisArg] - The value of `this` provided for the call to `fn`. + * @param {boolean} [reverse] - If true, iterates backward on the loopable. + */ +export function each(loopable, fn, thisArg, reverse) { + var i, len, keys; + if (isArray(loopable)) { + len = loopable.length; + if (reverse) { + for (i = len - 1; i >= 0; i--) { + fn.call(thisArg, loopable[i], i); } - } else if (helpers.isObject(loopable)) { - keys = Object.keys(loopable); - len = keys.length; + } else { for (i = 0; i < len; i++) { - fn.call(thisArg, loopable[keys[i]], keys[i]); + fn.call(thisArg, loopable[i], i); } } - }, - - /** - * Returns true if the `a0` and `a1` arrays have the same content, else returns false. - * @see https://stackoverflow.com/a/14853974 - * @param {Array} a0 - The array to compare - * @param {Array} a1 - The array to compare - * @returns {boolean} - */ - arrayEquals: function(a0, a1) { - var i, ilen, v0, v1; - - if (!a0 || !a1 || a0.length !== a1.length) { - return false; + } else if (isObject(loopable)) { + keys = Object.keys(loopable); + len = keys.length; + for (i = 0; i < len; i++) { + fn.call(thisArg, loopable[keys[i]], keys[i]); } + } +} - for (i = 0, ilen = a0.length; i < ilen; ++i) { - v0 = a0[i]; - v1 = a1[i]; +/** + * Returns true if the `a0` and `a1` arrays have the same content, else returns false. + * @see https://stackoverflow.com/a/14853974 + * @param {Array} a0 - The array to compare + * @param {Array} a1 - The array to compare + * @returns {boolean} + */ +export function arrayEquals(a0, a1) { + var i, ilen, v0, v1; - if (v0 instanceof Array && v1 instanceof Array) { - if (!helpers.arrayEquals(v0, v1)) { - return false; - } - } else if (v0 !== v1) { - // NOTE: two different object instances will never be equal: {x:20} != {x:20} + if (!a0 || !a1 || a0.length !== a1.length) { + return false; + } + + for (i = 0, ilen = a0.length; i < ilen; ++i) { + v0 = a0[i]; + v1 = a1[i]; + + if (v0 instanceof Array && v1 instanceof Array) { + if (!arrayEquals(v0, v1)) { return false; } - } - - return true; - }, - - /** - * Returns true if the `a0` and `a1` arrays have the same content, else returns false. - * @param {Array} a0 - The array to compare - * @param {Array} a1 - The array to compare - * @returns {boolean} - */ - _elementsEqual: function(a0, a1) { - let i, ilen, v0, v1; - - if (!a0 || !a1 || a0.length !== a1.length) { + } else if (v0 !== v1) { + // NOTE: two different object instances will never be equal: {x:20} != {x:20} return false; } + } - for (i = 0, ilen = a0.length; i < ilen; ++i) { - v0 = a0[i]; - v1 = a1[i]; + return true; +} - if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) { - return false; - } - } +/** + * Returns true if the `a0` and `a1` arrays have the same content, else returns false. + * @param {Array} a0 - The array to compare + * @param {Array} a1 - The array to compare + * @returns {boolean} + */ +export function _elementsEqual(a0, a1) { + let i, ilen, v0, v1; - return true; - }, - - /** - * Returns a deep copy of `source` without keeping references on objects and arrays. - * @param {*} source - The value to clone. - * @returns {*} - */ - clone: function(source) { - if (helpers.isArray(source)) { - return source.map(helpers.clone); + if (!a0 || !a1 || a0.length !== a1.length) { + return false; + } + + for (i = 0, ilen = a0.length; i < ilen; ++i) { + v0 = a0[i]; + v1 = a1[i]; + + if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) { + return false; } + } - if (helpers.isObject(source)) { - var target = {}; - var keys = Object.keys(source); - var klen = keys.length; - var k = 0; + return true; +} - for (; k < klen; ++k) { - target[keys[k]] = helpers.clone(source[keys[k]]); - } +/** + * Returns a deep copy of `source` without keeping references on objects and arrays. + * @param {*} source - The value to clone. + * @returns {*} + */ +export function clone(source) { + if (isArray(source)) { + return source.map(clone); + } + + if (isObject(source)) { + var target = {}; + var keys = Object.keys(source); + var klen = keys.length; + var k = 0; - return target; + for (; k < klen; ++k) { + target[keys[k]] = clone(source[keys[k]]); } - return source; - }, + return target; + } - /** - * The default merger when Chart.helpers.merge is called without merger option. - * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback. - * @private - */ - _merger: function(key, target, source, options) { - var tval = target[key]; - var sval = source[key]; + return source; +} - if (helpers.isObject(tval) && helpers.isObject(sval)) { - helpers.merge(tval, sval, options); - } else { - target[key] = helpers.clone(sval); - } - }, - - /** - * Merges source[key] in target[key] only if target[key] is undefined. - * @private - */ - _mergerIf: function(key, target, source) { - var tval = target[key]; - var sval = source[key]; - - if (helpers.isObject(tval) && helpers.isObject(sval)) { - helpers.mergeIf(tval, sval); - } else if (!Object.prototype.hasOwnProperty.call(target, key)) { - target[key] = helpers.clone(sval); - } - }, - - /** - * Recursively deep copies `source` properties into `target` with the given `options`. - * IMPORTANT: `target` is not cloned and will be updated with `source` properties. - * @param {object} target - The target object in which all sources are merged into. - * @param {object|object[]} source - Object(s) to merge into `target`. - * @param {object} [options] - Merging options: - * @param {function} [options.merger] - The merge method (key, target, source, options) - * @returns {object} The `target` object. - */ - merge: function(target, source, options) { - var sources = helpers.isArray(source) ? source : [source]; - var ilen = sources.length; - var merge, i, keys, klen, k; - - if (!helpers.isObject(target)) { - return target; - } +/** + * The default merger when Chart.helpers.merge is called without merger option. + * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback. + * @private + */ +export function _merger(key, target, source, options) { + var tval = target[key]; + var sval = source[key]; + + if (isObject(tval) && isObject(sval)) { + // eslint-disable-next-line no-use-before-define + merge(tval, sval, options); + } else { + target[key] = clone(sval); + } +} - options = options || {}; - merge = options.merger || helpers._merger; +/** + * Recursively deep copies `source` properties into `target` with the given `options`. + * IMPORTANT: `target` is not cloned and will be updated with `source` properties. + * @param {object} target - The target object in which all sources are merged into. + * @param {object|object[]} source - Object(s) to merge into `target`. + * @param {object} [options] - Merging options: + * @param {function} [options.merger] - The merge method (key, target, source, options) + * @returns {object} The `target` object. + */ +export function merge(target, source, options) { + var sources = isArray(source) ? source : [source]; + var ilen = sources.length; + var merger, i, keys, klen, k; - for (i = 0; i < ilen; ++i) { - source = sources[i]; - if (!helpers.isObject(source)) { - continue; - } + if (!isObject(target)) { + return target; + } - keys = Object.keys(source); - for (k = 0, klen = keys.length; k < klen; ++k) { - merge(keys[k], target, source, options); - } + options = options || {}; + merger = options.merger || _merger; + + for (i = 0; i < ilen; ++i) { + source = sources[i]; + if (!isObject(source)) { + continue; } - return target; - }, - - /** - * Recursively deep copies `source` properties into `target` *only* if not defined in target. - * IMPORTANT: `target` is not cloned and will be updated with `source` properties. - * @param {object} target - The target object in which all sources are merged into. - * @param {object|object[]} source - Object(s) to merge into `target`. - * @returns {object} The `target` object. - */ - mergeIf: function(target, source) { - return helpers.merge(target, source, {merger: helpers._mergerIf}); - }, - - /** - * Applies the contents of two or more objects together into the first object. - * @param {object} target - The target object in which all objects are merged into. - * @param {object} arg1 - Object containing additional properties to merge in target. - * @param {object} argN - Additional objects containing properties to merge in target. - * @returns {object} The `target` object. - */ - extend: Object.assign || function(target) { - return helpers.merge(target, [].slice.call(arguments, 1), { - merger: function(key, dst, src) { - dst[key] = src[key]; - } - }); - }, - - /** - * Basic javascript inheritance based on the model created in Backbone.js - */ - inherits: function(extensions) { - var me = this; - var ChartElement = (extensions && Object.prototype.hasOwnProperty.call(extensions, 'constructor')) ? extensions.constructor : function() { - return me.apply(this, arguments); - }; - - var Surrogate = function() { - this.constructor = ChartElement; - }; - - Surrogate.prototype = me.prototype; - ChartElement.prototype = new Surrogate(); - ChartElement.extend = helpers.inherits; - - if (extensions) { - helpers.extend(ChartElement.prototype, extensions); + keys = Object.keys(source); + for (k = 0, klen = keys.length; k < klen; ++k) { + merger(keys[k], target, source, options); } + } - ChartElement.__super__ = me.prototype; - return ChartElement; - }, + return target; +} - _deprecated: function(scope, value, previous, current) { - if (value !== undefined) { - console.warn(scope + ': "' + previous + - '" is deprecated. Please use "' + current + '" instead'); - } +/** + * Recursively deep copies `source` properties into `target` *only* if not defined in target. + * IMPORTANT: `target` is not cloned and will be updated with `source` properties. + * @param {object} target - The target object in which all sources are merged into. + * @param {object|object[]} source - Object(s) to merge into `target`. + * @returns {object} The `target` object. + */ +export function mergeIf(target, source) { + // eslint-disable-next-line no-use-before-define + return merge(target, source, {merger: _mergerIf}); +} + +/** + * Merges source[key] in target[key] only if target[key] is undefined. + * @private + */ +export function _mergerIf(key, target, source) { + var tval = target[key]; + var sval = source[key]; + + if (isObject(tval) && isObject(sval)) { + mergeIf(tval, sval); + } else if (!Object.prototype.hasOwnProperty.call(target, key)) { + target[key] = clone(sval); } +} + +/** + * Applies the contents of two or more objects together into the first object. + * @param {object} target - The target object in which all objects are merged into. + * @param {object} arg1 - Object containing additional properties to merge in target. + * @param {object} argN - Additional objects containing properties to merge in target. + * @returns {object} The `target` object. + */ +export const extend = Object.assign || function(target) { + return merge(target, [].slice.call(arguments, 1), { + merger: function(key, dst, src) { + dst[key] = src[key]; + } + }); }; -module.exports = helpers; +/** + * Basic javascript inheritance based on the model created in Backbone.js + */ +export function inherits(extensions) { + var me = this; + var ChartElement = (extensions && Object.prototype.hasOwnProperty.call(extensions, 'constructor')) ? extensions.constructor : function() { + return me.apply(this, arguments); + }; + + var Surrogate = function() { + this.constructor = ChartElement; + }; + + Surrogate.prototype = me.prototype; + ChartElement.prototype = new Surrogate(); + ChartElement.extend = inherits; + + if (extensions) { + extend(ChartElement.prototype, extensions); + } + + ChartElement.__super__ = me.prototype; + return ChartElement; +} + +export function _deprecated(scope, value, previous, current) { + if (value !== undefined) { + console.warn(scope + ': "' + previous + + '" is deprecated. Please use "' + current + '" instead'); + } +}
true
Other
chartjs
Chart.js
5a99dff5f7eeaa3c59ae9c473ccbe6738f289593.json
Convert src/helpers to use ES6 exports (#6797) * Canvas helpers exported * Easing helpers use exports * Math helper uses export * Linting * RTL options use export * Allow object spread operator * Rest of helpers use `export`
src/helpers/helpers.easing.js
@@ -5,7 +5,7 @@ * @namespace Chart.helpers.easing.effects * @see http://www.robertpenner.com/easing/ */ -var effects = { +export const effects = { linear: function(t) { return t; }, @@ -231,7 +231,3 @@ var effects = { return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5; } }; - -module.exports = { - effects: effects -};
true
Other
chartjs
Chart.js
5a99dff5f7eeaa3c59ae9c473ccbe6738f289593.json
Convert src/helpers to use ES6 exports (#6797) * Canvas helpers exported * Easing helpers use exports * Math helper uses export * Linting * RTL options use export * Allow object spread operator * Rest of helpers use `export`
src/helpers/helpers.math.js
@@ -4,41 +4,37 @@ * @alias Chart.helpers.math * @namespace */ -var exports = { - /** - * Returns an array of factors sorted from 1 to sqrt(value) - * @private - */ - _factorize: function(value) { - var result = []; - var sqrt = Math.sqrt(value); - var i; +/** + * Returns an array of factors sorted from 1 to sqrt(value) + * @private + */ +export function _factorize(value) { + var result = []; + var sqrt = Math.sqrt(value); + var i; - for (i = 1; i < sqrt; i++) { - if (value % i === 0) { - result.push(i); - result.push(value / i); - } - } - if (sqrt === (sqrt | 0)) { // if value is a square number - result.push(sqrt); + for (i = 1; i < sqrt; i++) { + if (value % i === 0) { + result.push(i); + result.push(value / i); } + } + if (sqrt === (sqrt | 0)) { // if value is a square number + result.push(sqrt); + } - result.sort(function(a, b) { - return a - b; - }).pop(); - return result; - }, + result.sort(function(a, b) { + return a - b; + }).pop(); + return result; +} - log10: Math.log10 || function(x) { - var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10. - // Check for whole powers of 10, - // which due to floating point rounding error should be corrected. - var powerOf10 = Math.round(exponent); - var isPowerOf10 = x === Math.pow(10, powerOf10); +export const log10 = Math.log10 || function(x) { + var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10. + // Check for whole powers of 10, + // which due to floating point rounding error should be corrected. + var powerOf10 = Math.round(exponent); + var isPowerOf10 = x === Math.pow(10, powerOf10); - return isPowerOf10 ? powerOf10 : exponent; - } + return isPowerOf10 ? powerOf10 : exponent; }; - -module.exports = exports;
true
Other
chartjs
Chart.js
5a99dff5f7eeaa3c59ae9c473ccbe6738f289593.json
Convert src/helpers to use ES6 exports (#6797) * Canvas helpers exported * Easing helpers use exports * Math helper uses export * Linting * RTL options use export * Allow object spread operator * Rest of helpers use `export`
src/helpers/helpers.options.js
@@ -1,9 +1,7 @@ 'use strict'; -var defaults = require('../core/core.defaults'); -var helpers = require('./helpers.core'); - -var valueOrDefault = helpers.valueOrDefault; +import defaults from '../core/core.defaults'; +import {isNullOrUndef, isArray, isObject, valueOrDefault} from './helpers.core'; /** * Converts the given font object into a CSS font string. @@ -12,7 +10,7 @@ var valueOrDefault = helpers.valueOrDefault; * @private */ function toFontString(font) { - if (!font || helpers.isNullOrUndef(font.size) || helpers.isNullOrUndef(font.family)) { + if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) { return null; } @@ -26,122 +24,120 @@ function toFontString(font) { * @alias Chart.helpers.options * @namespace */ -module.exports = { - /** - * Converts the given line height `value` in pixels for a specific font `size`. - * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em'). - * @param {number} size - The font size (in pixels) used to resolve relative `value`. - * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid). - * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height - * @since 2.7.0 - */ - toLineHeight: function(value, size) { - var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/); - if (!matches || matches[1] === 'normal') { - return size * 1.2; - } +/** + * Converts the given line height `value` in pixels for a specific font `size`. + * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em'). + * @param {number} size - The font size (in pixels) used to resolve relative `value`. + * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid). + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height + * @since 2.7.0 + */ +export function toLineHeight(value, size) { + var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/); + if (!matches || matches[1] === 'normal') { + return size * 1.2; + } - value = +matches[2]; + value = +matches[2]; - switch (matches[3]) { - case 'px': - return value; - case '%': - value /= 100; - break; - default: - break; - } + switch (matches[3]) { + case 'px': + return value; + case '%': + value /= 100; + break; + default: + break; + } - return size * value; - }, + return size * value; +} - /** - * Converts the given value into a padding object with pre-computed width/height. - * @param {number|object} value - If a number, set the value to all TRBL component, - * else, if and object, use defined properties and sets undefined ones to 0. - * @returns {object} The padding values (top, right, bottom, left, width, height) - * @since 2.7.0 - */ - toPadding: function(value) { - var t, r, b, l; +/** + * Converts the given value into a padding object with pre-computed width/height. + * @param {number|object} value - If a number, set the value to all TRBL component, + * else, if and object, use defined properties and sets undefined ones to 0. + * @returns {object} The padding values (top, right, bottom, left, width, height) + * @since 2.7.0 + */ +export function toPadding(value) { + var t, r, b, l; - if (helpers.isObject(value)) { - t = +value.top || 0; - r = +value.right || 0; - b = +value.bottom || 0; - l = +value.left || 0; - } else { - t = r = b = l = +value || 0; - } + if (isObject(value)) { + t = +value.top || 0; + r = +value.right || 0; + b = +value.bottom || 0; + l = +value.left || 0; + } else { + t = r = b = l = +value || 0; + } - return { - top: t, - right: r, - bottom: b, - left: l, - height: t + b, - width: l + r - }; - }, + return { + top: t, + right: r, + bottom: b, + left: l, + height: t + b, + width: l + r + }; +} - /** - * Parses font options and returns the font object. - * @param {object} options - A object that contains font options to be parsed. - * @return {object} The font object. - * @todo Support font.* options and renamed to toFont(). - * @private - */ - _parseFont: function(options) { - var globalDefaults = defaults.global; - var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize); - var font = { - family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily), - lineHeight: helpers.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size), - size: size, - style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle), - weight: null, - string: '' - }; +/** + * Parses font options and returns the font object. + * @param {object} options - A object that contains font options to be parsed. + * @return {object} The font object. + * @todo Support font.* options and renamed to toFont(). + * @private + */ +export function _parseFont(options) { + var globalDefaults = defaults.global; + var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize); + var font = { + family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily), + lineHeight: toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size), + size: size, + style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle), + weight: null, + string: '' + }; - font.string = toFontString(font); - return font; - }, + font.string = toFontString(font); + return font; +} - /** - * Evaluates the given `inputs` sequentially and returns the first defined value. - * @param {Array} inputs - An array of values, falling back to the last value. - * @param {object} [context] - If defined and the current value is a function, the value - * is called with `context` as first argument and the result becomes the new input. - * @param {number} [index] - If defined and the current value is an array, the value - * at `index` become the new input. - * @param {object} [info] - object to return information about resolution in - * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable. - * @since 2.7.0 - */ - resolve: function(inputs, context, index, info) { - var cacheable = true; - var i, ilen, value; +/** + * Evaluates the given `inputs` sequentially and returns the first defined value. + * @param {Array} inputs - An array of values, falling back to the last value. + * @param {object} [context] - If defined and the current value is a function, the value + * is called with `context` as first argument and the result becomes the new input. + * @param {number} [index] - If defined and the current value is an array, the value + * at `index` become the new input. + * @param {object} [info] - object to return information about resolution in + * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable. + * @since 2.7.0 + */ +export function resolve(inputs, context, index, info) { + var cacheable = true; + var i, ilen, value; - for (i = 0, ilen = inputs.length; i < ilen; ++i) { - value = inputs[i]; - if (value === undefined) { - continue; - } - if (context !== undefined && typeof value === 'function') { - value = value(context); - cacheable = false; - } - if (index !== undefined && helpers.isArray(value)) { - value = value[index]; - cacheable = false; - } - if (value !== undefined) { - if (info && !cacheable) { - info.cacheable = false; - } - return value; + for (i = 0, ilen = inputs.length; i < ilen; ++i) { + value = inputs[i]; + if (value === undefined) { + continue; + } + if (context !== undefined && typeof value === 'function') { + value = value(context); + cacheable = false; + } + if (index !== undefined && isArray(value)) { + value = value[index]; + cacheable = false; + } + if (value !== undefined) { + if (info && !cacheable) { + info.cacheable = false; } + return value; } } -}; +}
true
Other
chartjs
Chart.js
5a99dff5f7eeaa3c59ae9c473ccbe6738f289593.json
Convert src/helpers to use ES6 exports (#6797) * Canvas helpers exported * Easing helpers use exports * Math helper uses export * Linting * RTL options use export * Allow object spread operator * Rest of helpers use `export`
src/helpers/helpers.rtl.js
@@ -42,11 +42,11 @@ var getLtrAdapter = function() { }; }; -var getAdapter = function(rtl, rectX, width) { +const getAdapter = function(rtl, rectX, width) { return rtl ? getRtlAdapter(rectX, width) : getLtrAdapter(); }; -var overrideTextDirection = function(ctx, direction) { +const overrideTextDirection = function(ctx, direction) { var style, original; if (direction === 'ltr' || direction === 'rtl') { style = ctx.canvas.style; @@ -60,16 +60,16 @@ var overrideTextDirection = function(ctx, direction) { } }; -var restoreTextDirection = function(ctx) { +const restoreTextDirection = function(ctx) { var original = ctx.prevTextDirection; if (original !== undefined) { delete ctx.prevTextDirection; ctx.canvas.style.setProperty('direction', original[0], original[1]); } }; -module.exports = { - getRtlAdapter: getAdapter, - overrideTextDirection: overrideTextDirection, - restoreTextDirection: restoreTextDirection, +export { + getAdapter as getRtlAdapter, + overrideTextDirection, + restoreTextDirection };
true
Other
chartjs
Chart.js
5a99dff5f7eeaa3c59ae9c473ccbe6738f289593.json
Convert src/helpers to use ES6 exports (#6797) * Canvas helpers exported * Easing helpers use exports * Math helper uses export * Linting * RTL options use export * Allow object spread operator * Rest of helpers use `export`
src/helpers/index.js
@@ -1,8 +1,17 @@ 'use strict'; -module.exports = require('./helpers.core'); -module.exports.easing = require('./helpers.easing'); -module.exports.canvas = require('./helpers.canvas'); -module.exports.options = require('./helpers.options'); -module.exports.math = require('./helpers.math'); -module.exports.rtl = require('./helpers.rtl'); +import * as coreHelpers from './helpers.core'; +import * as canvas from './helpers.canvas'; +import * as easing from './helpers.easing'; +import * as options from './helpers.options'; +import * as math from './helpers.math'; +import * as rtl from './helpers.rtl'; + +export default { + ...coreHelpers, + canvas, + easing, + options, + math, + rtl, +};
true
Other
chartjs
Chart.js
5a99dff5f7eeaa3c59ae9c473ccbe6738f289593.json
Convert src/helpers to use ES6 exports (#6797) * Canvas helpers exported * Easing helpers use exports * Math helper uses export * Linting * RTL options use export * Allow object spread operator * Rest of helpers use `export`
test/specs/global.namespace.tests.js
@@ -37,10 +37,5 @@ describe('Chart namespace', function() { it('should be an object', function() { expect(Chart.helpers instanceof Object).toBeTruthy(); }); - it('should contains "helpers" namespaces', function() { - expect(Chart.helpers.easing instanceof Object).toBeTruthy(); - expect(Chart.helpers.canvas instanceof Object).toBeTruthy(); - expect(Chart.helpers.options instanceof Object).toBeTruthy(); - }); }); });
true
Other
chartjs
Chart.js
1f3cf3c28d85b650d7b74022871e2a141c3fc3fb.json
Remove createElement and pre-allocate arrays (#6788) * Remove createElement and pre-allocate arrays * Address review comment
docs/getting-started/v3-migration.md
@@ -70,6 +70,8 @@ Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released * `Chart.chart.chart` * `Chart.types` * `DatasetController.addElementAndReset` +* `DatasetController.createMetaData` +* `DatasetController.createMetaDataset` * `Element.getArea` * `Element.height` * `Element.initialize` @@ -104,7 +106,6 @@ Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released * `helpers.log10` was renamed to `helpers.math.log10` * `Chart.Animation.animationObject` was renamed to `Chart.Animation` * `Chart.Animation.chartInstance` was renamed to `Chart.Animation.chart` -* `DatasetController.createMetaData` and `DatasetController.createMetaDataset` were replaced with `DatasetController.createElement` * `DatasetController.updateElement` was renamed to `DatasetController.updateElements` * `TimeScale.getLabelCapacity` was renamed to `TimeScale._getLabelCapacity` * `TimeScale.tickFormatFunction` was renamed to `TimeScale._tickFormatFunction`
true
Other
chartjs
Chart.js
1f3cf3c28d85b650d7b74022871e2a141c3fc3fb.json
Remove createElement and pre-allocate arrays (#6788) * Remove createElement and pre-allocate arrays * Address review comment
src/core/core.datasetController.js
@@ -153,15 +153,15 @@ function applyStack(stack, value, dsIndex, allOther) { } function convertObjectDataToArray(data) { - var keys = Object.keys(data); - var adata = []; - var i, ilen, key; + const keys = Object.keys(data); + const adata = new Array(keys.length); + let i, ilen, key; for (i = 0, ilen = keys.length; i < ilen; ++i) { key = keys[i]; - adata.push({ + adata[i] = { x: key, y: data[key] - }); + }; } return adata; } @@ -358,17 +358,13 @@ helpers.extend(DatasetController.prototype, { } }, - createElement: function(type) { - return type && new type(); - }, - /** * @private */ _dataCheck: function() { - var me = this; - var dataset = me.getDataset(); - var data = dataset.data || (dataset.data = []); + const me = this; + const dataset = me.getDataset(); + const data = dataset.data || (dataset.data = []); // In order to correctly handle data addition/deletion animation (an thus simulate // real-time charts), we need to monitor these data modifications and synchronize @@ -420,19 +416,21 @@ helpers.extend(DatasetController.prototype, { }, addElements: function() { - var me = this; - var meta = me._cachedMeta; - var metaData = meta.data; - var i, ilen, data; + const me = this; + const meta = me._cachedMeta; + let i, ilen, data; me._dataCheck(); data = me._data; + const metaData = meta.data = new Array(data.length); for (i = 0, ilen = data.length; i < ilen; ++i) { - metaData[i] = metaData[i] || me.createElement(me.dataElementType); + metaData[i] = new me.dataElementType(); } - meta.dataset = meta.dataset || me.createElement(me.datasetElementType); + if (me.datasetElementType) { + meta.dataset = new me.datasetElementType(); + } }, buildOrUpdateElements: function() { @@ -516,14 +514,15 @@ helpers.extend(DatasetController.prototype, { const vId = vScale.id; const labels = iScale._getLabels(); const singleScale = iScale === vScale; - const parsed = []; - let i, ilen, item; + const parsed = new Array(count); + let i, ilen, index; - for (i = start, ilen = start + count; i < ilen; ++i) { - item = {}; - item[iId] = singleScale || iScale._parse(labels[i], i); - item[vId] = vScale._parse(data[i], i); - parsed.push(item); + for (i = 0, ilen = count; i < ilen; ++i) { + index = i + start; + parsed[i] = { + [iId]: singleScale || iScale._parse(labels[index], index), + [vId]: vScale._parse(data[index], index) + }; } return parsed; }, @@ -543,14 +542,16 @@ helpers.extend(DatasetController.prototype, { const {xScale, yScale} = meta; const xId = xScale.id; const yId = yScale.id; - const parsed = []; - let i, ilen, item; - for (i = start, ilen = start + count; i < ilen; ++i) { - item = data[i]; - parsed.push({ - [xId]: xScale._parse(item[0], i), - [yId]: yScale._parse(item[1], i) - }); + const parsed = new Array(count); + let i, ilen, index, item; + + for (i = 0, ilen = count; i < ilen; ++i) { + index = i + start; + item = data[index]; + parsed[i] = { + [xId]: xScale._parse(item[0], index), + [yId]: yScale._parse(item[1], index) + }; } return parsed; }, @@ -570,14 +571,16 @@ helpers.extend(DatasetController.prototype, { const {xScale, yScale} = meta; const xId = xScale.id; const yId = yScale.id; - const parsed = []; - let i, ilen, item; - for (i = start, ilen = start + count; i < ilen; ++i) { - item = data[i]; - parsed.push({ - [xId]: xScale._parseObject(item, 'x', i), - [yId]: yScale._parseObject(item, 'y', i) - }); + const parsed = new Array(count); + let i, ilen, index, item; + + for (i = 0, ilen = count; i < ilen; ++i) { + index = i + start; + item = data[index]; + parsed[i] = { + [xId]: xScale._parseObject(item, 'x', index), + [yId]: yScale._parseObject(item, 'y', index) + }; } return parsed; }, @@ -958,14 +961,15 @@ helpers.extend(DatasetController.prototype, { */ insertElements: function(start, count) { const me = this; - const elements = []; + const elements = new Array(count); const data = me._cachedMeta.data; let i; - for (i = start; i < start + count; ++i) { - elements.push(me.createElement(me.dataElementType)); + for (i = 0; i < count; ++i) { + elements[i] = new me.dataElementType(); } data.splice(start, 0, ...elements); + me._parse(start, count); me.updateElements(data, start, count); },
true
Other
chartjs
Chart.js
090b5aee1fdd866d0ebd5f687a9afe8259c03fa5.json
Improve autoSkip performance (#6783) * Improve autoSkip performance * Maintain tick ordering
src/core/core.scale.js
@@ -212,18 +212,6 @@ function parseTickFontOptions(options) { return {minor: minor, major: major}; } -function nonSkipped(ticksToFilter) { - var filtered = []; - var item, index, len; - for (index = 0, len = ticksToFilter.length; index < len; ++index) { - item = ticksToFilter[index]; - if (typeof item._index !== 'undefined') { - filtered.push(item); - } - } - return filtered; -} - function getEvenSpacing(arr) { var len = arr.length; var i, diff; @@ -272,29 +260,26 @@ function getMajorIndices(ticks) { return result; } -function skipMajors(ticks, majorIndices, spacing) { - var count = 0; - var next = majorIndices[0]; - var i, tick; +function skipMajors(ticks, newTicks, majorIndices, spacing) { + let count = 0; + let next = majorIndices[0]; + let i; spacing = Math.ceil(spacing); for (i = 0; i < ticks.length; i++) { - tick = ticks[i]; if (i === next) { - tick._index = i; + newTicks.push(ticks[i]); count++; next = majorIndices[count * spacing]; - } else { - delete tick.label; } } } -function skip(ticks, spacing, majorStart, majorEnd) { - var start = valueOrDefault(majorStart, 0); - var end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length); - var count = 0; - var length, i, tick, next; +function skip(ticks, newTicks, spacing, majorStart, majorEnd) { + const start = valueOrDefault(majorStart, 0); + const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length); + let count = 0; + let length, i, next; spacing = Math.ceil(spacing); if (majorEnd) { @@ -310,13 +295,10 @@ function skip(ticks, spacing, majorStart, majorEnd) { } for (i = Math.max(start, 0); i < end; i++) { - tick = ticks[i]; if (i === next) { - tick._index = i; + newTicks.push(ticks[i]); count++; next = Math.round(start + count * spacing); - } else { - delete tick.label; } } } @@ -910,35 +892,36 @@ class Scale extends Element { * @private */ _autoSkip(ticks) { - var me = this; - var tickOpts = me.options.ticks; - var axisLength = me._length; - var ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1; - var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : []; - var numMajorIndices = majorIndices.length; - var first = majorIndices[0]; - var last = majorIndices[numMajorIndices - 1]; - var i, ilen, spacing, avgMajorSpacing; + const me = this; + const tickOpts = me.options.ticks; + const axisLength = me._length; + const ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1; + const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : []; + const numMajorIndices = majorIndices.length; + const first = majorIndices[0]; + const last = majorIndices[numMajorIndices - 1]; + const newTicks = []; // If there are too many major ticks to display them all if (numMajorIndices > ticksLimit) { - skipMajors(ticks, majorIndices, numMajorIndices / ticksLimit); - return nonSkipped(ticks); + skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit); + return newTicks; } - spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit); + const spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit); if (numMajorIndices > 0) { + let i, ilen; + const avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null; + skip(ticks, newTicks, spacing, helpers.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first); for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) { - skip(ticks, spacing, majorIndices[i], majorIndices[i + 1]); + skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]); } - avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null; - skip(ticks, spacing, helpers.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first); - skip(ticks, spacing, last, helpers.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing); - return nonSkipped(ticks); + skip(ticks, newTicks, spacing, last, helpers.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing); + return newTicks; } - skip(ticks, spacing); - return nonSkipped(ticks); + skip(ticks, newTicks, spacing); + return newTicks; } /**
false
Other
chartjs
Chart.js
d5393003acb19164d6112e5c4745c37e6a9ee7be.json
Add min/max to performance documentation (#6785) * Add min/max to performance documentation * Review1 * Review2
docs/general/performance.md
@@ -34,6 +34,31 @@ new Chart(ctx, { }); ``` +## Specify `min` and `max` for scales + +If you specify the `min` and `max`, the scale does not have to compute the range from the data. + +```javascript +new Chart(ctx, { + type: 'line', + data: data, + options: { + scales: { + x: { + type: 'time', + min: new Date('2019-01-01').valueOf(), + max: new Date('2019-12-31').valueOf() + }, + y: { + type: 'linear', + min: 0, + max: 100 + } + } + } +}); +``` + ## Data Decimation Decimating your data will achieve the best results. When there is a lot of data to display on the graph, it doesn't make sense to show tens of thousands of data points on a graph that is only a few hundred pixels wide.
false
Other
chartjs
Chart.js
5eed101a53c424e9c37debd8669d4cadb495448e.json
Use correct dataset index in parseVisibleItems (#6786) * Use correct dataset index * Review1
src/core/core.interaction.js
@@ -25,15 +25,15 @@ function getRelativePosition(e, chart) { * @param {function} handler - the callback to execute for each visible item */ function parseVisibleItems(chart, handler) { - var metasets = chart._getSortedVisibleDatasetMetas(); - var metadata, i, j, ilen, jlen, element; + const metasets = chart._getSortedVisibleDatasetMetas(); + let index, data, element; - for (i = 0, ilen = metasets.length; i < ilen; ++i) { - metadata = metasets[i].data; - for (j = 0, jlen = metadata.length; j < jlen; ++j) { - element = metadata[j]; + for (let i = 0, ilen = metasets.length; i < ilen; ++i) { + ({index, data} = metasets[i]); + for (let j = 0, jlen = data.length; j < jlen; ++j) { + element = data[j]; if (!element._view.skip) { - handler(element, i, j); + handler(element, index, j); } } }
false
Other
chartjs
Chart.js
e6cf2fe8b80bd6cc00d20a4047afc3ac4d809e68.json
Fix broken tests (#6780)
test/fixtures/plugin.filler/fill-line-boundary-origin-span-dual.json
@@ -23,12 +23,12 @@ "legend": false, "title": false, "scales": { - "xAxes": [{ + "x": { "display": false - }], - "yAxes": [{ + }, + "y": { "display": false - }] + } }, "elements": { "point": {
true
Other
chartjs
Chart.js
e6cf2fe8b80bd6cc00d20a4047afc3ac4d809e68.json
Fix broken tests (#6780)
test/fixtures/plugin.filler/fill-line-boundary-origin-spline-above.json
@@ -23,12 +23,12 @@ "legend": false, "title": false, "scales": { - "xAxes": [{ + "x": { "display": false - }], - "yAxes": [{ + }, + "y": { "display": false - }] + } }, "elements": { "point": {
true
Other
chartjs
Chart.js
e6cf2fe8b80bd6cc00d20a4047afc3ac4d809e68.json
Fix broken tests (#6780)
test/fixtures/plugin.filler/fill-line-dataset-dual.json
@@ -21,12 +21,12 @@ "legend": false, "title": false, "scales": { - "xAxes": [{ + "x": { "display": false - }], - "yAxes": [{ + }, + "y": { "display": false - }] + } }, "elements": { "point": {
true
Other
chartjs
Chart.js
e6cf2fe8b80bd6cc00d20a4047afc3ac4d809e68.json
Fix broken tests (#6780)
test/fixtures/plugin.filler/fill-line-dataset-span-dual.json
@@ -43,12 +43,12 @@ "legend": false, "title": false, "scales": { - "xAxes": [{ + "x": { "display": false - }], - "yAxes": [{ + }, + "y": { "display": false - }] + } }, "elements": { "point": {
true
Other
chartjs
Chart.js
e6cf2fe8b80bd6cc00d20a4047afc3ac4d809e68.json
Fix broken tests (#6780)
test/fixtures/plugin.filler/fill-line-dataset-spline-span-above.json
@@ -39,12 +39,12 @@ "legend": false, "title": false, "scales": { - "xAxes": [{ + "x": { "display": false - }], - "yAxes": [{ + }, + "y": { "display": false - }] + } }, "elements": { "point": {
true
Other
chartjs
Chart.js
e6cf2fe8b80bd6cc00d20a4047afc3ac4d809e68.json
Fix broken tests (#6780)
test/fixtures/plugin.filler/fill-line-dataset-spline-span-below.json
@@ -39,12 +39,12 @@ "legend": false, "title": false, "scales": { - "xAxes": [{ + "x": { "display": false - }], - "yAxes": [{ + }, + "y": { "display": false - }] + } }, "elements": { "point": {
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/README.md
@@ -43,9 +43,9 @@ var myChart = new Chart(ctx, { }, options: { scales: { - yAxes: [{ + y: { beginAtZero: true - }] + } } } });
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/axes/cartesian/README.md
@@ -38,7 +38,8 @@ The following options are common to all cartesian axes but do not apply to other | `padding` | `number` | `0` | Padding between the tick label and the axis. When set on a vertical axis, this applies in the horizontal (X) direction. When set on a horizontal axis, this applies in the vertical (Y) direction. ### Axis ID -The properties `dataset.xAxisID` or `dataset.yAxisID` have to match the scale properties `scales.xAxes.id` or `scales.yAxes.id`. This is especially needed if multi-axes charts are used. + +The properties `dataset.xAxisID` or `dataset.yAxisID` have to match to `scales` property. This is especially needed if multi-axes charts are used. ```javascript var myChart = new Chart(ctx, { @@ -54,11 +55,10 @@ var myChart = new Chart(ctx, { }, options: { scales: { - yAxes: [{ - id: 'first-y-axis', + 'first-y-axis': { type: 'linear' - }, { - id: 'second-y-axis', + }, + 'second-y-axis': { type: 'linear' }] } @@ -93,12 +93,11 @@ var myChart = new Chart(ctx, { }, options: { scales: { - yAxes: [{ - id: 'left-y-axis', + 'left-y-axis': { type: 'linear', position: 'left' - }, { - id: 'right-y-axis', + }, + 'right-y-axis': { type: 'linear', position: 'right' }]
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/axes/cartesian/category.md
@@ -25,10 +25,10 @@ let chart = new Chart(ctx, { data: ... options: { scales: { - xAxes: [{ + x: { type: 'category', labels: ['January', 'February', 'March', 'April', 'May', 'June'] - }] + } } } }); @@ -58,9 +58,9 @@ let chart = new Chart(ctx, { }, options: { scales: { - xAxes: [{ + x: { min: 'March' - }] + } } } });
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/axes/cartesian/linear.md
@@ -45,10 +45,10 @@ let chart = new Chart(ctx, { }, options: { scales: { - yAxes: [{ + y: { suggestedMin: 50, suggestedMax: 100 - }] + } } } }); @@ -65,13 +65,13 @@ This example sets up a chart with a y axis that creates ticks at `0, 0.5, 1, 1.5 ```javascript let options = { scales: { - yAxes: [{ + y: { max: 5, min: 0, ticks: { stepSize: 0.5 } - }] + } } }; ```
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/axes/cartesian/time.md
@@ -67,18 +67,19 @@ var chart = new Chart(ctx, { data: data, options: { scales: { - xAxes: [{ + x: { type: 'time', time: { unit: 'month' } - }] + } } } }); ``` ### Display Formats + The following display formats are used to configure how different time units are formed into strings for the axis tick marks. See [Moment.js](https://momentjs.com/docs/#/displaying/format/) for the allowable format strings. Name | Default | Example @@ -101,14 +102,14 @@ var chart = new Chart(ctx, { data: data, options: { scales: { - xAxes: [{ + x: { type: 'time', time: { displayFormats: { quarter: 'MMM YYYY' } } - }] + } } } }); @@ -127,10 +128,10 @@ var chart = new Chart(ctx, { data: data, options: { scales: { - xAxes: [{ + x: { type: 'time', distribution: 'series' - }] + } } } });
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/axes/labelling.md
@@ -31,14 +31,14 @@ var chart = new Chart(ctx, { data: data, options: { scales: { - yAxes: [{ + y: { ticks: { // Include a dollar sign in the ticks callback: function(value, index, values) { return '$' + value; } } - }] + } } } });
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/charts/bar.md
@@ -41,9 +41,9 @@ A bar chart provides a way of showing data values represented as vertical bars. }, "options": { "scales": { - "yAxes": [{ + "y": { "beginAtZero": true - }] + } } } } @@ -160,14 +160,17 @@ data: { }] }; ``` + ### barThickness + If this value is a number, it is applied to the width of each bar, in pixels. When this is enforced, `barPercentage` and `categoryPercentage` are ignored. If set to `'flex'`, the base sample widths are calculated automatically based on the previous and following samples so that they take the full available widths without overlap. Then, bars are sized using `barPercentage` and `categoryPercentage`. There is no gap when the percentage options are 1. This mode generates bars with different widths when data are not evenly spaced. If not set (default), the base sample widths are calculated using the smallest interval that prevents bar overlapping, and bars are sized using `barPercentage` and `categoryPercentage`. This mode always generates bars equally sized. ## Scale Configuration + The bar chart sets unique default values for the following configuration from the associated `scale` options: | Name | Type | Default | Description @@ -180,16 +183,17 @@ The bar chart sets unique default values for the following configuration from th ```javascript options = { scales: { - xAxes: [{ + x: { gridLines: { offsetGridLines: true } - }] + } } }; ``` ### offsetGridLines + If true, the bars for a particular data point fall between the grid lines. The grid line will move to the left by one half of the tick interval, which is the space between the grid lines. If false, the grid line will go right down the middle of the bars. This is set to true for a category scale in a bar chart while false for other scales or chart types by default. ## Default Options @@ -249,12 +253,12 @@ var stackedBar = new Chart(ctx, { data: data, options: { scales: { - xAxes: [{ + x: { stacked: true - }], - yAxes: [{ + }, + y: { stacked: true - }] + } } } }); @@ -267,6 +271,7 @@ The following dataset properties are specific to stacked bar charts. | `stack` | `string` | The ID of the group to which this dataset belongs to (when stacked, each group will be a separate stack). ## Horizontal Bar Chart + A horizontal bar chart is a variation on a vertical bar chart. It is sometimes used to show trend data, and the comparison of multiple data sets side by side. {% chartjs %} { @@ -300,9 +305,9 @@ A horizontal bar chart is a variation on a vertical bar chart. It is sometimes u }, "options": { "scales": { - "xAxes": [{ + "x": { "beginAtZero": true - }] + } } } }
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/charts/line.md
@@ -211,9 +211,9 @@ var stackedLine = new Chart(ctx, { data: data, options: { scales: { - yAxes: [{ + y: { stacked: true - }] + } } } });
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/charts/mixed.md
@@ -61,9 +61,9 @@ At this point we have a chart rendering how we'd like. It's important to note th }, "options": { "scales": { - "yAxes": [{ + "y": { "beginAtZero": true - }] + } } } }
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/charts/scatter.md
@@ -22,10 +22,10 @@ var scatterChart = new Chart(ctx, { }, options: { scales: { - xAxes: [{ + x: { type: 'linear', position: 'bottom' - }] + } } } });
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/developers/axes.md
@@ -24,9 +24,9 @@ var lineChart = new Chart(ctx, { type: 'line', options: { scales: { - yAxes: [{ + y: { type: 'myScale' // this is the same key that was passed to the registerScaleType function - }] + } } } });
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/developers/updates.md
@@ -45,12 +45,12 @@ function updateConfigAsNewObject(chart) { text: 'Chart.js' }, scales: { - xAxes: [{ + x: { display: true - }], - yAxes: [{ + }, + y: { display: true - }] + } } }; chart.update(); @@ -64,30 +64,29 @@ Variables referencing any one from `chart.scales` would be lost after updating s ```javascript function updateScales(chart) { - var xScale = chart.scales['x-axis-0']; - var yScale = chart.scales['y-axis-0']; + var xScale = chart.scales.x; + var yScale = chart.scales.y; chart.options.scales = { - xAxes: [{ - id: 'newId', + newId: { display: true - }], - yAxes: [{ + }, + y: { display: true, type: 'logarithmic' - }] + } }; chart.update(); // need to update the reference - xScale = chart.scales['newId']; - yScale = chart.scales['y-axis-0']; + xScale = chart.scales.newId; + yScale = chart.scales.y; } ``` -You can also update a specific scale either by specifying its index or id. +You can also update a specific scale either by its id. ```javascript function updateScale(chart) { - chart.options.scales.yAxes[0] = { + chart.options.scales.y = { type: 'logarithmic' }; chart.update();
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/getting-started/usage.md
@@ -53,9 +53,9 @@ var myChart = new Chart(ctx, { }, options: { scales: { - yAxes: [{ + y: { beginAtZero: true - }] + } } } });
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
docs/getting-started/v3-migration.md
@@ -33,20 +33,21 @@ Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released ### Options * The dataset option `tension` was renamed to `lineTension` +* `scales.[x/y]Axes` arrays were removed. Scales are now configured directly to `options.scales` object with the object key being the scale Id. * `scales.[x/y]Axes.barPercentage` was moved to dataset option `barPercentage` * `scales.[x/y]Axes.barThickness` was moved to dataset option `barThickness` * `scales.[x/y]Axes.categoryPercentage` was moved to dataset option `categoryPercentage` * `scales.[x/y]Axes.minBarLength` was moved to dataset option `minBarLength` * `scales.[x/y]Axes.maxBarThickness` was moved to dataset option `maxBarThickness` -* `scales.[x/y]Axes.ticks.beginAtZero` was renamed to `scales.[x/y]Axes.beginAtZero` -* `scales.[x/y]Axes.ticks.max` was renamed to `scales.[x/y]Axes.max` -* `scales.[x/y]Axes.ticks.min` was renamed to `scales.[x/y]Axes.min` -* `scales.[x/y]Axes.ticks.reverse` was renamed to `scales.[x/y]Axes.reverse` -* `scales.[x/y]Axes.ticks.suggestedMax` was renamed to `scales.[x/y]Axes.suggestedMax` -* `scales.[x/y]Axes.ticks.suggestedMin` was renamed to `scales.[x/y]Axes.suggestedMin` -* `scales.[x/y]Axes.time.format` was renamed to `scales.[x/y]Axes.time.parser` -* `scales.[x/y]Axes.time.max` was renamed to `scales.[x/y]Axes.max` -* `scales.[x/y]Axes.time.min` was renamed to `scales.[x/y]Axes.min` +* `scales.[x/y]Axes.ticks.beginAtZero` was renamed to `scales[id].beginAtZero` +* `scales.[x/y]Axes.ticks.max` was renamed to `scales[id].max` +* `scales.[x/y]Axes.ticks.min` was renamed to `scales[id].min` +* `scales.[x/y]Axes.ticks.reverse` was renamed to `scales[id].reverse` +* `scales.[x/y]Axes.ticks.suggestedMax` was renamed to `scales[id].suggestedMax` +* `scales.[x/y]Axes.ticks.suggestedMin` was renamed to `scales[id].suggestedMin` +* `scales.[x/y]Axes.time.format` was renamed to `scales[id].time.parser` +* `scales.[x/y]Axes.time.max` was renamed to `scales[id].max` +* `scales.[x/y]Axes.time.min` was renamed to `scales[id].min` ## Developer migration
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
samples/charts/area/line-boundaries.html
@@ -59,12 +59,12 @@ } }, scales: { - xAxes: [{ + x: { ticks: { autoSkip: false, maxRotation: 0 } - }] + } } };
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
samples/charts/area/line-datasets.html
@@ -114,9 +114,9 @@ } }, scales: { - yAxes: [{ - stacked: true - }] + y: { + stacked: true, + } }, plugins: { filler: {
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
samples/charts/area/line-stacked.html
@@ -98,19 +98,19 @@ mode: 'index' }, scales: { - xAxes: [{ + x: { scaleLabel: { display: true, labelString: 'Month' } - }], - yAxes: [{ + }, + y: { stacked: true, scaleLabel: { display: true, labelString: 'Value' } - }] + } } } };
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
samples/charts/bar/multi-axis.html
@@ -33,7 +33,7 @@ window.chartColors.purple, window.chartColors.red ], - yAxisID: 'y-axis-1', + yAxisID: 'y', data: [ randomScalingFactor(), randomScalingFactor(), @@ -46,7 +46,7 @@ }, { label: 'Dataset 2', backgroundColor: window.chartColors.grey, - yAxisID: 'y-axis-2', + yAxisID: 'y1', data: [ randomScalingFactor(), randomScalingFactor(), @@ -75,20 +75,19 @@ intersect: true }, scales: { - yAxes: [{ - type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance + y: { + type: 'linear', display: true, position: 'left', - id: 'y-axis-1', - }, { - type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance + }, + y1: { + type: 'linear', display: true, position: 'right', - id: 'y-axis-2', gridLines: { drawOnChartArea: false } - }], + }, } } });
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
samples/charts/bar/stacked-group.html
@@ -80,12 +80,12 @@ }, responsive: true, scales: { - xAxes: [{ + x: { stacked: true, - }], - yAxes: [{ + }, + y: { stacked: true - }] + } } } });
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
samples/charts/bar/stacked.html
@@ -77,12 +77,12 @@ }, responsive: true, scales: { - xAxes: [{ + x: { stacked: true, - }], - yAxes: [{ + }, + y: { stacked: true - }] + } } } });
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
samples/charts/line/basic.html
@@ -76,20 +76,20 @@ intersect: true }, scales: { - xAxes: [{ + x: { display: true, scaleLabel: { display: true, labelString: 'Month' } - }], - yAxes: [{ + }, + y: { display: true, scaleLabel: { display: true, labelString: 'Value' } - }] + } } } };
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
samples/charts/line/interpolation-modes.html
@@ -64,21 +64,21 @@ mode: 'index' }, scales: { - xAxes: [{ + x: { display: true, scaleLabel: { display: true } - }], - yAxes: [{ + }, + y: { display: true, scaleLabel: { display: true, labelString: 'Value' }, suggestedMin: -10, - suggestedMax: 200, - }] + suggestedMax: 200 + } } } };
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
samples/charts/line/line-styles.html
@@ -83,20 +83,20 @@ intersect: true }, scales: { - xAxes: [{ + x: { display: true, scaleLabel: { display: true, labelString: 'Month' } - }], - yAxes: [{ + }, + y: { display: true, scaleLabel: { display: true, labelString: 'Value' } - }] + } } } };
true
Other
chartjs
Chart.js
ce74eb76a1ad29c0ccaeb8cf3e606d82e38f2ac7.json
Convert axis options from arrays to objects (#6773) * Convert axis options from arrays to objects * Updated all chart type defaults * Throw errors when axis type or position are not specified * Avoid raising unnecessary errors when merging options into the default configs * Fix additional tests * Ensure scale defaults are set if type is not explicitly defined * Another step * Include `scale` as `firstIDs.r` * update docs * Update for buildOrUpdateScales * Update migration guide * Add test back
samples/charts/line/multi-axis.html
@@ -36,7 +36,7 @@ randomScalingFactor(), randomScalingFactor() ], - yAxisID: 'y-axis-1', + yAxisID: 'y', }, { label: 'My Second dataset', borderColor: window.chartColors.blue, @@ -51,7 +51,7 @@ randomScalingFactor(), randomScalingFactor() ], - yAxisID: 'y-axis-2' + yAxisID: 'y1' }] }; @@ -69,22 +69,21 @@ text: 'Chart.js Line Chart - Multi Axis' }, scales: { - yAxes: [{ + y: { type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance display: true, position: 'left', - id: 'y-axis-1', - }, { + }, + y1: { type: 'linear', // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance display: true, position: 'right', - id: 'y-axis-2', // grid line settings gridLines: { drawOnChartArea: false, // only want the grid lines for one axis to show up }, - }], + }, } } });
true