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 | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/charts/line.md | @@ -166,7 +166,7 @@ If the `steppedLine` value is set to anything other than false, `lineTension` wi
## Configuration Options
-The line chart defines the following configuration options. These options are merged with the global chart configuration options, `Chart.defaults.global`, to form the options passed to the chart.
+The line chart defines the following configuration options. These options are merged with the global chart configuration options, `Chart.defaults`, to form the options passed to the chart.
| Name | Type | Default | Description
| ---- | ---- | ------- | ----------- | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/charts/radar.md | @@ -155,7 +155,7 @@ The interaction with each point can be controlled with the following properties:
## Configuration Options
-The radar chart defines the following configuration options. These options are merged with the global chart configuration options, `Chart.defaults.global`, to form the options passed to the chart.
+The radar chart defines the following configuration options. These options are merged with the global chart configuration options, `Chart.defaults`, to form the options passed to the chart.
| Name | Type | Default | Description
| ---- | ---- | ------- | ----------- | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/configuration/README.md | @@ -6,12 +6,12 @@ The configuration is used to change how the chart behaves. There are properties
This concept was introduced in Chart.js 1.0 to keep configuration [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself), and allow for changing options globally across chart types, avoiding the need to specify options for each instance, or the default for a particular chart type.
-Chart.js merges the options object passed to the chart with the global configuration using chart type defaults and scales defaults appropriately. This way you can be as specific as you would like in your individual chart configuration, while still changing the defaults for all chart types where applicable. The global general options are defined in `Chart.defaults.global`. The defaults for each chart type are discussed in the documentation for that chart type.
+Chart.js merges the options object passed to the chart with the global configuration using chart type defaults and scales defaults appropriately. This way you can be as specific as you would like in your individual chart configuration, while still changing the defaults for all chart types where applicable. The global general options are defined in `Chart.defaults`. The defaults for each chart type are discussed in the documentation for that chart type.
The following example would set the hover mode to 'nearest' for all charts where this was not overridden by the chart type defaults or the options passed to the constructor on creation.
```javascript
-Chart.defaults.global.hover.mode = 'nearest';
+Chart.defaults.hover.mode = 'nearest';
// Hover mode is set to nearest because it was not overridden here
var chartHoverModeNearest = new Chart(ctx, {
@@ -38,7 +38,7 @@ Options may be configured directly on the dataset. The dataset options can be ch
- per dataset: dataset.*
- per chart: options.datasets[type].*
-- or globally: Chart.defaults.global.datasets[type].*
+- or globally: Chart.defaults.datasets[type].*
where type corresponds to the dataset type.
@@ -48,7 +48,7 @@ The following example would set the `showLine` option to 'false' for all line da
```javascript
// Do not show lines for all datasets by default
-Chart.defaults.global.datasets.line.showLine = false;
+Chart.defaults.datasets.line.showLine = false;
// This chart would show a line only for the third dataset
var chart = new Chart(ctx, { | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/configuration/animations.md | @@ -4,7 +4,7 @@ Chart.js animates charts out of the box. A number of options are provided to con
## Animation Configuration
-The following animation options are available. The global options for are defined in `Chart.defaults.global.animation`.
+The following animation options are available. The global options for are defined in `Chart.defaults.animation`.
| Name | Type | Default | Description
| ---- | ---- | ------- | ----------- | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/configuration/elements.md | @@ -4,16 +4,16 @@ While chart types provide settings to configure the styling of each dataset, you
## Global Configuration
-The element options can be specified per chart or globally. The global options for elements are defined in `Chart.defaults.global.elements`. For example, to set the border width of all bar charts globally you would do:
+The element options can be specified per chart or globally. The global options for elements are defined in `Chart.defaults.elements`. For example, to set the border width of all bar charts globally you would do:
```javascript
-Chart.defaults.global.elements.rectangle.borderWidth = 2;
+Chart.defaults.elements.rectangle.borderWidth = 2;
```
## Point Configuration
Point elements are used to represent the points in a line, radar or bubble chart.
-Global point options: `Chart.defaults.global.elements.point`.
+Global point options: `Chart.defaults.elements.point`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
@@ -46,7 +46,7 @@ If the value is an image, that image is drawn on the canvas using [drawImage](ht
## Line Configuration
Line elements are used to represent the line in a line chart.
-Global line options: `Chart.defaults.global.elements.line`.
+Global line options: `Chart.defaults.elements.line`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
@@ -59,14 +59,14 @@ Global line options: `Chart.defaults.global.elements.line`.
| `borderDashOffset` | `number` | `0.0` | Line dash offset. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
| `borderJoinStyle` | `string` | `'miter'` | Line join style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin).
| `capBezierPoints` | `boolean` | `true` | `true` to keep Bézier control inside the chart, `false` for no restriction.
-| `cubicInterpolationMode` | `string` | `'default'` | Interpolation mode to apply. [See more...](../charts/line.md#cubicinterpolationmode)
+| `cubicInterpolationMode` | `string` | `'default'` | Interpolation mode to apply. [See more...](../charts/line.md#cubicinterpolationmode)
| `fill` | <code>boolean|string</code> | `true` | How to fill the area under the line. See [area charts](../charts/area.md#filling-modes).
| `stepped` | `boolean` | `false` | `true` to show the line as a stepped line (`tension` will be ignored).
## Rectangle Configuration
Rectangle elements are used to represent the bars in a bar chart.
-Global rectangle options: `Chart.defaults.global.elements.rectangle`.
+Global rectangle options: `Chart.defaults.elements.rectangle`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
@@ -78,7 +78,7 @@ Global rectangle options: `Chart.defaults.global.elements.rectangle`.
## Arc Configuration
Arcs are used in the polar area, doughnut and pie charts.
-Global arc options: `Chart.defaults.global.elements.arc`.
+Global arc options: `Chart.defaults.elements.arc`.
| Name | Type | Default | Description
| ---- | ---- | ------- | ----------- | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/configuration/layout.md | @@ -1,6 +1,6 @@
# Layout Configuration
-The layout configuration is passed into the `options.layout` namespace. The global options for the chart layout is defined in `Chart.defaults.global.layout`.
+The layout configuration is passed into the `options.layout` namespace. The global options for the chart layout is defined in `Chart.defaults.layout`.
| Name | Type | Default | Description
| ---- | ---- | ------- | ----------- | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/configuration/legend.md | @@ -4,7 +4,7 @@ The chart legend displays data about the datasets that are appearing on the char
## Configuration options
-The legend configuration is passed into the `options.legend` namespace. The global options for the chart legend is defined in `Chart.defaults.global.legend`.
+The legend configuration is passed into the `options.legend` namespace. The global options for the chart legend is defined in `Chart.defaults.legend`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
@@ -138,7 +138,7 @@ function(e, legendItem) {
Lets say we wanted instead to link the display of the first two datasets. We could change the click handler accordingly.
```javascript
-var defaultLegendClickHandler = Chart.defaults.global.legend.onClick;
+var defaultLegendClickHandler = Chart.defaults.legend.onClick;
var newLegendClickHandler = function (e, legendItem) {
var index = legendItem.datasetIndex;
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/configuration/title.md | @@ -3,7 +3,7 @@
The chart title defines text to draw at the top of the chart.
## Title Configuration
-The title configuration is passed into the `options.title` namespace. The global options for the chart title is defined in `Chart.defaults.global.title`.
+The title configuration is passed into the `options.title` namespace. The global options for the chart title is defined in `Chart.defaults.title`.
| Name | Type | Default | Description
| ---- | ---- | ------- | ----------- | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/configuration/tooltip.md | @@ -2,7 +2,7 @@
## Tooltip Configuration
-The tooltip configuration is passed into the `options.tooltips` namespace. The global options for the chart tooltips is defined in `Chart.defaults.global.tooltips`.
+The tooltip configuration is passed into the `options.tooltips` namespace. The global options for the chart tooltips is defined in `Chart.defaults.tooltips`.
| Name | Type | Default | Description
| ---- | ---- | ------- | ----------- | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/developers/charts.md | @@ -83,7 +83,7 @@ Chart.defaults.derivedBubble = Chart.defaults.bubble;
// Sets the default dataset config for 'derivedBubble' to be the same as the bubble dataset defaults.
// It looks like a bug exists when the dataset defaults don't exist
-Chart.defaults.global.datasets.derivedBubble = Chart.defaults.global.datasets.bubble;
+Chart.defaults.datasets.derivedBubble = Chart.defaults.datasets.bubble;
// I think the recommend using Chart.controllers.bubble.extend({ extensions here });
var custom = Chart.controllers.bubble.extend({ | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/general/colors.md | @@ -1,6 +1,6 @@
# Colors
-When supplying colors to Chart options, you can use a number of formats. You can specify the color as a string in hexadecimal, RGB, or HSL notations. If a color is needed, but not specified, Chart.js will use the global default color. This color is stored at `Chart.defaults.global.defaultColor`. It is initially set to `'rgba(0, 0, 0, 0.1)'`.
+When supplying colors to Chart options, you can use a number of formats. You can specify the color as a string in hexadecimal, RGB, or HSL notations. If a color is needed, but not specified, Chart.js will use the global default color. This color is stored at `Chart.defaults.color`. It is initially set to `'rgba(0, 0, 0, 0.1)'`.
You can also pass a [CanvasGradient](https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient) object. You will need to create this before passing to the chart, but using it you can achieve some interesting effects.
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/general/fonts.md | @@ -1,11 +1,11 @@
# Fonts
-There are 4 special global settings that can change all of the fonts on the chart. These options are in `Chart.defaults.global`. The global font settings only apply when more specific options are not included in the config.
+There are 4 special global settings that can change all of the fonts on the chart. These options are in `Chart.defaults`. The global font settings only apply when more specific options are not included in the config.
For example, in this chart the text will all be red except for the labels in the legend.
```javascript
-Chart.defaults.global.defaultFontColor = 'red';
+Chart.defaults.fontColor = 'red';
let chart = new Chart(ctx, {
type: 'line',
data: data,
@@ -22,10 +22,10 @@ let chart = new Chart(ctx, {
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
-| `defaultFontColor` | `Color` | `'#666'` | Default font color for all text.
-| `defaultFontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Default font family for all text.
-| `defaultFontSize` | `number` | `12` | Default font size (in px) for text. Does not apply to radialLinear scale point labels.
-| `defaultFontStyle` | `string` | `'normal'` | Default font style. Does not apply to tooltip title or footer. Does not apply to chart title.
+| `fontColor` | `Color` | `'#666'` | Default font color for all text.
+| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Default font family for all text.
+| `fontSize` | `number` | `12` | Default font size (in px) for text. Does not apply to radialLinear scale point labels.
+| `fontStyle` | `string` | `'normal'` | Default font style. Does not apply to tooltip title or footer. Does not apply to chart title.
## Missing Fonts
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/general/interactions/README.md | @@ -1,6 +1,6 @@
# Interactions
-The hover configuration is passed into the `options.hover` namespace. The global hover configuration is at `Chart.defaults.global.hover`. To configure which events trigger chart interactions, see [events](./events.md#events).
+The hover configuration is passed into the `options.hover` namespace. The global hover configuration is at `Chart.defaults.hover`. To configure which events trigger chart interactions, see [events](./events.md#events).
| Name | Type | Default | Description
| ---- | ---- | ------- | ----------- | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | docs/getting-started/v3-migration.md | @@ -30,6 +30,17 @@ Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released
* The `hover` property of scriptable options `context` object was renamed to `active` to align it with the datalabels plugin.
* The `zeroLine*` options of axes were removed. Use scriptable scale options instead.
+## Defaults
+
+* `global` namespace was removed from `defaults`. So `Chart.defaults.global` is now `Chart.defaults`
+* `default` prefix was removed from defaults. For example `Chart.defaults.global.defaultColor` is now `Chart.defaults.color`
+ * `defaultColor` was renamed to `color`
+ * `defaultFontColor` was renamed to `fontColor`
+ * `defaultFontFamily` was renamed to `fontFamily`
+ * `defaultFontSize` was renamed to `fontSize`
+ * `defaultFontStyle` was renamed to `fontStyle`
+ * `defaultLineHeight` was renamed to `lineHeight`
+
### Options
* `scales.[x/y]Axes` arrays were removed. Scales are now configured directly to `options.scales` object with the object key being the scale Id. | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | samples/animations/loop.html | @@ -71,7 +71,7 @@
}
};
}
- return Chart.defaults.global.animation;
+ return Chart.defaults.animation;
},
elements: {
point: { | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | samples/tooltips/custom-line.html | @@ -38,7 +38,7 @@
<canvas id="chart"></canvas>
</div>
<script>
- Chart.defaults.global.pointHitDetectionRadius = 1;
+ Chart.defaults.pointHitDetectionRadius = 1;
var customTooltips = function(tooltip) {
// Tooltip Element | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | samples/tooltips/custom-pie.html | @@ -43,7 +43,7 @@
</div>
<script>
- Chart.defaults.global.tooltips.custom = function(tooltip) {
+ Chart.default.tooltips.custom = function(tooltip) {
// Tooltip Element
var tooltipEl = document.getElementById('chartjs-tooltip');
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/controllers/controller.bar.js | @@ -26,16 +26,14 @@ defaults._set('bar', {
}
});
-defaults._set('global', {
- datasets: {
- bar: {
- categoryPercentage: 0.8,
- barPercentage: 0.9,
- animation: {
- numbers: {
- type: 'number',
- properties: ['x', 'y', 'base', 'width', 'height']
- }
+defaults._set('datasets', {
+ bar: {
+ categoryPercentage: 0.8,
+ barPercentage: 0.9,
+ animation: {
+ numbers: {
+ type: 'number',
+ properties: ['x', 'y', 'base', 'width', 'height']
}
}
} | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/controllers/controller.horizontalBar.js | @@ -36,12 +36,10 @@ defaults._set('horizontalBar', {
}
});
-defaults._set('global', {
- datasets: {
- horizontalBar: {
- categoryPercentage: 0.8,
- barPercentage: 0.9
- }
+defaults._set('datasets', {
+ horizontalBar: {
+ categoryPercentage: 0.8,
+ barPercentage: 0.9
}
});
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/controllers/controller.scatter.js | @@ -27,11 +27,9 @@ defaults._set('scatter', {
}
});
-defaults._set('global', {
- datasets: {
- scatter: {
- showLine: false
- }
+defaults._set('datasets', {
+ scatter: {
+ showLine: false
}
});
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/core/core.animations.js | @@ -5,27 +5,25 @@ import Animation from './core.animation';
import defaults from '../core/core.defaults';
import {noop, extend, isObject} from '../helpers/helpers.core';
-defaults._set('global', {
- animation: {
- duration: 1000,
- easing: 'easeOutQuart',
- active: {
- duration: 400
- },
- resize: {
- duration: 0
- },
- numbers: {
- type: 'number',
- properties: ['x', 'y', 'borderWidth', 'radius', 'tension']
- },
- colors: {
- type: 'color',
- properties: ['borderColor', 'backgroundColor']
- },
- onProgress: noop,
- onComplete: noop
- }
+defaults._set('animation', {
+ duration: 1000,
+ easing: 'easeOutQuart',
+ active: {
+ duration: 400
+ },
+ resize: {
+ duration: 0
+ },
+ numbers: {
+ type: 'number',
+ properties: ['x', 'y', 'borderWidth', 'radius', 'tension']
+ },
+ colors: {
+ type: 'color',
+ properties: ['borderColor', 'backgroundColor']
+ },
+ onProgress: noop,
+ onComplete: noop
});
function copyOptions(target, values) { | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/core/core.controller.js | @@ -13,25 +13,6 @@ import Tooltip from './core.tooltip';
const valueOrDefault = helpers.valueOrDefault;
-defaults._set('global', {
- elements: {},
- events: [
- 'mousemove',
- 'mouseout',
- 'click',
- 'touchstart',
- 'touchmove'
- ],
- hover: {
- onHover: null,
- mode: 'nearest',
- intersect: true
- },
- onClick: null,
- maintainAspectRatio: true,
- responsive: true
-});
-
function mergeScaleConfig(config, options) {
options = options || {};
const chartDefaults = defaults[config.type] || {scales: {}};
@@ -103,7 +84,7 @@ function initConfig(config) {
const scaleConfig = mergeScaleConfig(config, config.options);
config.options = mergeConfig(
- defaults.global,
+ defaults,
defaults[config.type],
config.options || {});
@@ -126,7 +107,7 @@ function updateConfig(chart) {
const scaleConfig = mergeScaleConfig(chart.config, newOptions);
newOptions = mergeConfig(
- defaults.global,
+ defaults,
defaults[chart.config.type],
newOptions);
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/core/core.defaults.js | @@ -1,26 +1,36 @@
'use strict';
-var helpers = require('../helpers/helpers.core');
+import {merge} from '../helpers/helpers.core';
+
+export default {
+ color: 'rgba(0,0,0,0.1)',
+ elements: {},
+ events: [
+ 'mousemove',
+ 'mouseout',
+ 'click',
+ 'touchstart',
+ 'touchmove'
+ ],
+ fontColor: '#666',
+ fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
+ fontSize: 12,
+ fontStyle: 'normal',
+ lineHeight: 1.2,
+ hover: {
+ onHover: null,
+ mode: 'nearest',
+ intersect: true
+ },
+ maintainAspectRatio: true,
+ onClick: null,
+ responsive: true,
+ showLines: true,
-var defaults = {
/**
* @private
*/
_set: function(scope, values) {
- return helpers.merge(this[scope] || (this[scope] = {}), values);
+ return merge(this[scope] || (this[scope] = {}), values);
}
};
-
-// TODO(v3): remove 'global' from namespace. all default are global and
-// there's inconsistency around which options are under 'global'
-defaults._set('global', {
- defaultColor: 'rgba(0,0,0,0.1)',
- defaultFontColor: '#666',
- defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
- defaultFontSize: 12,
- defaultFontStyle: 'normal',
- defaultLineHeight: 1.2,
- showLines: true
-});
-
-module.exports = defaults; | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/core/core.layouts.js | @@ -198,14 +198,12 @@ function placeBoxes(boxes, chartArea, params) {
chartArea.y = y;
}
-defaults._set('global', {
- layout: {
- padding: {
- top: 0,
- right: 0,
- bottom: 0,
- left: 0
- }
+defaults._set('layout', {
+ padding: {
+ top: 0,
+ right: 0,
+ bottom: 0,
+ left: 0
}
});
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/core/core.plugins.js | @@ -3,9 +3,7 @@
var defaults = require('./core.defaults');
var helpers = require('../helpers/index');
-defaults._set('global', {
- plugins: {}
-});
+defaults._set('plugins', {});
/**
* The plugin service singleton
@@ -144,7 +142,7 @@ module.exports = {
}
if (opts === true) {
- opts = helpers.clone(defaults.global.plugins[id]);
+ opts = helpers.clone(defaults.plugins[id]);
}
plugins.push(plugin); | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/core/core.scale.js | @@ -200,7 +200,7 @@ function parseFontOptions(options, nestedOpts) {
fontStyle: valueOrDefault(nestedOpts.fontStyle, options.fontStyle),
lineHeight: valueOrDefault(nestedOpts.lineHeight, options.lineHeight)
}), {
- color: resolve([nestedOpts.fontColor, options.fontColor, defaults.global.defaultFontColor])
+ color: resolve([nestedOpts.fontColor, options.fontColor, defaults.fontColor])
});
}
@@ -1307,7 +1307,7 @@ class Scale extends Element {
return;
}
- var scaleLabelFontColor = valueOrDefault(scaleLabel.fontColor, defaults.global.defaultFontColor);
+ var scaleLabelFontColor = valueOrDefault(scaleLabel.fontColor, defaults.fontColor);
var scaleLabelFont = helpers.options._parseFont(scaleLabel);
var scaleLabelPadding = helpers.options.toPadding(scaleLabel.padding);
var halfLineHeight = scaleLabelFont.lineHeight / 2; | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/core/core.tooltip.js | @@ -8,106 +8,104 @@ const Animations = require('./core.animations');
const valueOrDefault = helpers.valueOrDefault;
const getRtlHelper = helpers.rtl.getRtlAdapter;
-defaults._set('global', {
- tooltips: {
- enabled: true,
- custom: null,
- mode: 'nearest',
- position: 'average',
- intersect: true,
- backgroundColor: 'rgba(0,0,0,0.8)',
- titleFontStyle: 'bold',
- titleSpacing: 2,
- titleMarginBottom: 6,
- titleFontColor: '#fff',
- titleAlign: 'left',
- bodySpacing: 2,
- bodyFontColor: '#fff',
- bodyAlign: 'left',
- footerFontStyle: 'bold',
- footerSpacing: 2,
- footerMarginTop: 6,
- footerFontColor: '#fff',
- footerAlign: 'left',
- yPadding: 6,
- xPadding: 6,
- caretPadding: 2,
- caretSize: 5,
- cornerRadius: 6,
- multiKeyBackground: '#fff',
- displayColors: true,
- borderColor: 'rgba(0,0,0,0)',
- borderWidth: 0,
- animation: {
- duration: 400,
- easing: 'easeOutQuart',
- numbers: {
- type: 'number',
- properties: ['x', 'y', 'width', 'height'],
- },
- opacity: {
- easing: 'linear',
- duration: 200
- }
+defaults._set('tooltips', {
+ enabled: true,
+ custom: null,
+ mode: 'nearest',
+ position: 'average',
+ intersect: true,
+ backgroundColor: 'rgba(0,0,0,0.8)',
+ titleFontStyle: 'bold',
+ titleSpacing: 2,
+ titleMarginBottom: 6,
+ titleFontColor: '#fff',
+ titleAlign: 'left',
+ bodySpacing: 2,
+ bodyFontColor: '#fff',
+ bodyAlign: 'left',
+ footerFontStyle: 'bold',
+ footerSpacing: 2,
+ footerMarginTop: 6,
+ footerFontColor: '#fff',
+ footerAlign: 'left',
+ yPadding: 6,
+ xPadding: 6,
+ caretPadding: 2,
+ caretSize: 5,
+ cornerRadius: 6,
+ multiKeyBackground: '#fff',
+ displayColors: true,
+ borderColor: 'rgba(0,0,0,0)',
+ borderWidth: 0,
+ animation: {
+ duration: 400,
+ easing: 'easeOutQuart',
+ numbers: {
+ type: 'number',
+ properties: ['x', 'y', 'width', 'height'],
},
- callbacks: {
- // Args are: (tooltipItems, data)
- beforeTitle: helpers.noop,
- title: function(tooltipItems, data) {
- var title = '';
- var labels = data.labels;
- var labelCount = labels ? labels.length : 0;
-
- if (tooltipItems.length > 0) {
- var item = tooltipItems[0];
- if (item.label) {
- title = item.label;
- } else if (labelCount > 0 && item.index < labelCount) {
- title = labels[item.index];
- }
+ opacity: {
+ easing: 'linear',
+ duration: 200
+ }
+ },
+ callbacks: {
+ // Args are: (tooltipItems, data)
+ beforeTitle: helpers.noop,
+ title: function(tooltipItems, data) {
+ var title = '';
+ var labels = data.labels;
+ var labelCount = labels ? labels.length : 0;
+
+ if (tooltipItems.length > 0) {
+ var item = tooltipItems[0];
+ if (item.label) {
+ title = item.label;
+ } else if (labelCount > 0 && item.index < labelCount) {
+ title = labels[item.index];
}
+ }
- return title;
- },
- afterTitle: helpers.noop,
+ return title;
+ },
+ afterTitle: helpers.noop,
- // Args are: (tooltipItems, data)
- beforeBody: helpers.noop,
+ // Args are: (tooltipItems, data)
+ beforeBody: helpers.noop,
- // Args are: (tooltipItem, data)
- beforeLabel: helpers.noop,
- label: function(tooltipItem, data) {
- var label = data.datasets[tooltipItem.datasetIndex].label || '';
+ // Args are: (tooltipItem, data)
+ beforeLabel: helpers.noop,
+ label: function(tooltipItem, data) {
+ var label = data.datasets[tooltipItem.datasetIndex].label || '';
- if (label) {
- label += ': ';
- }
- if (!helpers.isNullOrUndef(tooltipItem.value)) {
- label += tooltipItem.value;
- }
- return label;
- },
- labelColor: function(tooltipItem, chart) {
- var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
- var options = meta.controller.getStyle(tooltipItem.index);
- return {
- borderColor: options.borderColor,
- backgroundColor: options.backgroundColor
- };
- },
- labelTextColor: function() {
- return this.options.bodyFontColor;
- },
- afterLabel: helpers.noop,
+ if (label) {
+ label += ': ';
+ }
+ if (!helpers.isNullOrUndef(tooltipItem.value)) {
+ label += tooltipItem.value;
+ }
+ return label;
+ },
+ labelColor: function(tooltipItem, chart) {
+ var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
+ var options = meta.controller.getStyle(tooltipItem.index);
+ return {
+ borderColor: options.borderColor,
+ backgroundColor: options.backgroundColor
+ };
+ },
+ labelTextColor: function() {
+ return this.options.bodyFontColor;
+ },
+ afterLabel: helpers.noop,
- // Args are: (tooltipItems, data)
- afterBody: helpers.noop,
+ // Args are: (tooltipItems, data)
+ afterBody: helpers.noop,
- // Args are: (tooltipItems, data)
- beforeFooter: helpers.noop,
- footer: helpers.noop,
- afterFooter: helpers.noop
- }
+ // Args are: (tooltipItems, data)
+ beforeFooter: helpers.noop,
+ footer: helpers.noop,
+ afterFooter: helpers.noop
}
});
@@ -233,21 +231,20 @@ function createTooltipItem(chart, item) {
* @param options {object} the tooltip options
*/
function resolveOptions(options) {
- var globalDefaults = defaults.global;
- options = helpers.extend({}, globalDefaults.tooltips, options);
+ options = helpers.extend({}, defaults.tooltips, options);
- options.bodyFontFamily = valueOrDefault(options.bodyFontFamily, globalDefaults.defaultFontFamily);
- options.bodyFontStyle = valueOrDefault(options.bodyFontStyle, globalDefaults.defaultFontStyle);
- options.bodyFontSize = valueOrDefault(options.bodyFontSize, globalDefaults.defaultFontSize);
+ options.bodyFontFamily = valueOrDefault(options.bodyFontFamily, defaults.fontFamily);
+ options.bodyFontStyle = valueOrDefault(options.bodyFontStyle, defaults.fontStyle);
+ options.bodyFontSize = valueOrDefault(options.bodyFontSize, defaults.fontSize);
- options.titleFontFamily = valueOrDefault(options.titleFontFamily, globalDefaults.defaultFontFamily);
- options.titleFontStyle = valueOrDefault(options.titleFontStyle, globalDefaults.defaultFontStyle);
- options.titleFontSize = valueOrDefault(options.titleFontSize, globalDefaults.defaultFontSize);
+ options.titleFontFamily = valueOrDefault(options.titleFontFamily, defaults.fontFamily);
+ options.titleFontStyle = valueOrDefault(options.titleFontStyle, defaults.fontStyle);
+ options.titleFontSize = valueOrDefault(options.titleFontSize, defaults.fontSize);
- options.footerFontFamily = valueOrDefault(options.footerFontFamily, globalDefaults.defaultFontFamily);
- options.footerFontStyle = valueOrDefault(options.footerFontStyle, globalDefaults.defaultFontStyle);
- options.footerFontSize = valueOrDefault(options.footerFontSize, globalDefaults.defaultFontSize);
+ options.footerFontFamily = valueOrDefault(options.footerFontFamily, defaults.fontFamily);
+ options.footerFontStyle = valueOrDefault(options.footerFontStyle, defaults.fontStyle);
+ options.footerFontSize = valueOrDefault(options.footerFontSize, defaults.fontSize);
return options;
} | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/elements/element.arc.js | @@ -5,14 +5,12 @@ import Element from '../core/core.element';
import {getAngleFromPoint} from '../helpers/helpers.math';
const TAU = Math.PI * 2;
-defaults._set('global', {
- elements: {
- arc: {
- backgroundColor: defaults.global.defaultColor,
- borderColor: '#fff',
- borderWidth: 2,
- borderAlign: 'center'
- }
+defaults._set('elements', {
+ arc: {
+ backgroundColor: defaults.color,
+ borderColor: '#fff',
+ borderWidth: 2,
+ borderAlign: 'center'
}
});
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/elements/element.line.js | @@ -7,22 +7,20 @@ import {_computeSegments, _boundSegments} from '../helpers/helpers.segment';
import {_steppedLineTo, _bezierCurveTo} from '../helpers/helpers.canvas';
import {_updateBezierControlPoints} from '../helpers/helpers.curve';
-const defaultColor = defaults.global.defaultColor;
-
-defaults._set('global', {
- elements: {
- line: {
- tension: 0.4,
- backgroundColor: defaultColor,
- borderWidth: 3,
- borderColor: defaultColor,
- borderCapStyle: 'butt',
- borderDash: [],
- borderDashOffset: 0.0,
- borderJoinStyle: 'miter',
- capBezierPoints: true,
- fill: true
- }
+const defaultColor = defaults.color;
+
+defaults._set('elements', {
+ line: {
+ tension: 0.4,
+ backgroundColor: defaultColor,
+ borderWidth: 3,
+ borderColor: defaultColor,
+ borderCapStyle: 'butt',
+ borderDash: [],
+ borderDashOffset: 0.0,
+ borderJoinStyle: 'miter',
+ capBezierPoints: true,
+ fill: true
}
});
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/elements/element.point.js | @@ -4,21 +4,19 @@ import defaults from '../core/core.defaults';
import Element from '../core/core.element';
import helpers from '../helpers';
-const defaultColor = defaults.global.defaultColor;
-
-defaults._set('global', {
- elements: {
- point: {
- radius: 3,
- pointStyle: 'circle',
- backgroundColor: defaultColor,
- borderColor: defaultColor,
- borderWidth: 1,
- // Hover
- hitRadius: 1,
- hoverRadius: 4,
- hoverBorderWidth: 1
- }
+const defaultColor = defaults.color;
+
+defaults._set('elements', {
+ point: {
+ radius: 3,
+ pointStyle: 'circle',
+ backgroundColor: defaultColor,
+ borderColor: defaultColor,
+ borderWidth: 1,
+ // Hover
+ hitRadius: 1,
+ hoverRadius: 4,
+ hoverBorderWidth: 1
}
});
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/elements/element.rectangle.js | @@ -4,16 +4,14 @@ import defaults from '../core/core.defaults';
import Element from '../core/core.element';
import helpers from '../helpers';
-const defaultColor = defaults.global.defaultColor;
-
-defaults._set('global', {
- elements: {
- rectangle: {
- backgroundColor: defaultColor,
- borderColor: defaultColor,
- borderSkipped: 'bottom',
- borderWidth: 0
- }
+const defaultColor = defaults.color;
+
+defaults._set('elements', {
+ rectangle: {
+ backgroundColor: defaultColor,
+ borderColor: defaultColor,
+ borderSkipped: 'bottom',
+ borderWidth: 0
}
});
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/helpers/helpers.options.js | @@ -90,13 +90,12 @@ export function toPadding(value) {
* @private
*/
export function _parseFont(options) {
- var globalDefaults = defaults.global;
- var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
+ var size = valueOrDefault(options.fontSize, defaults.fontSize);
var font = {
- family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
- lineHeight: toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
+ family: valueOrDefault(options.fontFamily, defaults.fontFamily),
+ lineHeight: toLineHeight(valueOrDefault(options.lineHeight, defaults.lineHeight), size),
size: size,
- style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
+ style: valueOrDefault(options.fontStyle, defaults.fontStyle),
weight: null,
string: ''
}; | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/plugins/plugin.filler.js | @@ -13,11 +13,9 @@ import {clipArea, unclipArea} from '../helpers/helpers.canvas';
import {valueOrDefault, isFinite, isArray, extend} from '../helpers/helpers.core';
import {_normalizeAngle} from '../helpers/helpers.math';
-defaults._set('global', {
- plugins: {
- filler: {
- propagate: true
- }
+defaults._set('plugins', {
+ filler: {
+ propagate: true
}
});
@@ -436,7 +434,7 @@ export default {
const {line, target, scale} = meta;
const lineOpts = line.options;
const fillOption = lineOpts.fill;
- const color = lineOpts.backgroundColor || defaults.global.defaultColor;
+ const color = lineOpts.backgroundColor || defaults.color;
const {above = color, below = color} = fillOption || {};
if (target && line.points.length) {
clipArea(ctx, area); | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/plugins/plugin.legend.js | @@ -8,71 +8,69 @@ const layouts = require('../core/core.layouts');
const getRtlHelper = helpers.rtl.getRtlAdapter;
const valueOrDefault = helpers.valueOrDefault;
-defaults._set('global', {
- legend: {
- display: true,
- position: 'top',
- align: 'center',
- fullWidth: true,
- reverse: false,
- weight: 1000,
-
- // a callback that will handle
- onClick: function(e, legendItem) {
- var index = legendItem.datasetIndex;
- var ci = this.chart;
- var meta = ci.getDatasetMeta(index);
-
- // See controller.isDatasetVisible comment
- meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
-
- // We hid a dataset ... rerender the chart
- ci.update();
- },
-
- onHover: null,
- onLeave: null,
-
- labels: {
- boxWidth: 40,
- padding: 10,
- // Generates labels shown in the legend
- // Valid properties to return:
- // text : text to display
- // fillStyle : fill of coloured box
- // strokeStyle: stroke of coloured box
- // hidden : if this legend item refers to a hidden item
- // lineCap : cap style for line
- // lineDash
- // lineDashOffset :
- // lineJoin :
- // lineWidth :
- generateLabels: function(chart) {
- var datasets = chart.data.datasets;
- var options = chart.options.legend || {};
- var usePointStyle = options.labels && options.labels.usePointStyle;
-
- return chart._getSortedDatasetMetas().map(function(meta) {
- var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
-
- return {
- text: datasets[meta.index].label,
- fillStyle: style.backgroundColor,
- hidden: !meta.visible,
- lineCap: style.borderCapStyle,
- lineDash: style.borderDash,
- lineDashOffset: style.borderDashOffset,
- lineJoin: style.borderJoinStyle,
- lineWidth: style.borderWidth,
- strokeStyle: style.borderColor,
- pointStyle: style.pointStyle,
- rotation: style.rotation,
-
- // Below is extra data used for toggling the datasets
- datasetIndex: meta.index
- };
- }, this);
- }
+defaults._set('legend', {
+ display: true,
+ position: 'top',
+ align: 'center',
+ fullWidth: true,
+ reverse: false,
+ weight: 1000,
+
+ // a callback that will handle
+ onClick: function(e, legendItem) {
+ var index = legendItem.datasetIndex;
+ var ci = this.chart;
+ var meta = ci.getDatasetMeta(index);
+
+ // See controller.isDatasetVisible comment
+ meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
+
+ // We hid a dataset ... rerender the chart
+ ci.update();
+ },
+
+ onHover: null,
+ onLeave: null,
+
+ labels: {
+ boxWidth: 40,
+ padding: 10,
+ // Generates labels shown in the legend
+ // Valid properties to return:
+ // text : text to display
+ // fillStyle : fill of coloured box
+ // strokeStyle: stroke of coloured box
+ // hidden : if this legend item refers to a hidden item
+ // lineCap : cap style for line
+ // lineDash
+ // lineDashOffset :
+ // lineJoin :
+ // lineWidth :
+ generateLabels: function(chart) {
+ var datasets = chart.data.datasets;
+ var options = chart.options.legend || {};
+ var usePointStyle = options.labels && options.labels.usePointStyle;
+
+ return chart._getSortedDatasetMetas().map(function(meta) {
+ var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
+
+ return {
+ text: datasets[meta.index].label,
+ fillStyle: style.backgroundColor,
+ hidden: !meta.visible,
+ lineCap: style.borderCapStyle,
+ lineDash: style.borderDash,
+ lineDashOffset: style.borderDashOffset,
+ lineJoin: style.borderJoinStyle,
+ lineWidth: style.borderWidth,
+ strokeStyle: style.borderColor,
+ pointStyle: style.pointStyle,
+ rotation: style.rotation,
+
+ // Below is extra data used for toggling the datasets
+ datasetIndex: meta.index
+ };
+ }, this);
}
}
});
@@ -333,9 +331,8 @@ class Legend extends Element {
var me = this;
var opts = me.options;
var labelOpts = opts.labels;
- var globalDefaults = defaults.global;
- var defaultColor = globalDefaults.defaultColor;
- var lineDefault = globalDefaults.elements.line;
+ var defaultColor = defaults.color;
+ var lineDefault = defaults.elements.line;
var legendHeight = me.height;
var columnHeights = me.columnHeights;
var legendWidth = me.width;
@@ -347,7 +344,7 @@ class Legend extends Element {
var rtlHelper = getRtlHelper(opts.rtl, me.left, me.minSize.width);
var ctx = me.ctx;
- var fontColor = valueOrDefault(labelOpts.fontColor, globalDefaults.defaultFontColor);
+ var fontColor = valueOrDefault(labelOpts.fontColor, defaults.fontColor);
var labelFont = helpers.options._parseFont(labelOpts);
var fontSize = labelFont.size;
var cursor;
@@ -602,7 +599,7 @@ module.exports = {
var legend = chart.legend;
if (legendOpts) {
- helpers.mergeIf(legendOpts, defaults.global.legend);
+ helpers.mergeIf(legendOpts, defaults.legend);
if (legend) {
layouts.configure(chart, legend, legendOpts); | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/plugins/plugin.title.js | @@ -5,16 +5,14 @@ const Element = require('../core/core.element');
const helpers = require('../helpers/index');
const layouts = require('../core/core.layouts');
-defaults._set('global', {
- title: {
- display: false,
- fontStyle: 'bold',
- fullWidth: true,
- padding: 10,
- position: 'top',
- text: '',
- weight: 2000 // by default greater than legend (1000) to be above
- }
+defaults._set('title', {
+ display: false,
+ fontStyle: 'bold',
+ fullWidth: true,
+ padding: 10,
+ position: 'top',
+ text: '',
+ weight: 2000 // by default greater than legend (1000) to be above
});
/**
@@ -148,7 +146,7 @@ class Title extends Element {
var right = me.right;
var maxWidth, titleX, titleY;
- ctx.fillStyle = helpers.valueOrDefault(opts.fontColor, defaults.global.defaultFontColor); // render in correct colour
+ ctx.fillStyle = helpers.valueOrDefault(opts.fontColor, defaults.fontColor); // render in correct colour
ctx.font = fontOpts.string;
// Horizontal
@@ -221,7 +219,7 @@ module.exports = {
var titleBlock = chart.titleBlock;
if (titleOpts) {
- helpers.mergeIf(titleOpts, defaults.global.title);
+ helpers.mergeIf(titleOpts, defaults.title);
if (titleBlock) {
layouts.configure(chart, titleBlock, titleOpts); | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/scales/scale.logarithmic.js | @@ -182,7 +182,7 @@ class LogarithmicScale extends Scale {
if (start === 0) {
start = me._getFirstTickValue(me.minNotZero);
- offset = valueOrDefault(me.options.ticks.fontSize, defaults.global.defaultFontSize) / me._length;
+ offset = valueOrDefault(me.options.ticks.fontSize, defaults.fontSize) / me._length;
}
me._startValue = log10(start); | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/scales/scale.radialLinear.js | @@ -64,7 +64,7 @@ function getTickBackdropHeight(opts) {
var tickOpts = opts.ticks;
if (tickOpts.display && opts.display) {
- return valueOrDefault(tickOpts.fontSize, defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
+ return valueOrDefault(tickOpts.fontSize, defaults.fontSize) + tickOpts.backdropPaddingY * 2;
}
return 0;
}
@@ -236,7 +236,7 @@ function drawPointLabels(scale) {
var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
// Keep this in loop since we may support array properties here
- var pointLabelFontColor = valueAtIndexOrDefault(pointLabelOpts.fontColor, i, defaults.global.defaultFontColor);
+ var pointLabelFontColor = valueAtIndexOrDefault(pointLabelOpts.fontColor, i, defaults.fontColor);
ctx.fillStyle = pointLabelFontColor;
var angleRadians = scale.getIndexAngle(i);
@@ -486,7 +486,7 @@ class RadialLinearScale extends LinearScaleBase {
var startAngle = me.getIndexAngle(0);
var tickFont = helpers.options._parseFont(tickOpts);
- var tickFontColor = valueOrDefault(tickOpts.fontColor, defaults.global.defaultFontColor);
+ var tickFontColor = valueOrDefault(tickOpts.fontColor, defaults.fontColor);
var offset, width;
ctx.save(); | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | src/scales/scale.time.js | @@ -735,7 +735,7 @@ class TimeScale extends Scale {
const angle = 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);
+ const tickFontSize = valueOrDefault(ticksOpts.fontSize, defaults.fontSize);
return {
w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation), | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | test/specs/controller.bar.tests.js | @@ -1343,7 +1343,7 @@ describe('Chart.controllers.bar', function() {
var chart = window.acquireChart(this.config);
var meta = chart.getDatasetMeta(0);
var xScale = chart.scales[meta.xAxisID];
- var options = Chart.defaults.global.datasets.bar;
+ var options = Chart.defaults.datasets.bar;
var categoryPercentage = options.categoryPercentage;
var barPercentage = options.barPercentage;
@@ -1517,7 +1517,7 @@ describe('Chart.controllers.bar', function() {
expected = barThickness;
} else {
var scale = chart.scales.x;
- var options = Chart.defaults.global.datasets.bar;
+ var options = Chart.defaults.datasets.bar;
var categoryPercentage = options.categoryPercentage;
var barPercentage = options.barPercentage;
var tickInterval = scale.getPixelForTick(1) - scale.getPixelForTick(0); | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | test/specs/controller.bubble.tests.js | @@ -141,8 +141,8 @@ describe('Chart.controllers.bubble', function() {
expect(meta.data[i].x).toBeCloseToPixel(expected.x);
expect(meta.data[i].y).toBeCloseToPixel(expected.y);
expect(meta.data[i].options).toEqual(jasmine.objectContaining({
- backgroundColor: Chart.defaults.global.defaultColor,
- borderColor: Chart.defaults.global.defaultColor,
+ backgroundColor: Chart.defaults.color,
+ borderColor: Chart.defaults.color,
borderWidth: 1,
hitRadius: 1,
radius: expected.r | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | test/specs/controller.line.tests.js | @@ -559,18 +559,18 @@ describe('Chart.controllers.line', function() {
describe('dataset global defaults', function() {
beforeEach(function() {
- this._defaults = Chart.helpers.clone(Chart.defaults.global.datasets.line);
+ this._defaults = Chart.helpers.clone(Chart.defaults.datasets.line);
});
afterEach(function() {
- Chart.defaults.global.datasets.line = this._defaults;
+ Chart.defaults.datasets.line = this._defaults;
delete this._defaults;
});
it('should utilize the dataset global default options', function() {
- Chart.defaults.global.datasets.line = Chart.defaults.global.datasets.line || {};
+ Chart.defaults.datasets.line = Chart.defaults.datasets.line || {};
- Chart.helpers.merge(Chart.defaults.global.datasets.line, {
+ Chart.helpers.merge(Chart.defaults.datasets.line, {
spanGaps: true,
lineTension: 0.231,
backgroundColor: '#add',
@@ -611,9 +611,9 @@ describe('Chart.controllers.line', function() {
});
it('should be overriden by user-supplied values', function() {
- Chart.defaults.global.datasets.line = Chart.defaults.global.datasets.line || {};
+ Chart.defaults.datasets.line = Chart.defaults.datasets.line || {};
- Chart.helpers.merge(Chart.defaults.global.datasets.line, {
+ Chart.helpers.merge(Chart.defaults.datasets.line, {
spanGaps: true,
lineTension: 0.231
}); | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | test/specs/controller.radar.tests.js | @@ -100,9 +100,9 @@ describe('Chart.controllers.radar', function() {
tension: 0.1,
},
point: {
- backgroundColor: Chart.defaults.global.defaultColor,
+ backgroundColor: Chart.defaults.color,
borderWidth: 1,
- borderColor: Chart.defaults.global.defaultColor,
+ borderColor: Chart.defaults.color,
hitRadius: 1,
hoverRadius: 4,
hoverBorderWidth: 1,
@@ -143,9 +143,9 @@ describe('Chart.controllers.radar', function() {
expect(meta.data[i].controlPointNextX).toBeCloseToPixel(expected.cpnx);
expect(meta.data[i].controlPointNextY).toBeCloseToPixel(expected.cpny);
expect(meta.data[i].options).toEqual(jasmine.objectContaining({
- backgroundColor: Chart.defaults.global.defaultColor,
+ backgroundColor: Chart.defaults.color,
borderWidth: 1,
- borderColor: Chart.defaults.global.defaultColor,
+ borderColor: Chart.defaults.color,
hitRadius: 1,
radius: 3,
pointStyle: 'circle',
@@ -168,9 +168,9 @@ describe('Chart.controllers.radar', function() {
expect(meta.data[i].controlPointNextX).toBeCloseToPixel(expected.cpnx);
expect(meta.data[i].controlPointNextY).toBeCloseToPixel(expected.cpny);
expect(meta.data[i].options).toEqual(jasmine.objectContaining({
- backgroundColor: Chart.defaults.global.defaultColor,
+ backgroundColor: Chart.defaults.color,
borderWidth: 1,
- borderColor: Chart.defaults.global.defaultColor,
+ borderColor: Chart.defaults.color,
hitRadius: 1,
radius: 3,
pointStyle: 'circle', | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | test/specs/core.controller.tests.js | @@ -66,7 +66,7 @@ describe('Chart', function() {
var callback = function() {};
var defaults = Chart.defaults;
- defaults.global.hover.onHover = callback;
+ defaults.hover.onHover = callback;
defaults.line.spanGaps = true;
defaults.line.hover.mode = 'x-axis';
@@ -75,13 +75,13 @@ describe('Chart', function() {
});
var options = chart.options;
- expect(options.defaultFontSize).toBe(defaults.global.defaultFontSize);
+ expect(options.fontSize).toBe(defaults.fontSize);
expect(options.showLines).toBe(defaults.line.showLines);
expect(options.spanGaps).toBe(true);
expect(options.hover.onHover).toBe(callback);
expect(options.hover.mode).toBe('x-axis');
- defaults.global.hover.onHover = null;
+ defaults.hover.onHover = null;
defaults.line.spanGaps = false;
defaults.line.hover.mode = 'index';
});
@@ -90,7 +90,7 @@ describe('Chart', function() {
var callback = function() {};
var defaults = Chart.defaults;
- defaults.global.hover.onHover = callback;
+ defaults.hover.onHover = callback;
defaults.line.hover.mode = 'x-axis';
defaults.line.spanGaps = true;
@@ -108,12 +108,12 @@ describe('Chart', function() {
});
var options = chart.options;
- expect(options.showLines).toBe(defaults.global.showLines);
+ expect(options.showLines).toBe(defaults.showLines);
expect(options.spanGaps).toBe(false);
expect(options.hover.mode).toBe('dataset');
expect(options.title.position).toBe('bottom');
- defaults.global.hover.onHover = null;
+ defaults.hover.onHover = null;
defaults.line.hover.mode = 'index';
defaults.line.spanGaps = false;
});
@@ -297,7 +297,7 @@ describe('Chart', function() {
expect(chart.scales.y.options._jasmineCheck).toBeDefined();
expect(Chart.defaults.line._jasmineCheck).not.toBeDefined();
- expect(Chart.defaults.global._jasmineCheck).not.toBeDefined();
+ expect(Chart.defaults._jasmineCheck).not.toBeDefined();
expect(Chart.scaleService.defaults.linear._jasmineCheck).not.toBeDefined();
expect(Chart.scaleService.defaults.category._jasmineCheck).not.toBeDefined();
}); | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | test/specs/core.plugin.tests.js | @@ -306,7 +306,7 @@ describe('Chart.plugins', function() {
it('should call plugins with default options when plugin options is TRUE', function() {
var plugin = {id: 'a', hook: function() {}};
- Chart.defaults.global.plugins.a = {a: 42};
+ Chart.defaults.plugins.a = {a: 42};
Chart.plugins.register(plugin);
var chart = window.acquireChart({
@@ -324,14 +324,14 @@ describe('Chart.plugins', function() {
expect(plugin.hook).toHaveBeenCalled();
expect(plugin.hook.calls.first().args[1]).toEqual({a: 42});
- delete Chart.defaults.global.plugins.a;
+ delete Chart.defaults.plugins.a;
});
it('should call plugins with default options if plugin config options is undefined', function() {
var plugin = {id: 'a', hook: function() {}};
- Chart.defaults.global.plugins.a = {a: 'foobar'};
+ Chart.defaults.plugins.a = {a: 'foobar'};
Chart.plugins.register(plugin);
spyOn(plugin, 'hook');
@@ -342,7 +342,7 @@ describe('Chart.plugins', function() {
expect(plugin.hook).toHaveBeenCalled();
expect(plugin.hook.calls.first().args[1]).toEqual({a: 'foobar'});
- delete Chart.defaults.global.plugins.a;
+ delete Chart.defaults.plugins.a;
});
// https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167 | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | test/specs/core.tooltip.tests.js | @@ -19,11 +19,11 @@ describe('Core.Tooltip', function() {
value: '20'
};
- var label = Chart.defaults.global.tooltips.callbacks.label(tooltipItem, data);
+ var label = Chart.defaults.tooltips.callbacks.label(tooltipItem, data);
expect(label).toBe('20');
data.datasets[0].label = 'My dataset';
- label = Chart.defaults.global.tooltips.callbacks.label(tooltipItem, data);
+ label = Chart.defaults.tooltips.callbacks.label(tooltipItem, data);
expect(label).toBe('My dataset: 20');
});
});
@@ -78,7 +78,7 @@ describe('Core.Tooltip', function() {
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
- var globalDefaults = Chart.defaults.global;
+ var defaults = Chart.defaults;
expect(tooltip.options.xPadding).toEqual(6);
expect(tooltip.options.yPadding).toEqual(6);
@@ -88,19 +88,19 @@ describe('Core.Tooltip', function() {
expect(tooltip.options).toEqual(jasmine.objectContaining({
// Body
bodyFontColor: '#fff',
- bodyFontFamily: globalDefaults.defaultFontFamily,
- bodyFontStyle: globalDefaults.defaultFontStyle,
+ bodyFontFamily: defaults.fontFamily,
+ bodyFontStyle: defaults.fontStyle,
bodyAlign: 'left',
- bodyFontSize: globalDefaults.defaultFontSize,
+ bodyFontSize: defaults.fontSize,
bodySpacing: 2,
}));
expect(tooltip.options).toEqual(jasmine.objectContaining({
// Title
titleFontColor: '#fff',
- titleFontFamily: globalDefaults.defaultFontFamily,
+ titleFontFamily: defaults.fontFamily,
titleFontStyle: 'bold',
- titleFontSize: globalDefaults.defaultFontSize,
+ titleFontSize: defaults.fontSize,
titleAlign: 'left',
titleSpacing: 2,
titleMarginBottom: 6,
@@ -109,9 +109,9 @@ describe('Core.Tooltip', function() {
expect(tooltip.options).toEqual(jasmine.objectContaining({
// Footer
footerFontColor: '#fff',
- footerFontFamily: globalDefaults.defaultFontFamily,
+ footerFontFamily: defaults.fontFamily,
footerFontStyle: 'bold',
- footerFontSize: globalDefaults.defaultFontSize,
+ footerFontSize: defaults.fontSize,
footerAlign: 'left',
footerSpacing: 2,
footerMarginTop: 6,
@@ -145,11 +145,11 @@ describe('Core.Tooltip', function() {
afterBody: [],
footer: [],
labelColors: [{
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}, {
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}]
}));
@@ -254,7 +254,7 @@ describe('Core.Tooltip', function() {
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
- var globalDefaults = Chart.defaults.global;
+ var defaults = Chart.defaults;
expect(tooltip.options.xPadding).toEqual(6);
expect(tooltip.options.yPadding).toEqual(6);
@@ -264,19 +264,19 @@ describe('Core.Tooltip', function() {
expect(tooltip.options).toEqual(jasmine.objectContaining({
// Body
bodyFontColor: '#fff',
- bodyFontFamily: globalDefaults.defaultFontFamily,
- bodyFontStyle: globalDefaults.defaultFontStyle,
+ bodyFontFamily: defaults.fontFamily,
+ bodyFontStyle: defaults.fontStyle,
bodyAlign: 'left',
- bodyFontSize: globalDefaults.defaultFontSize,
+ bodyFontSize: defaults.fontSize,
bodySpacing: 2,
}));
expect(tooltip.options).toEqual(jasmine.objectContaining({
// Title
titleFontColor: '#fff',
- titleFontFamily: globalDefaults.defaultFontFamily,
+ titleFontFamily: defaults.fontFamily,
titleFontStyle: 'bold',
- titleFontSize: globalDefaults.defaultFontSize,
+ titleFontSize: defaults.fontSize,
titleAlign: 'left',
titleSpacing: 2,
titleMarginBottom: 6,
@@ -285,9 +285,9 @@ describe('Core.Tooltip', function() {
expect(tooltip.options).toEqual(jasmine.objectContaining({
// Footer
footerFontColor: '#fff',
- footerFontFamily: globalDefaults.defaultFontFamily,
+ footerFontFamily: defaults.fontFamily,
footerFontStyle: 'bold',
- footerFontSize: globalDefaults.defaultFontSize,
+ footerFontSize: defaults.fontSize,
footerAlign: 'left',
footerSpacing: 2,
footerMarginTop: 6,
@@ -318,8 +318,8 @@ describe('Core.Tooltip', function() {
footer: [],
labelTextColors: ['#fff'],
labelColors: [{
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}]
}));
@@ -409,7 +409,7 @@ describe('Core.Tooltip', function() {
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
- var globalDefaults = Chart.defaults.global;
+ var defaults = Chart.defaults;
expect(tooltip.options.xPadding).toEqual(6);
expect(tooltip.options.yPadding).toEqual(6);
@@ -419,19 +419,19 @@ describe('Core.Tooltip', function() {
expect(tooltip.options).toEqual(jasmine.objectContaining({
// Body
bodyFontColor: '#fff',
- bodyFontFamily: globalDefaults.defaultFontFamily,
- bodyFontStyle: globalDefaults.defaultFontStyle,
+ bodyFontFamily: defaults.fontFamily,
+ bodyFontStyle: defaults.fontStyle,
bodyAlign: 'left',
- bodyFontSize: globalDefaults.defaultFontSize,
+ bodyFontSize: defaults.fontSize,
bodySpacing: 2,
}));
expect(tooltip.options).toEqual(jasmine.objectContaining({
// Title
titleFontColor: '#fff',
- titleFontFamily: globalDefaults.defaultFontFamily,
+ titleFontFamily: defaults.fontFamily,
titleFontStyle: 'bold',
- titleFontSize: globalDefaults.defaultFontSize,
+ titleFontSize: defaults.fontSize,
titleAlign: 'left',
titleSpacing: 2,
titleMarginBottom: 6,
@@ -440,9 +440,9 @@ describe('Core.Tooltip', function() {
expect(tooltip.options).toEqual(jasmine.objectContaining({
// Footer
footerFontColor: '#fff',
- footerFontFamily: globalDefaults.defaultFontFamily,
+ footerFontFamily: defaults.fontFamily,
footerFontStyle: 'bold',
- footerFontSize: globalDefaults.defaultFontSize,
+ footerFontSize: defaults.fontSize,
footerAlign: 'left',
footerSpacing: 2,
footerMarginTop: 6,
@@ -476,11 +476,11 @@ describe('Core.Tooltip', function() {
footer: ['beforeFooter', 'footer', 'afterFooter'],
labelTextColors: ['labelTextColor', 'labelTextColor'],
labelColors: [{
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}, {
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}]
}));
@@ -535,7 +535,7 @@ describe('Core.Tooltip', function() {
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
- var globalDefaults = Chart.defaults.global;
+ var defaults = Chart.defaults;
expect(tooltip).toEqual(jasmine.objectContaining({
// Positioning
@@ -557,11 +557,11 @@ describe('Core.Tooltip', function() {
afterBody: [],
footer: [],
labelColors: [{
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}, {
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}]
}));
@@ -614,7 +614,7 @@ describe('Core.Tooltip', function() {
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
- var globalDefaults = Chart.defaults.global;
+ var defaults = Chart.defaults;
expect(tooltip).toEqual(jasmine.objectContaining({
// Positioning
@@ -636,11 +636,11 @@ describe('Core.Tooltip', function() {
afterBody: [],
footer: [],
labelColors: [{
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}, {
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}]
}));
@@ -694,7 +694,7 @@ describe('Core.Tooltip', function() {
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
- var globalDefaults = Chart.defaults.global;
+ var defaults = Chart.defaults;
expect(tooltip).toEqual(jasmine.objectContaining({
// Positioning
@@ -716,11 +716,11 @@ describe('Core.Tooltip', function() {
afterBody: [],
footer: [],
labelColors: [{
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}, {
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}]
}));
@@ -777,7 +777,7 @@ describe('Core.Tooltip', function() {
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
- var globalDefaults = Chart.defaults.global;
+ var defaults = Chart.defaults;
expect(tooltip).toEqual(jasmine.objectContaining({
// Positioning
@@ -795,8 +795,8 @@ describe('Core.Tooltip', function() {
afterBody: [],
footer: [],
labelColors: [{
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}]
}));
});
@@ -1176,7 +1176,7 @@ describe('Core.Tooltip', function() {
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
- var globalDefaults = Chart.defaults.global;
+ var defaults = Chart.defaults;
expect(tooltip.options.xPadding).toEqual(6);
expect(tooltip.options.yPadding).toEqual(6);
@@ -1186,19 +1186,19 @@ describe('Core.Tooltip', function() {
expect(tooltip.options).toEqual(jasmine.objectContaining({
// Body
bodyFontColor: '#fff',
- bodyFontFamily: globalDefaults.defaultFontFamily,
- bodyFontStyle: globalDefaults.defaultFontStyle,
+ bodyFontFamily: defaults.fontFamily,
+ bodyFontStyle: defaults.fontStyle,
bodyAlign: 'left',
- bodyFontSize: globalDefaults.defaultFontSize,
+ bodyFontSize: defaults.fontSize,
bodySpacing: 2,
}));
expect(tooltip.options).toEqual(jasmine.objectContaining({
// Title
titleFontColor: '#fff',
- titleFontFamily: globalDefaults.defaultFontFamily,
+ titleFontFamily: defaults.fontFamily,
titleFontStyle: 'bold',
- titleFontSize: globalDefaults.defaultFontSize,
+ titleFontSize: defaults.fontSize,
titleAlign: 'left',
titleSpacing: 2,
titleMarginBottom: 6,
@@ -1207,9 +1207,9 @@ describe('Core.Tooltip', function() {
expect(tooltip.options).toEqual(jasmine.objectContaining({
// Footer
footerFontColor: '#fff',
- footerFontFamily: globalDefaults.defaultFontFamily,
+ footerFontFamily: defaults.fontFamily,
footerFontStyle: 'bold',
- footerFontSize: globalDefaults.defaultFontSize,
+ footerFontSize: defaults.fontSize,
footerAlign: 'left',
footerSpacing: 2,
footerMarginTop: 6,
@@ -1243,17 +1243,17 @@ describe('Core.Tooltip', function() {
footer: ['beforeFooter', 'newline', 'footer', 'newline', 'afterFooter', 'newline'],
labelTextColors: ['labelTextColor', 'labelTextColor'],
labelColors: [{
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}, {
- borderColor: globalDefaults.defaultColor,
- backgroundColor: globalDefaults.defaultColor
+ borderColor: defaults.color,
+ backgroundColor: defaults.color
}]
}));
});
describe('text align', function() {
- var globalDefaults = Chart.defaults.global;
+ var defaults = Chart.defaults;
var makeView = function(title, body, footer) {
return {
// Positioning
@@ -1270,26 +1270,26 @@ describe('Core.Tooltip', function() {
// Body
bodyFontColor: '#fff',
- bodyFontFamily: globalDefaults.defaultFontFamily,
- bodyFontStyle: globalDefaults.defaultFontStyle,
+ bodyFontFamily: defaults.fontFamily,
+ bodyFontStyle: defaults.fontStyle,
bodyAlign: body,
- bodyFontSize: globalDefaults.defaultFontSize,
+ bodyFontSize: defaults.fontSize,
bodySpacing: 2,
// Title
titleFontColor: '#fff',
- titleFontFamily: globalDefaults.defaultFontFamily,
+ titleFontFamily: defaults.fontFamily,
titleFontStyle: 'bold',
- titleFontSize: globalDefaults.defaultFontSize,
+ titleFontSize: defaults.fontSize,
titleAlign: title,
titleSpacing: 2,
titleMarginBottom: 6,
// Footer
footerFontColor: '#fff',
- footerFontFamily: globalDefaults.defaultFontFamily,
+ footerFontFamily: defaults.fontFamily,
footerFontStyle: 'bold',
- footerFontSize: globalDefaults.defaultFontSize,
+ footerFontSize: defaults.fontSize,
footerAlign: footer,
footerSpacing: 2,
footerMarginTop: 6, | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | test/specs/helpers.options.tests.js | @@ -70,14 +70,17 @@ describe('Chart.helpers.options', function() {
var parseFont = options._parseFont;
it ('should return a font with default values', function() {
- var global = Chart.defaults.global;
-
- Chart.defaults.global = {
- defaultFontFamily: 'foobar',
- defaultFontSize: 42,
- defaultFontStyle: 'xxxyyy',
- defaultLineHeight: 1.5
- };
+ const fontFamily = Chart.defaults.fontFamily;
+ const fontSize = Chart.defaults.fontSize;
+ const fontStyle = Chart.defaults.fontStyle;
+ const lineHeight = Chart.defaults.lineHeight;
+
+ Chart.helpers.extend(Chart.defaults, {
+ fontFamily: 'foobar',
+ fontSize: 42,
+ fontStyle: 'xxxyyy',
+ lineHeight: 1.5
+ });
expect(parseFont({})).toEqual({
family: 'foobar',
@@ -88,7 +91,12 @@ describe('Chart.helpers.options', function() {
weight: null
});
- Chart.defaults.global = global;
+ Chart.helpers.extend(Chart.defaults, {
+ fontFamily,
+ fontSize,
+ fontStyle,
+ lineHeight
+ });
});
it ('should return a font with given values', function() {
expect(parseFont({
@@ -106,9 +114,10 @@ describe('Chart.helpers.options', function() {
});
});
it('should return null as a font string if fontSize or fontFamily are missing', function() {
- var global = Chart.defaults.global;
-
- Chart.defaults.global = {};
+ const fontFamily = Chart.defaults.fontFamily;
+ const fontSize = Chart.defaults.fontSize;
+ delete Chart.defaults.fontFamily;
+ delete Chart.defaults.fontSize;
expect(parseFont({
fontStyle: 'italic',
@@ -119,19 +128,19 @@ describe('Chart.helpers.options', function() {
fontFamily: 'serif'
}).string).toBeNull();
- Chart.defaults.global = global;
+ Chart.defaults.fontFamily = fontFamily;
+ Chart.defaults.fontSize = fontSize;
});
it('fontStyle should be optional for font strings', function() {
- var global = Chart.defaults.global;
-
- Chart.defaults.global = {};
+ const fontStyle = Chart.defaults.fontStyle;
+ delete Chart.defaults.fontStyle;
expect(parseFont({
fontSize: 12,
fontFamily: 'serif'
}).string).toBe('12px serif');
- Chart.defaults.global = global;
+ Chart.defaults.fontStyle = fontStyle;
});
});
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | test/specs/plugin.legend.tests.js | @@ -3,7 +3,7 @@ describe('Legend block tests', function() {
describe('auto', jasmine.fixture.specs('plugin.legend'));
it('should have the correct default config', function() {
- expect(Chart.defaults.global.legend).toEqual({
+ expect(Chart.defaults.legend).toEqual({
display: true,
position: 'top',
align: 'center',
@@ -591,7 +591,7 @@ describe('Legend block tests', function() {
chart.options.legend = {};
chart.update();
expect(chart.legend).not.toBe(undefined);
- expect(chart.legend.options).toEqual(jasmine.objectContaining(Chart.defaults.global.legend));
+ expect(chart.legend.options).toEqual(jasmine.objectContaining(Chart.defaults.legend));
});
});
| true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | test/specs/plugin.title.tests.js | @@ -4,7 +4,7 @@ var Title = Chart.plugins.getAll().find(p => p.id === 'title')._element;
describe('Title block tests', function() {
it('Should have the correct default config', function() {
- expect(Chart.defaults.global.title).toEqual({
+ expect(Chart.defaults.title).toEqual({
display: false,
position: 'top',
fullWidth: true,
@@ -18,7 +18,7 @@ describe('Title block tests', function() {
it('should update correctly', function() {
var chart = {};
- var options = Chart.helpers.clone(Chart.defaults.global.title);
+ var options = Chart.helpers.clone(Chart.defaults.title);
options.text = 'My title';
var title = new Title({
@@ -47,7 +47,7 @@ describe('Title block tests', function() {
it('should update correctly when vertical', function() {
var chart = {};
- var options = Chart.helpers.clone(Chart.defaults.global.title);
+ var options = Chart.helpers.clone(Chart.defaults.title);
options.text = 'My title';
options.position = 'left';
@@ -77,7 +77,7 @@ describe('Title block tests', function() {
it('should have the correct size when there are multiple lines of text', function() {
var chart = {};
- var options = Chart.helpers.clone(Chart.defaults.global.title);
+ var options = Chart.helpers.clone(Chart.defaults.title);
options.text = ['line1', 'line2'];
options.position = 'left';
options.display = true;
@@ -100,7 +100,7 @@ describe('Title block tests', function() {
var chart = {};
var context = window.createMockContext();
- var options = Chart.helpers.clone(Chart.defaults.global.title);
+ var options = Chart.helpers.clone(Chart.defaults.title);
options.text = 'My title';
var title = new Title({
@@ -152,7 +152,7 @@ describe('Title block tests', function() {
var chart = {};
var context = window.createMockContext();
- var options = Chart.helpers.clone(Chart.defaults.global.title);
+ var options = Chart.helpers.clone(Chart.defaults.title);
options.text = 'My title';
options.position = 'left';
@@ -322,7 +322,7 @@ describe('Title block tests', function() {
chart.options.title = {};
chart.update();
expect(chart.titleBlock).not.toBe(undefined);
- expect(chart.titleBlock.options).toEqual(jasmine.objectContaining(Chart.defaults.global.title));
+ expect(chart.titleBlock.options).toEqual(jasmine.objectContaining(Chart.defaults.title));
});
});
}); | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | test/specs/scale.logarithmic.tests.js | @@ -1135,7 +1135,7 @@ describe('Logarithmic Scale tests', function() {
var scale = chart.scales[axisID];
var firstTick = setup.firstTick;
var lastTick = setup.lastTick;
- var fontSize = chart.options.defaultFontSize;
+ var fontSize = chart.options.fontSize;
var start = chart.chartArea[axis.start];
var end = chart.chartArea[axis.end];
var sign = scale.isHorizontal() ? 1 : -1; | true |
Other | chartjs | Chart.js | f4792306e04b0c2d6dedc9e0a196348c2bf3f3dd.json | Remove global from defaults (#6893) | test/utils.js | @@ -55,7 +55,7 @@ function acquireChart(config, options) {
config.options = config.options || {};
config.options.animation = config.options.animation === undefined ? false : config.options.animation;
config.options.responsive = config.options.responsive === undefined ? false : config.options.responsive;
- config.options.defaultFontFamily = config.options.defaultFontFamily || 'Arial';
+ config.options.fontFamily = config.options.fontFamily || 'Arial';
wrapper.appendChild(canvas);
window.document.body.appendChild(wrapper); | true |
Other | chartjs | Chart.js | e96ad6f2491db9e7a94f734ca09330b296d47f52.json | Remove HTML legend that is mostly unsupported. (#6887)
* Remove HTML legend that is mostly unsupported.
Resolves the discussion in #5070
* Add migration docs | docs/configuration/legend.md | @@ -169,23 +169,3 @@ var chart = new Chart(ctx, {
```
Now when you click the legend in this chart, the visibility of the first two datasets will be linked together.
-
-## HTML Legends
-
-Sometimes you need a very complex legend. In these cases, it makes sense to generate an HTML legend. Charts provide a `generateLegend()` method on their prototype that returns an HTML string for the legend.
-
-To configure how this legend is generated, you can change the `legendCallback` config property.
-
-```javascript
-var chart = new Chart(ctx, {
- type: 'line',
- data: data,
- options: {
- legendCallback: function(chart) {
- // Return the HTML string here.
- }
- }
-});
-```
-
-Note that legendCallback is not called automatically and you must call `generateLegend()` yourself in code when creating a legend using this method. | true |
Other | chartjs | Chart.js | e96ad6f2491db9e7a94f734ca09330b296d47f52.json | Remove HTML legend that is mostly unsupported. (#6887)
* Remove HTML legend that is mostly unsupported.
Resolves the discussion in #5070
* Add migration docs | docs/developers/api.md | @@ -89,15 +89,6 @@ myLineChart.toBase64Image();
// => returns png data url of the image on the canvas
```
-## .generateLegend()
-
-Returns an HTML string of a legend for that chart. The legend is generated from the `legendCallback` in the options.
-
-```javascript
-myLineChart.generateLegend();
-// => returns HTML string of a legend for this chart
-```
-
## .getElementAtEvent(e)
Calling `getElementAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the single element at the event position. If there are multiple items within range, only the first is returned. The value returned from this method is an array with a single parameter. An array is used to keep a consistent API between the `get*AtEvent` methods. | true |
Other | chartjs | Chart.js | e96ad6f2491db9e7a94f734ca09330b296d47f52.json | Remove HTML legend that is mostly unsupported. (#6887)
* Remove HTML legend that is mostly unsupported.
Resolves the discussion in #5070
* Add migration docs | docs/getting-started/v3-migration.md | @@ -62,6 +62,7 @@ Animation system was completely rewritten in Chart.js v3. Each property can now
* `Chart.chart.chart`
* `Chart.Controller`
+* `Chart.prototype.generateLegend`
* `Chart.types`
* `DatasetController.addElementAndReset`
* `DatasetController.createMetaData` | true |
Other | chartjs | Chart.js | e96ad6f2491db9e7a94f734ca09330b296d47f52.json | Remove HTML legend that is mostly unsupported. (#6887)
* Remove HTML legend that is mostly unsupported.
Resolves the discussion in #5070
* Add migration docs | src/controllers/controller.doughnut.js | @@ -22,27 +22,6 @@ defaults._set('doughnut', {
// Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false
},
- legendCallback: function(chart) {
- var list = document.createElement('ul');
- var data = chart.data;
- var datasets = data.datasets;
- var labels = data.labels;
- var i, ilen, listItem, listItemSpan;
-
- list.setAttribute('class', chart.id + '-legend');
- if (datasets.length) {
- for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
- listItem = list.appendChild(document.createElement('li'));
- listItemSpan = listItem.appendChild(document.createElement('span'));
- listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
- if (labels[i]) {
- listItem.appendChild(document.createTextNode(labels[i]));
- }
- }
- }
-
- return list.outerHTML;
- },
legend: {
labels: {
generateLabels: function(chart) { | true |
Other | chartjs | Chart.js | e96ad6f2491db9e7a94f734ca09330b296d47f52.json | Remove HTML legend that is mostly unsupported. (#6887)
* Remove HTML legend that is mostly unsupported.
Resolves the discussion in #5070
* Add migration docs | src/controllers/controller.polarArea.js | @@ -33,27 +33,6 @@ defaults._set('polarArea', {
},
startAngle: -0.5 * Math.PI,
- legendCallback: function(chart) {
- var list = document.createElement('ul');
- var data = chart.data;
- var datasets = data.datasets;
- var labels = data.labels;
- var i, ilen, listItem, listItemSpan;
-
- list.setAttribute('class', chart.id + '-legend');
- if (datasets.length) {
- for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
- listItem = list.appendChild(document.createElement('li'));
- listItemSpan = listItem.appendChild(document.createElement('span'));
- listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
- if (labels[i]) {
- listItem.appendChild(document.createTextNode(labels[i]));
- }
- }
- }
-
- return list.outerHTML;
- },
legend: {
labels: {
generateLabels: function(chart) { | true |
Other | chartjs | Chart.js | e96ad6f2491db9e7a94f734ca09330b296d47f52.json | Remove HTML legend that is mostly unsupported. (#6887)
* Remove HTML legend that is mostly unsupported.
Resolves the discussion in #5070
* Add migration docs | src/core/core.controller.js | @@ -828,10 +828,6 @@ class Chart {
return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
}
- generateLegend() {
- return this.options.legendCallback(this);
- }
-
/**
* @private
*/ | true |
Other | chartjs | Chart.js | e96ad6f2491db9e7a94f734ca09330b296d47f52.json | Remove HTML legend that is mostly unsupported. (#6887)
* Remove HTML legend that is mostly unsupported.
Resolves the discussion in #5070
* Add migration docs | src/plugins/plugin.legend.js | @@ -74,25 +74,6 @@ defaults._set('global', {
}, this);
}
}
- },
-
- legendCallback: function(chart) {
- var list = document.createElement('ul');
- var datasets = chart.data.datasets;
- var i, ilen, listItem, listItemSpan;
-
- list.setAttribute('class', chart.id + '-legend');
-
- for (i = 0, ilen = datasets.length; i < ilen; i++) {
- listItem = list.appendChild(document.createElement('li'));
- listItemSpan = listItem.appendChild(document.createElement('span'));
- listItemSpan.style.backgroundColor = datasets[i].backgroundColor;
- if (datasets[i].label) {
- listItem.appendChild(document.createTextNode(datasets[i].label));
- }
- }
-
- return list.outerHTML;
}
});
| true |
Other | chartjs | Chart.js | e96ad6f2491db9e7a94f734ca09330b296d47f52.json | Remove HTML legend that is mostly unsupported. (#6887)
* Remove HTML legend that is mostly unsupported.
Resolves the discussion in #5070
* Add migration docs | test/specs/global.defaults.tests.js | @@ -88,24 +88,6 @@ describe('Default Configs', function() {
}]);
});
- it('should return the correct html legend', function() {
- var config = Chart.defaults.doughnut;
- var chart = window.acquireChart({
- type: 'doughnut',
- data: {
- labels: ['label1', 'label2'],
- datasets: [{
- data: [10, 20],
- backgroundColor: ['red', 'green']
- }]
- },
- options: config
- });
-
- var expectedLegend = '<ul class="' + chart.id + '-legend"><li><span style="background-color: red;"></span>label1</li><li><span style="background-color: green;"></span>label2</li></ul>';
- expect(chart.generateLegend()).toBe(expectedLegend);
- });
-
it('should return correct legend label objects', function() {
var config = Chart.defaults.doughnut;
var chart = window.acquireChart({
@@ -204,24 +186,6 @@ describe('Default Configs', function() {
}]);
});
- it('should return the correct html legend', function() {
- var config = Chart.defaults.polarArea;
- var chart = window.acquireChart({
- type: 'polarArea',
- data: {
- labels: ['label1', 'label2'],
- datasets: [{
- data: [10, 20],
- backgroundColor: ['red', 'green']
- }]
- },
- options: config
- });
-
- var expectedLegend = '<ul class="' + chart.id + '-legend"><li><span style="background-color: red;"></span>label1</li><li><span style="background-color: green;"></span>label2</li></ul>';
- expect(chart.generateLegend()).toBe(expectedLegend);
- });
-
it('should return correct legend label objects', function() {
var config = Chart.defaults.polarArea;
var chart = window.acquireChart({ | true |
Other | chartjs | Chart.js | 5d94cacb91b96083485781f22d6b0dc44efaad9e.json | Update documentation of `order` (#6897) | docs/charts/bar.md | @@ -88,7 +88,7 @@ the color of the bars is generally set this way.
| ---- | ----
| `clip` | How to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. `0` = clip at chartArea. Clipping can also be configured per side: `clip: {left: 5, top: false, right: -2, bottom: 0}`
| `label` | The label for the dataset which appears in the legend and tooltips.
-| `order` | The drawing order of dataset. Also affects order for stacking, tooltip, and legend.
+| `order` | The drawing order of dataset. Also affects order for stacking, tooltip and legend.
| `xAxisID` | The ID of the x axis to plot this dataset on.
| `yAxisID` | The ID of the y axis to plot this dataset on.
| true |
Other | chartjs | Chart.js | 5d94cacb91b96083485781f22d6b0dc44efaad9e.json | Update documentation of `order` (#6897) | docs/charts/bubble.md | @@ -62,7 +62,7 @@ The bubble chart allows a number of properties to be specified for each dataset.
| ---- | ----
| `clip` | How to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. `0` = clip at chartArea. Clipping can also be configured per side: `clip: {left: 5, top: false, right: -2, bottom: 0}`
| `label` | The label for the dataset which appears in the legend and tooltips.
-| `order` | The drawing order of dataset.
+| `order` | The drawing order of dataset. Also affects order for tooltip and legend.
### Styling
| true |
Other | chartjs | Chart.js | 5d94cacb91b96083485781f22d6b0dc44efaad9e.json | Update documentation of `order` (#6897) | docs/charts/line.md | @@ -88,7 +88,7 @@ The line chart allows a number of properties to be specified for each dataset. T
| ---- | ----
| `clip` | How to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. `0` = clip at chartArea. Clipping can also be configured per side: `clip: {left: 5, top: false, right: -2, bottom: 0}`
| `label` | The label for the dataset which appears in the legend and tooltips.
-| `order` | The drawing order of dataset. Also affects order for stacking, tooltip, and legend.
+| `order` | The drawing order of dataset. Also affects order for stacking, tooltip and legend.
| `xAxisID` | The ID of the x axis to plot this dataset on.
| `yAxisID` | The ID of the y axis to plot this dataset on.
| true |
Other | chartjs | Chart.js | 5d94cacb91b96083485781f22d6b0dc44efaad9e.json | Update documentation of `order` (#6897) | docs/charts/mixed.md | @@ -71,7 +71,7 @@ At this point we have a chart rendering how we'd like. It's important to note th
## Drawing order
- By default, datasets are drawn so that first one is top-most. This can be altered by specifying `order` option to datasets. `order` defaults to `0`.
+ By default, datasets are drawn so that first one is top-most. This can be altered by specifying `order` option to datasets. `order` defaults to `0`. Note that this also affects stacking, legend and tooltip. So its essentially the same as reordering the datasets.
```javascript
var mixedChart = new Chart(ctx, {
@@ -81,13 +81,13 @@ var mixedChart = new Chart(ctx, {
label: 'Bar Dataset',
data: [10, 20, 30, 40],
// this dataset is drawn below
- order: 1
+ order: 2
}, {
label: 'Line Dataset',
data: [10, 10, 10, 10],
type: 'line',
// this dataset is drawn on top
- order: 2
+ order: 1
}],
labels: ['January', 'February', 'March', 'April']
}, | true |
Other | chartjs | Chart.js | 5d94cacb91b96083485781f22d6b0dc44efaad9e.json | Update documentation of `order` (#6897) | docs/configuration/legend.md | @@ -3,6 +3,7 @@
The chart legend displays data about the datasets that are appearing on the chart.
## Configuration options
+
The legend configuration is passed into the `options.legend` namespace. The global options for the chart legend is defined in `Chart.defaults.global.legend`.
| Name | Type | Default | Description
@@ -20,14 +21,18 @@ The legend configuration is passed into the `options.legend` namespace. The glob
| `textDirection` | `string` | canvas' default | This will force the text direction `'rtl'|'ltr` on the canvas for rendering the legend, regardless of the css specified on the canvas
## Position
+
Position of the legend. Options are:
+
* `'top'`
* `'left'`
* `'bottom'`
* `'right'`
## Align
+
Alignment of the legend. Options are:
+
* `'start'`
* `'center'`
* `'end'`
@@ -115,6 +120,7 @@ var chart = new Chart(ctx, {
It can be common to want to trigger different behaviour when clicking an item in the legend. This can be easily achieved using a callback in the config object.
The default legend click handler is:
+
```javascript
function(e, legendItem) {
var index = legendItem.datasetIndex; | true |
Other | chartjs | Chart.js | 27129db2e81df037f14957ba52b86ea4e0087285.json | Update some dependencies that have security alerts (#6891) | package-lock.json | @@ -5069,9 +5069,9 @@
}
},
"handlebars": {
- "version": "4.5.1",
- "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.5.1.tgz",
- "integrity": "sha512-C29UoFzHe9yM61lOsIlCE5/mQVGrnIOrOq7maQl76L7tYPCgC1og0Ajt6uWnX4ZTxBPnjw+CUvawphwCfJgUnA==",
+ "version": "4.5.3",
+ "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.5.3.tgz",
+ "integrity": "sha512-3yPecJoJHK/4c6aZhSvxOyG4vJKDshV36VHp0iVCDVh7o9w2vwi3NSnL2MMPj3YdduqaBcu7cGbggJQM0br9xA==",
"dev": true,
"requires": {
"neo-async": "^2.6.0",
@@ -12687,15 +12687,15 @@
}
},
"rollup-plugin-terser": {
- "version": "5.1.2",
- "resolved": "https://registry.npmjs.org/rollup-plugin-terser/-/rollup-plugin-terser-5.1.2.tgz",
- "integrity": "sha512-sWKBCOS+vUkRtHtEiJPAf+WnBqk/C402fBD9AVHxSIXMqjsY7MnYWKYEUqGixtr0c8+1DjzUEPlNgOYQPVrS1g==",
+ "version": "5.1.3",
+ "resolved": "https://registry.npmjs.org/rollup-plugin-terser/-/rollup-plugin-terser-5.1.3.tgz",
+ "integrity": "sha512-FuFuXE5QUJ7snyxHLPp/0LFXJhdomKlIx/aK7Tg88Yubsx/UU/lmInoJafXJ4jwVVNcORJ1wRUC5T9cy5yk0wA==",
"dev": true,
"requires": {
"@babel/code-frame": "^7.0.0",
"jest-worker": "^24.6.0",
"rollup-pluginutils": "^2.8.1",
- "serialize-javascript": "^1.7.0",
+ "serialize-javascript": "^2.1.2",
"terser": "^4.1.0"
}
},
@@ -12781,9 +12781,9 @@
}
},
"serialize-javascript": {
- "version": "1.9.1",
- "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-1.9.1.tgz",
- "integrity": "sha512-0Vb/54WJ6k5v8sSWN09S0ora+Hnr+cX40r9F170nT+mSkaxltoE/7R3OrIdBSUv1OoiobH1QoWQbCnAO+e8J1A==",
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-2.1.2.tgz",
+ "integrity": "sha512-rs9OggEUF0V4jUSecXazOYsLfu7OGK2qIn3c7IPBiffz32XniEp/TX9Xmc9LQfK2nQ2QKHvZ2oygKUGU0lG4jQ==",
"dev": true
},
"set-blocking": { | true |
Other | chartjs | Chart.js | 27129db2e81df037f14957ba52b86ea4e0087285.json | Update some dependencies that have security alerts (#6891) | package.json | @@ -68,7 +68,7 @@
"rollup-plugin-commonjs": "^10.0.0",
"rollup-plugin-istanbul": "^2.0.1",
"rollup-plugin-node-resolve": "^5.0.0",
- "rollup-plugin-terser": "^5.0.0",
+ "rollup-plugin-terser": "^5.1.3",
"yargs": "^14.0.0"
},
"dependencies": { | true |
Other | chartjs | Chart.js | b35e5526869846c224d04f8d954cdd1cbdc0baac.json | Convert `Chart` class to an ES6 class (#6886)
* Chart class is now an ES6 class
* Use of const and let in core Chart class
* Use import/export for core Chart file | src/core/core.controller.js | @@ -1,17 +1,17 @@
'use strict';
-var Animator = require('./core.animator');
-var controllers = require('../controllers/index');
-var defaults = require('./core.defaults');
-var helpers = require('../helpers/index');
-var Interaction = require('./core.interaction');
-var layouts = require('./core.layouts');
-var platform = require('../platforms/platform');
-var plugins = require('./core.plugins');
-var scaleService = require('../core/core.scaleService');
-var Tooltip = require('./core.tooltip');
-
-var valueOrDefault = helpers.valueOrDefault;
+import Animator from './core.animator';
+import controllers from '../controllers/index';
+import defaults from './core.defaults';
+import helpers from '../helpers/index';
+import Interaction from './core.interaction';
+import layouts from './core.layouts';
+import platform from '../platforms/platform';
+import plugins from './core.plugins';
+import scaleService from '../core/core.scaleService';
+import Tooltip from './core.tooltip';
+
+const valueOrDefault = helpers.valueOrDefault;
defaults._set('global', {
elements: {},
@@ -167,24 +167,16 @@ function onAnimationProgress(ctx) {
helpers.callback(animationOptions && animationOptions.onProgress, arguments, chart);
}
-var Chart = function(item, config) {
- this.construct(item, config);
- return this;
-};
-
-helpers.extend(Chart.prototype, /** @lends Chart */ {
- /**
- * @private
- */
- construct: function(item, config) {
- var me = this;
+class Chart {
+ constructor(item, config) {
+ const me = this;
config = initConfig(config);
- var context = platform.acquireContext(item, config);
- var canvas = context && context.canvas;
- var height = canvas && canvas.height;
- var width = canvas && canvas.width;
+ const context = platform.acquireContext(item, config);
+ const canvas = context && context.canvas;
+ const height = canvas && canvas.height;
+ const width = canvas && canvas.width;
me.id = helpers.uid();
me.ctx = context;
@@ -225,13 +217,13 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
me.initialize();
me.update();
- },
+ }
/**
* @private
*/
- initialize: function() {
- var me = this;
+ initialize() {
+ const me = this;
// Before init plugin notification
plugins.notify(me, 'beforeInit');
@@ -251,30 +243,30 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
plugins.notify(me, 'afterInit');
return me;
- },
+ }
- clear: function() {
+ clear() {
helpers.canvas.clear(this);
return this;
- },
+ }
- stop: function() {
+ stop() {
Animator.stop(this);
return this;
- },
+ }
- resize: function(silent) {
- var me = this;
- var options = me.options;
- var canvas = me.canvas;
- var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
+ resize(silent) {
+ const me = this;
+ const options = me.options;
+ const canvas = me.canvas;
+ const aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
// the canvas render width and height will be casted to integers so make sure that
// the canvas display style uses the same integer values to avoid blurring effect.
// Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
- var newWidth = Math.max(0, Math.floor(helpers.dom.getMaximumWidth(canvas)));
- var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers.dom.getMaximumHeight(canvas)));
+ const newWidth = Math.max(0, Math.floor(helpers.dom.getMaximumWidth(canvas)));
+ const newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers.dom.getMaximumHeight(canvas)));
if (me.width === newWidth && me.height === newHeight) {
return;
@@ -289,7 +281,7 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
if (!silent) {
// Notify any plugins about the resize
- var newSize = {width: newWidth, height: newHeight};
+ const newSize = {width: newWidth, height: newHeight};
plugins.notify(me, 'resize', [newSize]);
// Notify of resize
@@ -300,12 +292,12 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
me.stop();
me.update('resize');
}
- },
+ }
- ensureScalesHaveIDs: function() {
- var options = this.options;
- var scalesOptions = options.scales || {};
- var scaleOptions = options.scale;
+ ensureScalesHaveIDs() {
+ const options = this.options;
+ const scalesOptions = options.scales || {};
+ const scaleOptions = options.scale;
helpers.each(scalesOptions, function(axisOptions, axisID) {
axisOptions.id = axisID;
@@ -314,12 +306,12 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
if (scaleOptions) {
scaleOptions.id = scaleOptions.id || 'scale';
}
- },
+ }
/**
* Builds a map of scale ID to scale object for future lookup.
*/
- buildOrUpdateScales: function() {
+ buildOrUpdateScales() {
const me = this;
const options = me.options;
const scaleOpts = options.scales;
@@ -399,7 +391,7 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
me.scales = scales;
scaleService.addScalesToLayout(this);
- },
+ }
/**
* Updates the given metaset with the given dataset index. Ensures it's stored at that index
@@ -408,20 +400,20 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
* @param {number} index - the dataset index
* @private
*/
- _updateMetasetIndex: function(meta, index) {
+ _updateMetasetIndex(meta, index) {
const metasets = this._metasets;
const oldIndex = meta.index;
if (oldIndex !== index) {
metasets[oldIndex] = metasets[index];
metasets[index] = meta;
meta.index = index;
}
- },
+ }
/**
* @private
*/
- _updateMetasets: function() {
+ _updateMetasets() {
const me = this;
const metasets = me._metasets;
const numData = me.data.datasets.length;
@@ -434,18 +426,18 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
metasets.splice(numData, numMeta - numData);
}
me._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));
- },
+ }
- buildOrUpdateControllers: function() {
- var me = this;
- var newControllers = [];
- var datasets = me.data.datasets;
- var i, ilen;
+ buildOrUpdateControllers() {
+ const me = this;
+ const newControllers = [];
+ const datasets = me.data.datasets;
+ let i, ilen;
for (i = 0, ilen = datasets.length; i < ilen; i++) {
- var dataset = datasets[i];
- var meta = me.getDatasetMeta(i);
- var type = dataset.type || me.config.type;
+ const dataset = datasets[i];
+ let meta = me.getDatasetMeta(i);
+ const type = dataset.type || me.config.type;
if (meta.type && meta.type !== type) {
me.destroyDatasetMeta(i);
@@ -461,7 +453,7 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
meta.controller.updateIndex(i);
meta.controller.linkScales();
} else {
- var ControllerClass = controllers[meta.type];
+ const ControllerClass = controllers[meta.type];
if (ControllerClass === undefined) {
throw new Error('"' + meta.type + '" is not a chart type.');
}
@@ -473,30 +465,30 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
me._updateMetasets();
return newControllers;
- },
+ }
/**
* Reset the elements of all datasets
* @private
*/
- resetElements: function() {
- var me = this;
+ resetElements() {
+ const me = this;
helpers.each(me.data.datasets, function(dataset, datasetIndex) {
me.getDatasetMeta(datasetIndex).controller.reset();
}, me);
- },
+ }
/**
* Resets the chart back to its state before the initial animation
*/
- reset: function() {
+ reset() {
this.resetElements();
this.tooltip.initialize();
- },
+ }
- update: function(mode) {
- var me = this;
- var i, ilen;
+ update(mode) {
+ const me = this;
+ let i, ilen;
me._updating = true;
@@ -511,7 +503,7 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
}
// Make sure dataset controllers are updated and new controllers are reset
- var newControllers = me.buildOrUpdateControllers();
+ const newControllers = me.buildOrUpdateControllers();
// Make sure all dataset controllers have correct meta data counts
for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
@@ -542,21 +534,21 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
me.render();
me._updating = false;
- },
+ }
/**
* Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
* hook, in which case, plugins will not be called on `afterLayout`.
* @private
*/
- updateLayout: function() {
- var me = this;
+ updateLayout() {
+ const me = this;
if (plugins.notify(me, 'beforeLayout') === false) {
return;
}
- layouts.update(this, this.width, this.height);
+ layouts.update(me, me.width, me.height);
me._layers = [];
helpers.each(me.boxes, function(box) {
@@ -573,33 +565,33 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
});
plugins.notify(me, 'afterLayout');
- },
+ }
/**
* Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
* hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
* @private
*/
- updateDatasets: function(mode) {
- var me = this;
+ updateDatasets(mode) {
+ const me = this;
if (plugins.notify(me, 'beforeDatasetsUpdate') === false) {
return;
}
- for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
+ for (let i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
me.updateDataset(i, mode);
}
plugins.notify(me, 'afterDatasetsUpdate');
- },
+ }
/**
* Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
* hook, in which case, plugins will not be called on `afterDatasetUpdate`.
* @private
*/
- updateDataset: function(index, mode) {
+ updateDataset(index, mode) {
const me = this;
const meta = me.getDatasetMeta(index);
const args = {meta, index, mode};
@@ -611,15 +603,15 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
meta.controller._update(mode);
plugins.notify(me, 'afterDatasetUpdate', [args]);
- },
+ }
- render: function() {
+ render() {
const me = this;
const animationOptions = me.options.animation;
if (plugins.notify(me, 'beforeRender') === false) {
return;
}
- var onComplete = function() {
+ const onComplete = function() {
plugins.notify(me, 'afterRender');
helpers.callback(animationOptions && animationOptions.onComplete, [], me);
};
@@ -632,11 +624,11 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
me.draw();
onComplete();
}
- },
+ }
- draw: function() {
- var me = this;
- var i, layers;
+ draw() {
+ const me = this;
+ let i, layers;
me.clear();
@@ -666,16 +658,16 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
me._drawTooltip();
plugins.notify(me, 'afterDraw');
- },
+ }
/**
* @private
*/
- _getSortedDatasetMetas: function(filterVisible) {
- var me = this;
- var metasets = me._sortedMetasets;
- var result = [];
- var i, ilen;
+ _getSortedDatasetMetas(filterVisible) {
+ const me = this;
+ const metasets = me._sortedMetasets;
+ const result = [];
+ let i, ilen;
for (i = 0, ilen = metasets.length; i < ilen; ++i) {
const meta = metasets[i];
@@ -685,23 +677,23 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
}
return result;
- },
+ }
/**
* @private
*/
- _getSortedVisibleDatasetMetas: function() {
+ _getSortedVisibleDatasetMetas() {
return this._getSortedDatasetMetas(true);
- },
+ }
/**
* Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
* hook, in which case, plugins will not be called on `afterDatasetsDraw`.
* @private
*/
- drawDatasets: function() {
- var me = this;
- var metasets, i;
+ drawDatasets() {
+ const me = this;
+ let metasets, i;
if (plugins.notify(me, 'beforeDatasetsDraw') === false) {
return;
@@ -713,20 +705,20 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
}
plugins.notify(me, 'afterDatasetsDraw');
- },
+ }
/**
* Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
* hook, in which case, plugins will not be called on `afterDatasetDraw`.
* @private
*/
- drawDataset: function(meta) {
- var me = this;
- var ctx = me.ctx;
- var clip = meta._clip;
- var canvas = me.canvas;
- var area = me.chartArea;
- var args = {
+ drawDataset(meta) {
+ const me = this;
+ const ctx = me.ctx;
+ const clip = meta._clip;
+ const canvas = me.canvas;
+ const area = me.chartArea;
+ const args = {
meta: meta,
index: meta.index,
};
@@ -747,17 +739,17 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
helpers.canvas.unclipArea(ctx);
plugins.notify(me, 'afterDatasetDraw', [args]);
- },
+ }
/**
* Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
* hook, in which case, plugins will not be called on `afterTooltipDraw`.
* @private
*/
- _drawTooltip: function() {
- var me = this;
- var tooltip = me.tooltip;
- var args = {
+ _drawTooltip() {
+ const me = this;
+ const tooltip = me.tooltip;
+ const args = {
tooltip: tooltip
};
@@ -768,38 +760,38 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
tooltip.draw(me.ctx);
plugins.notify(me, 'afterTooltipDraw', [args]);
- },
+ }
/**
* Get the single element that was clicked on
* @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
*/
- getElementAtEvent: function(e) {
+ getElementAtEvent(e) {
return Interaction.modes.nearest(this, e, {intersect: true});
- },
+ }
- getElementsAtEvent: function(e) {
+ getElementsAtEvent(e) {
return Interaction.modes.index(this, e, {intersect: true});
- },
+ }
- getElementsAtXAxis: function(e) {
+ getElementsAtXAxis(e) {
return Interaction.modes.index(this, e, {intersect: false});
- },
+ }
- getElementsAtEventForMode: function(e, mode, options) {
- var method = Interaction.modes[mode];
+ getElementsAtEventForMode(e, mode, options) {
+ const method = Interaction.modes[mode];
if (typeof method === 'function') {
return method(this, e, options);
}
return [];
- },
+ }
- getDatasetAtEvent: function(e) {
+ getDatasetAtEvent(e) {
return Interaction.modes.dataset(this, e, {intersect: true});
- },
+ }
- getDatasetMeta: function(datasetIndex) {
+ getDatasetMeta(datasetIndex) {
const me = this;
const dataset = me.data.datasets[datasetIndex];
const metasets = me._metasets;
@@ -822,41 +814,41 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
}
return meta;
- },
+ }
- getVisibleDatasetCount: function() {
+ getVisibleDatasetCount() {
return this._getSortedVisibleDatasetMetas().length;
- },
+ }
- isDatasetVisible: function(datasetIndex) {
- var meta = this.getDatasetMeta(datasetIndex);
+ isDatasetVisible(datasetIndex) {
+ const meta = this.getDatasetMeta(datasetIndex);
// meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
// the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
- },
+ }
- generateLegend: function() {
+ generateLegend() {
return this.options.legendCallback(this);
- },
+ }
/**
* @private
*/
- destroyDatasetMeta: function(datasetIndex) {
+ destroyDatasetMeta(datasetIndex) {
const me = this;
const meta = me._metasets && me._metasets[datasetIndex];
if (meta) {
meta.controller.destroy();
delete me._metasets[datasetIndex];
}
- },
+ }
- destroy: function() {
- var me = this;
- var canvas = me.canvas;
- var i, ilen;
+ destroy() {
+ const me = this;
+ const canvas = me.canvas;
+ let i, ilen;
me.stop();
@@ -876,23 +868,23 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
plugins.notify(me, 'destroy');
delete Chart.instances[me.id];
- },
+ }
- toBase64Image: function() {
+ toBase64Image() {
return this.canvas.toDataURL.apply(this.canvas, arguments);
- },
+ }
- initToolTip: function() {
+ initToolTip() {
this.tooltip = new Tooltip({_chart: this});
- },
+ }
/**
* @private
*/
- bindEvents: function() {
- var me = this;
- var listeners = me._listeners = {};
- var listener = function() {
+ bindEvents() {
+ const me = this;
+ const listeners = me._listeners = {};
+ let listener = function() {
me.eventHandler.apply(me, arguments);
};
@@ -911,14 +903,14 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
platform.addEventListener(me, 'resize', listener);
listeners.resize = listener;
}
- },
+ }
/**
* @private
*/
- unbindEvents: function() {
- var me = this;
- var listeners = me._listeners;
+ unbindEvents() {
+ const me = this;
+ const listeners = me._listeners;
if (!listeners) {
return;
}
@@ -927,11 +919,11 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
helpers.each(listeners, function(listener, type) {
platform.removeEventListener(me, type, listener);
});
- },
+ }
- updateHoverStyle: function(items, mode, enabled) {
- var prefix = enabled ? 'set' : 'remove';
- var meta, item, i, ilen;
+ updateHoverStyle(items, mode, enabled) {
+ const prefix = enabled ? 'set' : 'remove';
+ let meta, item, i, ilen;
if (mode === 'dataset') {
meta = this.getDatasetMeta(items[0].datasetIndex);
@@ -948,15 +940,15 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
this.getDatasetMeta(item.datasetIndex).controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
}
}
- },
+ }
/**
* @private
*/
- _updateHoverStyles: function() {
- var me = this;
- var options = me.options || {};
- var hoverOptions = options.hover;
+ _updateHoverStyles() {
+ const me = this;
+ const options = me.options || {};
+ const hoverOptions = options.hover;
// Remove styling for last active (even if it may still be active)
if (me.lastActive.length) {
@@ -967,12 +959,12 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
if (me.active.length && hoverOptions.mode) {
me.updateHoverStyle(me.active, hoverOptions.mode, true);
}
- },
+ }
/**
* @private
*/
- eventHandler: function(e) {
+ eventHandler(e) {
const me = this;
const tooltip = me.tooltip;
@@ -991,19 +983,19 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
me.render();
return me;
- },
+ }
/**
* Handle an event
* @private
* @param {IEvent} event the event to handle
* @return {boolean} true if the chart needs to re-render
*/
- handleEvent: function(e) {
- var me = this;
- var options = me.options || {};
- var hoverOptions = options.hover;
- var changed = false;
+ handleEvent(e) {
+ const me = this;
+ const options = me.options || {};
+ const hoverOptions = options.hover;
+ let changed = false;
me.lastActive = me.lastActive || [];
@@ -1037,7 +1029,7 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
return changed;
}
-});
+}
/**
* NOTE(SB) We actually don't use this container anymore but we need to keep it
@@ -1046,4 +1038,4 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
*/
Chart.instances = {};
-module.exports = Chart;
+export default Chart; | false |
Other | chartjs | Chart.js | f388ed3136a3b62f46e9f0e4c5ef96f175cc1670.json | Remove outdated element tests (#6869) | test/specs/element.arc.tests.js | @@ -1,17 +1,6 @@
// Test the rectangle element
describe('Arc element tests', function() {
- it ('Should be constructed', function() {
- var arc = new Chart.elements.Arc({
- _datasetIndex: 2,
- _index: 1
- });
-
- expect(arc).not.toBe(undefined);
- expect(arc._datasetIndex).toBe(2);
- expect(arc._index).toBe(1);
- });
-
it ('should determine if in range', function() {
// Mock out the arc as if the controller put it there
var arc = new Chart.elements.Arc({ | true |
Other | chartjs | Chart.js | f388ed3136a3b62f46e9f0e4c5ef96f175cc1670.json | Remove outdated element tests (#6869) | test/specs/element.point.tests.js | @@ -1,17 +1,6 @@
describe('Chart.elements.Point', function() {
describe('auto', jasmine.fixture.specs('element.point'));
- it ('Should be constructed', function() {
- var point = new Chart.elements.Point({
- _datasetIndex: 2,
- _index: 1
- });
-
- expect(point).not.toBe(undefined);
- expect(point._datasetIndex).toBe(2);
- expect(point._index).toBe(1);
- });
-
it ('Should correctly identify as in range', function() {
// Mock out the point as if we were made by the controller
var point = new Chart.elements.Point({ | true |
Other | chartjs | Chart.js | f388ed3136a3b62f46e9f0e4c5ef96f175cc1670.json | Remove outdated element tests (#6869) | test/specs/element.rectangle.tests.js | @@ -1,17 +1,6 @@
// Test the rectangle element
describe('Rectangle element tests', function() {
- it('Should be constructed', function() {
- var rectangle = new Chart.elements.Rectangle({
- _datasetIndex: 2,
- _index: 1
- });
-
- expect(rectangle).not.toBe(undefined);
- expect(rectangle._datasetIndex).toBe(2);
- expect(rectangle._index).toBe(1);
- });
-
it('Should correctly identify as in range', function() {
var rectangle = new Chart.elements.Rectangle({
base: 0, | true |
Other | chartjs | Chart.js | 8bc250f63a039f5507582840b06f965f816dcca2.json | Remove unnecessary method argument (#6878)
Remove unnecessary method argument | docs/getting-started/v3-migration.md | @@ -106,7 +106,6 @@ Animation system was completely rewritten in Chart.js v3. Each property can now
* `Chart.Animation.animationObject` was renamed to `Chart.Animation`
* `Chart.Animation.chartInstance` was renamed to `Chart.Animation.chart`
-* `DatasetController.updateElement` was renamed to `DatasetController.updateElements`
* `helpers._decimalPlaces` was renamed to `helpers.math._decimalPlaces`
* `helpers.almostEquals` was renamed to `helpers.math.almostEquals`
* `helpers.almostWhole` was renamed to `helpers.math.almostWhole`
@@ -168,6 +167,7 @@ Animation system was completely rewritten in Chart.js v3. Each property can now
##### Dataset Controllers
+* `updateElement` was replaced with `updateElements` now taking the elements to update, the `start` index, and `mode`
* `setHoverStyle` and `removeHoverStyle` now additionally take the `datasetIndex` and `index`
#### Interactions | true |
Other | chartjs | Chart.js | 8bc250f63a039f5507582840b06f965f816dcca2.json | Remove unnecessary method argument (#6878)
Remove unnecessary method argument | src/controllers/controller.bar.js | @@ -277,10 +277,10 @@ module.exports = DatasetController.extend({
const me = this;
const rects = me._cachedMeta.data;
- me.updateElements(rects, 0, rects.length, mode);
+ me.updateElements(rects, 0, mode);
},
- updateElements: function(rectangles, start, count, mode) {
+ updateElements: function(rectangles, start, mode) {
const me = this;
const reset = mode === 'reset';
const vscale = me._cachedMeta.vScale;
@@ -293,10 +293,11 @@ module.exports = DatasetController.extend({
let i;
- for (i = 0; i < start + count; i++) {
- const options = me._resolveDataElementOptions(i, mode);
- const vpixels = me.calculateBarValuePixels(i, options);
- const ipixels = me.calculateBarIndexPixels(i, ruler, options);
+ for (i = 0; i < rectangles.length; i++) {
+ const index = start + i;
+ const options = me._resolveDataElementOptions(index, mode);
+ const vpixels = me.calculateBarValuePixels(index, options);
+ const ipixels = me.calculateBarIndexPixels(index, ruler, options);
const properties = {
horizontal,
@@ -316,7 +317,7 @@ module.exports = DatasetController.extend({
if (includeOptions) {
properties.options = options;
}
- me._updateElement(rectangles[i], i, properties, mode);
+ me._updateElement(rectangles[i], index, properties, mode);
}
me._updateSharedOptions(sharedOptions, mode); | true |
Other | chartjs | Chart.js | 8bc250f63a039f5507582840b06f965f816dcca2.json | Remove unnecessary method argument (#6878)
Remove unnecessary method argument | src/controllers/controller.bubble.js | @@ -114,13 +114,13 @@ module.exports = DatasetController.extend({
const points = me._cachedMeta.data;
// Update Points
- me.updateElements(points, 0, points.length, mode);
+ me.updateElements(points, 0, mode);
},
/**
* @protected
*/
- updateElements: function(points, start, count, mode) {
+ updateElements: function(points, start, mode) {
const me = this;
const reset = mode === 'reset';
const {xScale, yScale} = me._cachedMeta;
@@ -129,9 +129,10 @@ module.exports = DatasetController.extend({
const includeOptions = me._includeOptions(mode, sharedOptions);
let i;
- for (i = start; i < start + count; i++) {
+ for (i = 0; i < points.length; i++) {
const point = points[i];
- const parsed = !reset && me._getParsed(i);
+ const index = start + i;
+ const parsed = !reset && me._getParsed(index);
const x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(parsed[xScale.id]);
const y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(parsed[yScale.id]);
const properties = {
@@ -141,15 +142,15 @@ module.exports = DatasetController.extend({
};
if (includeOptions) {
- properties.options = i === start ? firstOpts
+ properties.options = i === 0 ? firstOpts
: me._resolveDataElementOptions(i, mode);
if (reset) {
properties.options.radius = 0;
}
}
- me._updateElement(point, i, properties, mode);
+ me._updateElement(point, index, properties, mode);
}
me._updateSharedOptions(sharedOptions, mode); | true |
Other | chartjs | Chart.js | 8bc250f63a039f5507582840b06f965f816dcca2.json | Remove unnecessary method argument (#6878)
Remove unnecessary method argument | src/controllers/controller.doughnut.js | @@ -221,10 +221,20 @@ module.exports = DatasetController.extend({
me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
- me.updateElements(arcs, 0, arcs.length, mode);
+ me.updateElements(arcs, 0, mode);
},
- updateElements: function(arcs, start, count, mode) {
+ /**
+ * @private
+ */
+ _circumference: function(i, reset) {
+ const me = this;
+ const opts = me.chart.options;
+ const meta = me._cachedMeta;
+ return reset && opts.animation.animateRotate ? 0 : meta.data[i].hidden ? 0 : me.calculateCircumference(meta._parsed[i] * opts.circumference / DOUBLE_PI);
+ },
+
+ updateElements: function(arcs, start, mode) {
const me = this;
const reset = mode === 'reset';
const chart = me.chart;
@@ -233,20 +243,20 @@ module.exports = DatasetController.extend({
const animationOpts = opts.animation;
const centerX = (chartArea.left + chartArea.right) / 2;
const centerY = (chartArea.top + chartArea.bottom) / 2;
- const meta = me.getMeta();
const innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
const outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
let startAngle = opts.rotation;
let i;
- for (i = 0; i < start + count; ++i) {
+ for (i = 0; i < start; ++i) {
+ startAngle += me._circumference(i, reset);
+ }
+
+ for (i = 0; i < arcs.length; ++i) {
+ const index = start + i;
+ const circumference = me._circumference(index, reset);
const arc = arcs[i];
- const circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(meta._parsed[i] * opts.circumference / DOUBLE_PI);
const options = arc._options || {};
- if (i < start) {
- startAngle += circumference;
- continue;
- }
const properties = {
x: centerX + chart.offsetX,
y: centerY + chart.offsetY,
@@ -259,7 +269,7 @@ module.exports = DatasetController.extend({
};
startAngle += circumference;
- me._updateElement(arc, i, properties, mode);
+ me._updateElement(arc, index, properties, mode);
}
},
| true |
Other | chartjs | Chart.js | 8bc250f63a039f5507582840b06f965f816dcca2.json | Remove unnecessary method argument (#6878)
Remove unnecessary method argument | src/controllers/controller.line.js | @@ -88,11 +88,11 @@ module.exports = DatasetController.extend({
// Update Points
if (meta.visible) {
- me.updateElements(points, 0, points.length, mode);
+ me.updateElements(points, 0, mode);
}
},
- updateElements: function(points, start, count, mode) {
+ updateElements: function(points, start, mode) {
const me = this;
const reset = mode === 'reset';
const {xScale, yScale, _stacked} = me._cachedMeta;
@@ -101,9 +101,10 @@ module.exports = DatasetController.extend({
const includeOptions = me._includeOptions(mode, sharedOptions);
let i;
- for (i = start; i < start + count; ++i) {
+ for (i = 0; i < points.length; ++i) {
+ const index = start + i;
const point = points[i];
- const parsed = me._getParsed(i);
+ const parsed = me._getParsed(index);
const x = xScale.getPixelForValue(parsed[xScale.id]);
const y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(_stacked ? me._applyStack(yScale, parsed) : parsed[yScale.id]);
const properties = {
@@ -113,11 +114,11 @@ module.exports = DatasetController.extend({
};
if (includeOptions) {
- properties.options = i === start ? firstOpts
- : me._resolveDataElementOptions(i, mode);
+ properties.options = i === 0 ? firstOpts
+ : me._resolveDataElementOptions(index, mode);
}
- me._updateElement(point, i, properties, mode);
+ me._updateElement(point, index, properties, mode);
}
me._updateSharedOptions(sharedOptions, mode); | true |
Other | chartjs | Chart.js | 8bc250f63a039f5507582840b06f965f816dcca2.json | Remove unnecessary method argument (#6878)
Remove unnecessary method argument | src/controllers/controller.polarArea.js | @@ -144,7 +144,7 @@ module.exports = DatasetController.extend({
me._updateRadius();
- me.updateElements(arcs, 0, arcs.length, mode);
+ me.updateElements(arcs, 0, mode);
},
/**
@@ -165,7 +165,7 @@ module.exports = DatasetController.extend({
me.innerRadius = me.outerRadius - chart.radiusLength;
},
- updateElements: function(arcs, start, count, mode) {
+ updateElements: function(arcs, start, mode) {
const me = this;
const reset = mode === 'reset';
const chart = me.chart;
@@ -184,11 +184,12 @@ module.exports = DatasetController.extend({
for (i = 0; i < start; ++i) {
angle += me._computeAngle(i);
}
- for (; i < start + count; i++) {
+ for (i = 0; i < arcs.length; i++) {
const arc = arcs[i];
+ const index = start + i;
let startAngle = angle;
- let endAngle = angle + me._computeAngle(i);
- let outerRadius = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[i]);
+ let endAngle = angle + me._computeAngle(index);
+ let outerRadius = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
angle = endAngle;
if (reset) {
@@ -208,10 +209,10 @@ module.exports = DatasetController.extend({
outerRadius,
startAngle,
endAngle,
- options: me._resolveDataElementOptions(i)
+ options: me._resolveDataElementOptions(index)
};
- me._updateElement(arc, i, properties, mode);
+ me._updateElement(arc, index, properties, mode);
}
},
| true |
Other | chartjs | Chart.js | 8bc250f63a039f5507582840b06f965f816dcca2.json | Remove unnecessary method argument (#6878)
Remove unnecessary method argument | src/controllers/controller.radar.js | @@ -86,10 +86,10 @@ module.exports = DatasetController.extend({
},
update: function(mode) {
- var me = this;
- var meta = me._cachedMeta;
- var line = meta.dataset;
- var points = meta.data || [];
+ const me = this;
+ const meta = me._cachedMeta;
+ const line = meta.dataset;
+ const points = meta.data || [];
const properties = {
_children: points,
@@ -100,22 +100,23 @@ module.exports = DatasetController.extend({
me._updateElement(line, undefined, properties, mode);
// Update Points
- me.updateElements(points, 0, points.length, mode);
+ me.updateElements(points, 0, mode);
line.updateControlPoints(me.chart.chartArea);
},
- updateElements: function(points, start, count, mode) {
+ updateElements: function(points, start, mode) {
const me = this;
const dataset = me.getDataset();
const scale = me.chart.scales.r;
const reset = mode === 'reset';
- var i;
+ let i;
- for (i = start; i < start + count; i++) {
+ for (i = 0; i < points.length; i++) {
const point = points[i];
- const options = me._resolveDataElementOptions(i);
- const pointPosition = scale.getPointPositionForValue(i, dataset.data[i]);
+ const index = start + i;
+ const options = me._resolveDataElementOptions(index);
+ const pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
const x = reset ? scale.xCenter : pointPosition.x;
const y = reset ? scale.yCenter : pointPosition.y;
@@ -127,18 +128,18 @@ module.exports = DatasetController.extend({
options,
};
- me._updateElement(point, i, properties, mode);
+ me._updateElement(point, index, properties, mode);
}
},
/**
* @private
*/
_resolveDatasetElementOptions: function() {
- var me = this;
- var config = me._config;
- var options = me.chart.options;
- var values = DatasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
+ const me = this;
+ const config = me._config;
+ const options = me.chart.options;
+ const values = DatasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
values.spanGaps = valueOrDefault(config.spanGaps, options.spanGaps);
values.tension = valueOrDefault(config.lineTension, options.elements.line.tension); | true |
Other | chartjs | Chart.js | 8bc250f63a039f5507582840b06f965f816dcca2.json | Remove unnecessary method argument (#6878)
Remove unnecessary method argument | src/core/core.datasetController.js | @@ -1063,7 +1063,7 @@ helpers.extend(DatasetController.prototype, {
}
me._parse(start, count);
- me.updateElements(data, start, count, 'reset');
+ me.updateElements(elements, start, 'reset');
},
/** | true |
Other | chartjs | Chart.js | dbd835f4f33d99395ef5951edb4deef1e2df49e0.json | Use ticks consistently (#6873) | src/controllers/controller.bar.js | @@ -53,7 +53,7 @@ function computeMinSampleSize(scale, pixels) {
min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
}
- for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) {
+ for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {
curr = scale.getPixelForTick(i);
min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;
prev = curr; | true |
Other | chartjs | Chart.js | dbd835f4f33d99395ef5951edb4deef1e2df49e0.json | Use ticks consistently (#6873) | src/scales/scale.category.js | @@ -78,7 +78,7 @@ class CategoryScale extends Scale {
if (index < 0 || index > ticks.length - 1) {
return null;
}
- return this.getPixelForValue(index * me._numLabels / ticks.length + this.min);
+ return me.getPixelForValue(index * me._numLabels / ticks.length + me.min);
}
getValueForPixel(pixel) { | true |
Other | chartjs | Chart.js | dbd835f4f33d99395ef5951edb4deef1e2df49e0.json | Use ticks consistently (#6873) | src/scales/scale.linear.js | @@ -63,11 +63,11 @@ class LinearScale extends LinearScaleBase {
}
getPixelForTick(index) {
- var ticks = this._tickValues;
+ const ticks = this.ticks;
if (index < 0 || index > ticks.length - 1) {
return null;
}
- return this.getPixelForValue(ticks[index]);
+ return this.getPixelForValue(ticks[index].value);
}
}
| true |
Other | chartjs | Chart.js | dbd835f4f33d99395ef5951edb4deef1e2df49e0.json | Use ticks consistently (#6873) | src/scales/scale.linearbase.js | @@ -231,15 +231,9 @@ class LinearScaleBase extends Scale {
return ticks;
}
- generateTickLabels(ticks) {
- var me = this;
- me._tickValues = ticks.map(t => t.value);
- Scale.prototype.generateTickLabels.call(me, ticks);
- }
-
_configure() {
var me = this;
- var ticks = me.getTicks();
+ var ticks = me.ticks;
var start = me.min;
var end = me.max;
var offset; | true |
Other | chartjs | Chart.js | dbd835f4f33d99395ef5951edb4deef1e2df49e0.json | Use ticks consistently (#6873) | src/scales/scale.radialLinear.js | @@ -450,7 +450,7 @@ class RadialLinearScale extends LinearScaleBase {
if (gridLineOpts.display) {
me.ticks.forEach(function(tick, index) {
if (index !== 0) {
- offset = me.getDistanceFromCenterForValue(me._tickValues[index]);
+ offset = me.getDistanceFromCenterForValue(me.ticks[index].value);
drawRadiusLine(me, gridLineOpts, offset, index);
}
});
@@ -508,7 +508,7 @@ class RadialLinearScale extends LinearScaleBase {
return;
}
- offset = me.getDistanceFromCenterForValue(me._tickValues[index]);
+ offset = me.getDistanceFromCenterForValue(me.ticks[index].value);
if (tickOpts.showLabelBackdrop) {
width = ctx.measureText(tick.label).width; | true |
Other | chartjs | Chart.js | dbd835f4f33d99395ef5951edb4deef1e2df49e0.json | Use ticks consistently (#6873) | src/scales/scale.time.js | @@ -703,10 +703,11 @@ class TimeScale extends Scale {
}
getPixelForTick(index) {
- const ticks = this.getTicks();
- return index >= 0 && index < ticks.length ?
- this.getPixelForValue(ticks[index].value) :
- null;
+ const ticks = this.ticks;
+ if (index < 0 || index > ticks.length - 1) {
+ return null;
+ }
+ return this.getPixelForValue(ticks[index].value);
}
getValueForPixel(pixel) { | true |
Other | chartjs | Chart.js | e39970d494edf5f503072e0b0038b46465233868.json | Alphabetize migration guide (#6865)
Alphabetize migration guide | docs/getting-started/v3-migration.md | @@ -19,26 +19,25 @@ Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released
### Interactions
-* `options.onClick` is now limited to the chart area
-* `{mode: 'single'}` was replaced with `{mode: 'nearest', intersect: true}`
* `{mode: 'label'}` was replaced with `{mode: 'index'}`
+* `{mode: 'single'}` was replaced with `{mode: 'nearest', intersect: true}`
* `modes['X-axis']` was replaced with `{mode: 'index', intersect: false}`
+* `options.onClick` is now limited to the chart area
### Customizability
* `custom` attribute of elements was removed. Please use scriptable options
-* The `zeroLine*` options of axes were removed. Use scriptable scale options instead.
* The `hover` property of scriptable options `context` object was renamed to `active` to align it with the datalabels plugin.
+* The `zeroLine*` options of axes were removed. Use scriptable scale options instead.
### 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.minBarLength` was moved to dataset option `minBarLength`
* `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`
@@ -48,6 +47,7 @@ Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released
* `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`
+* The dataset option `tension` was renamed to `lineTension`
### Animations
@@ -60,36 +60,36 @@ Animation system was completely rewritten in Chart.js v3. Each property can now
### Removed
+* `Chart.chart.chart`
+* `Chart.Controller`
+* `Chart.types`
+* `DatasetController.addElementAndReset`
+* `DatasetController.createMetaData`
+* `DatasetController.createMetaDataset`
+* `Element.getArea`
+* `Element.height`
+* `Element.initialize`
+* `Element.inLabelRange`
* `helpers.addEvent`
* `helpers.aliasPixel`
* `helpers.configMerge`
* `helpers.indexOf`
* `helpers.lineTo`
-* `helpers.min`
* `helpers.max`
+* `helpers.min`
* `helpers.nextItem`
* `helpers.numberOfLabelLines`
* `helpers.previousItem`
* `helpers.removeEvent`
* `helpers.roundedRect`
* `helpers.scaleMerge`
* `helpers.where`
-* `Chart.Controller`
-* `Chart.chart.chart`
-* `Chart.types`
-* `DatasetController.addElementAndReset`
-* `DatasetController.createMetaData`
-* `DatasetController.createMetaDataset`
-* `Element.getArea`
-* `Element.height`
-* `Element.initialize`
-* `Element.inLabelRange`
* `IPlugin.afterScaleUpdate`. Use `afterLayout` instead
* `Line.calculatePointY`
* `Scale.getRightValue`
+* `Scale.handleDirectionalChanges` is now private
* `Scale.mergeTicksOptions`
* `Scale.ticksAsNumbers`
-* `Scale.handleDirectionalChanges` is now private
* `Scale.tickValues` is now private
* The tooltip item's `x` and `y` attributes were removed. Use `datasetIndex` and `index` to get the element and any corresponding data from it
@@ -104,35 +104,36 @@ Animation system was completely rewritten in Chart.js v3. Each property can now
### Renamed
+* `Chart.Animation.animationObject` was renamed to `Chart.Animation`
+* `Chart.Animation.chartInstance` was renamed to `Chart.Animation.chart`
+* `DatasetController.updateElement` was renamed to `DatasetController.updateElements`
+* `helpers._decimalPlaces` was renamed to `helpers.math._decimalPlaces`
+* `helpers.almostEquals` was renamed to `helpers.math.almostEquals`
+* `helpers.almostWhole` was renamed to `helpers.math.almostWhole`
+* `helpers.callCallback` was renamed to `helpers.callback`
* `helpers.clear` was renamed to `helpers.canvas.clear`
+* `helpers.distanceBetweenPoints` was renamed to `helpers.math.distanceBetweenPoints`
* `helpers.drawRoundedRectangle` was renamed to `helpers.canvas.roundedRect`
-* `helpers.callCallback` was renamed to `helpers.callback`
-* `helpers.getValueOrDefault` was renamed to `helpers.valueOrDefault`
+* `helpers.getAngleFromPoint` was renamed to `helpers.math.getAngleFromPoint`
+* `helpers.getMaximumHeight` was renamed to `helpers.dom.getMaximumHeight`
+* `helpers.getMaximumWidth` was renamed to `helpers.dom.getMaximumWidth`
+* `helpers.getRelativePosition` was renamed to `helpers.dom.getRelativePosition`
+* `helpers.getStyle` was renamed to `helpers.dom.getStyle`
* `helpers.getValueAtIndexOrDefault` was renamed to `helpers.valueAtIndexOrDefault`
+* `helpers.getValueOrDefault` was renamed to `helpers.valueOrDefault`
* `helpers.easingEffects` was renamed to `helpers.easing.effects`
* `helpers.log10` was renamed to `helpers.math.log10`
-* `helpers.almostEquals` was renamed to `helpers.math.almostEquals`
-* `helpers.almostWhole` was renamed to `helpers.math.almostWhole`
-* `helpers.distanceBetweenPoints` was renamed to `helpers.math.distanceBetweenPoints`
* `helpers.isNumber` was renamed to `helpers.math.isNumber`
* `helpers.sign` was renamed to `helpers.math.sign`
+* `helpers.retinaScale` was renamed to `helpers.dom.retinaScale`
+* `helpers.splineCurve` was renamed to `helpers.curve.splineCurve`
+* `helpers.splineCurveMonotone` was renamed to `helpers.curve.splineCurveMonotone`
* `helpers.toDegrees` was renamed to `helpers.math.toDegrees`
* `helpers.toRadians` was renamed to `helpers.math.toRadians`
-* `helpers.getAngleFromPoint` was renamed to `helpers.math.getAngleFromPoint`
-* `helpers.splineCurveMonotone` was renamed to `helpers.curve.splineCurveMonotone`
-* `helpers.splineCurve` was renamed to `helpers.curve.splineCurve`
-* `helpers.retinaScale` was renamed to `helpers.dom.retinaScale`
-* `helpers.getMaximumWidth` was renamed to `helpers.dom.getMaximumWidth`
-* `helpers.getMaximumHeight` was renamed to `helpers.dom.getMaximumHeight`
-* `helpers.getRelativePosition` was renamed to `helpers.dom.getRelativePosition`
-* `helpers.getStyle` was renamed to `helpers.dom.getStyle`
-* `Chart.Animation.animationObject` was renamed to `Chart.Animation`
-* `Chart.Animation.chartInstance` was renamed to `Chart.Animation.chart`
-* `DatasetController.updateElement` was renamed to `DatasetController.updateElements`
* `Scale.calculateTickRotation` was renamed to `Scale.calculateLabelRotation`
* `TimeScale.getLabelCapacity` was renamed to `TimeScale._getLabelCapacity`
-* `TimeScale.tickFormatFunction` was renamed to `TimeScale._tickFormatFunction`
* `TimeScale.getPixelForOffset` was renamed to `TimeScale._getPixelForOffset`
+* `TimeScale.tickFormatFunction` was renamed to `TimeScale._tickFormatFunction`
* `Tooltip.options.legendColorBackgroupd` was renamed to `Tooltip.options.multiKeyBackground`
#### Renamed private APIs
@@ -149,11 +150,11 @@ Animation system was completely rewritten in Chart.js v3. Each property can now
##### Ticks
-* When the `autoSkip` option is enabled, `Scale.ticks` now contains only the non-skipped ticks instead of all ticks.
-* `Scale.ticks` now contains objects instead of strings
-* `Scale.buildTicks` is now expected to return tick objects
* `Scale.afterBuildTicks` now has no parameters like the other callbacks
+* `Scale.buildTicks` is now expected to return tick objects
* `Scale.convertTicksToLabels` was renamed to `generateTickLabels`. It is now expected to set the label property on the ticks given as input
+* `Scale.ticks` now contains objects instead of strings
+* When the `autoSkip` option is enabled, `Scale.ticks` now contains only the non-skipped ticks instead of all ticks.
##### Time Scale
| false |
Other | chartjs | Chart.js | 3abe9bfebf05b3c52fb7edd4cb190c42a55e3755.json | Replace Object.entries with Object.keys (#6862) | src/core/core.controller.js | @@ -44,10 +44,10 @@ function mergeScaleConfig(config, options) {
// First figure out first scale id's per axis.
// Note: for now, axis is determined from first letter of scale id!
- Object.entries(configScales).forEach(([id, scale]) => {
+ Object.keys(configScales).forEach(id => {
const axis = id[0];
firstIDs[axis] = firstIDs[axis] || id;
- scales[id] = helpers.mergeIf({}, [scale, chartDefaults.scales[axis]]);
+ scales[id] = helpers.mergeIf({}, [configScales[id], chartDefaults.scales[axis]]);
});
// Backward compatibility
@@ -59,12 +59,13 @@ function mergeScaleConfig(config, options) {
// Then merge dataset defaults to scale configs
config.data.datasets.forEach(dataset => {
const datasetDefaults = defaults[dataset.type || config.type] || {scales: {}};
- Object.entries(datasetDefaults.scales || {}).forEach(([defaultID, defaultScaleOptions]) => {
+ const defaultScaleOptions = datasetDefaults.scales || {};
+ Object.keys(defaultScaleOptions).forEach(defaultID => {
const id = dataset[defaultID + 'AxisID'] || firstIDs[defaultID] || defaultID;
scales[id] = scales[id] || {};
helpers.mergeIf(scales[id], [
configScales[id],
- defaultScaleOptions
+ defaultScaleOptions[defaultID]
]);
});
});
@@ -312,22 +313,22 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
* Builds a map of scale ID to scale object for future lookup.
*/
buildOrUpdateScales: function() {
- var me = this;
- var options = me.options;
- var scales = me.scales || {};
- var items = [];
- var updated = Object.keys(scales).reduce(function(obj, id) {
+ const me = this;
+ const options = me.options;
+ const scaleOpts = options.scales;
+ const scales = me.scales || {};
+ const updated = Object.keys(scales).reduce(function(obj, id) {
obj[id] = false;
return obj;
}, {});
+ let items = [];
- if (options.scales) {
+ if (scaleOpts) {
items = items.concat(
- Object.entries(options.scales).map(function(entry) {
- var axisID = entry[0];
- var axisOptions = entry[1];
- var isRadial = axisID.charAt(0).toLowerCase === 'r';
- var isHorizontal = axisID.charAt(0).toLowerCase() === 'x';
+ Object.keys(scaleOpts).map(function(axisID) {
+ const axisOptions = scaleOpts[axisID];
+ const isRadial = axisID.charAt(0).toLowerCase === 'r';
+ const isHorizontal = axisID.charAt(0).toLowerCase() === 'x';
return {
options: axisOptions,
dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',
@@ -338,23 +339,23 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
}
helpers.each(items, function(item) {
- var scaleOptions = item.options;
- var id = scaleOptions.id;
- var scaleType = valueOrDefault(scaleOptions.type, item.dtype);
+ const scaleOptions = item.options;
+ const id = scaleOptions.id;
+ const scaleType = valueOrDefault(scaleOptions.type, item.dtype);
if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, scaleOptions.axis || id[0]) !== positionIsHorizontal(item.dposition)) {
scaleOptions.position = item.dposition;
}
updated[id] = true;
- var scale = null;
+ let scale = null;
if (id in scales && scales[id].type === scaleType) {
scale = scales[id];
scale.options = scaleOptions;
scale.ctx = me.ctx;
scale.chart = me;
} else {
- var scaleClass = scaleService.getScaleConstructor(scaleType);
+ const scaleClass = scaleService.getScaleConstructor(scaleType);
if (!scaleClass) {
return;
} | false |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | docs/getting-started/v3-migration.md | @@ -105,6 +105,22 @@ Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released
* `helpers.getValueAtIndexOrDefault` was renamed to `helpers.valueAtIndexOrDefault`
* `helpers.easingEffects` was renamed to `helpers.easing.effects`
* `helpers.log10` was renamed to `helpers.math.log10`
+* `helpers.almostEquals` was renamed to `helpers.math.almostEquals`
+* `helpers.almostWhole` was renamed to `helpers.math.almostWhole`
+* `helpers._decimalPlaces` was renamed to `helpers.math._decimalPlaces`
+* `helpers.distanceBetweenPoints` was renamed to `helpers.math.distanceBetweenPoints`
+* `helpers.isNumber` was renamed to `helpers.math.isNumber`
+* `helpers.sign` was renamed to `helpers.math.sign`
+* `helpers.toDegrees` was renamed to `helpers.math.toDegrees`
+* `helpers.toRadians` was renamed to `helpers.math.toRadians`
+* `helpers.getAngleFromPoint` was renamed to `helpers.math.getAngleFromPoint`
+* `helpers.splineCurveMonotone` was renamed to `helpers.curve.splineCurveMonotone`
+* `helpers.splineCurve` was renamed to `helpers.curve.splineCurve`
+* `helpers.retinaScale` was renamed to `helpers.dom.retinaScale`
+* `helpers.getMaximumWidth` was renamed to `helpers.dom.getMaximumWidth`
+* `helpers.getMaximumHeight` was renamed to `helpers.dom.getMaximumHeight`
+* `helpers.getRelativePosition` was renamed to `helpers.dom.getRelativePosition`
+* `helpers.getStyle` was renamed to `helpers.dom.getStyle`
* `Chart.Animation.animationObject` was renamed to `Chart.Animation`
* `Chart.Animation.chartInstance` was renamed to `Chart.Animation.chart`
* `DatasetController.updateElement` was renamed to `DatasetController.updateElements` | true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/controllers/controller.bar.js | @@ -422,7 +422,7 @@ module.exports = DatasetController.extend({
value = custom.barStart;
length = custom.barEnd - custom.barStart;
// bars crossing origin are not stacked
- if (value !== 0 && helpers.sign(value) !== helpers.sign(custom.barEnd)) {
+ if (value !== 0 && helpers.math.sign(value) !== helpers.math.sign(custom.barEnd)) {
start = 0;
}
start += value; | true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/controllers/controller.line.js | @@ -188,11 +188,11 @@ module.exports = DatasetController.extend({
}
if (lineModel.cubicInterpolationMode === 'monotone') {
- helpers.splineCurveMonotone(points);
+ helpers.curve.splineCurveMonotone(points);
} else {
for (i = 0, ilen = points.length; i < ilen; ++i) {
const model = points[i]._model;
- const controlPoints = helpers.splineCurve(
+ const controlPoints = helpers.curve.splineCurve(
points[Math.max(0, i - 1)]._model,
model,
points[Math.min(i + 1, ilen - 1)]._model, | true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/controllers/controller.radar.js | @@ -192,7 +192,7 @@ module.exports = DatasetController.extend({
for (i = 0, ilen = points.length; i < ilen; ++i) {
model = points[i]._model;
- controlPoints = helpers.splineCurve(
+ controlPoints = helpers.curve.splineCurve(
previousItem(points, i)._model,
model,
nextItem(points, i)._model, | true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/core/core.controller.js | @@ -225,7 +225,7 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
// Before init plugin notification
plugins.notify(me, 'beforeInit');
- helpers.retinaScale(me, me.options.devicePixelRatio);
+ helpers.dom.retinaScale(me, me.options.devicePixelRatio);
me.bindEvents();
@@ -263,8 +263,8 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
// the canvas display style uses the same integer values to avoid blurring effect.
// Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
- var newWidth = Math.max(0, Math.floor(helpers.getMaximumWidth(canvas)));
- var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas)));
+ var newWidth = Math.max(0, Math.floor(helpers.dom.getMaximumWidth(canvas)));
+ var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers.dom.getMaximumHeight(canvas)));
if (me.width === newWidth && me.height === newHeight) {
return;
@@ -275,7 +275,7 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
canvas.style.width = newWidth + 'px';
canvas.style.height = newHeight + 'px';
- helpers.retinaScale(me, options.devicePixelRatio);
+ helpers.dom.retinaScale(me, options.devicePixelRatio);
if (!silent) {
// Notify any plugins about the resize | true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/core/core.datasetController.js | @@ -145,7 +145,7 @@ function applyStack(stack, value, dsIndex, allOther) {
break;
}
otherValue = stack.values[datasetIndex];
- if (!isNaN(otherValue) && (value === 0 || helpers.sign(value) === helpers.sign(otherValue))) {
+ if (!isNaN(otherValue) && (value === 0 || helpers.math.sign(value) === helpers.math.sign(otherValue))) {
value += otherValue;
}
} | true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/core/core.element.js | @@ -1,7 +1,8 @@
'use strict';
-const color = require('chartjs-color');
-const helpers = require('../helpers/index');
+import color from 'chartjs-color';
+import helpers from '../helpers/index';
+import {isNumber} from '../helpers/helpers.math';
function interpolate(start, view, model, ease) {
var keys = Object.keys(model);
@@ -110,10 +111,9 @@ class Element {
}
hasValue() {
- return helpers.isNumber(this._model.x) && helpers.isNumber(this._model.y);
+ return isNumber(this._model.x) && isNumber(this._model.y);
}
}
Element.extend = helpers.inherits;
-
-module.exports = Element;
+export default Element; | true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/core/core.helpers.js | @@ -1,571 +0,0 @@
-'use strict';
-
-var color = require('chartjs-color');
-var defaults = require('./core.defaults');
-var helpers = require('../helpers/index');
-
-module.exports = function() {
-
- // -- Basic js utility methods
-
- helpers.where = function(collection, filterCallback) {
- if (helpers.isArray(collection) && Array.prototype.filter) {
- return collection.filter(filterCallback);
- }
- var filtered = [];
-
- helpers.each(collection, function(item) {
- if (filterCallback(item)) {
- filtered.push(item);
- }
- });
-
- return filtered;
- };
- helpers.findIndex = Array.prototype.findIndex ?
- function(array, callback, scope) {
- return array.findIndex(callback, scope);
- } :
- function(array, callback, scope) {
- scope = scope === undefined ? array : scope;
- for (var i = 0, ilen = array.length; i < ilen; ++i) {
- if (callback.call(scope, array[i], i, array)) {
- return i;
- }
- }
- return -1;
- };
- helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
- // Default to start of the array
- if (helpers.isNullOrUndef(startIndex)) {
- startIndex = -1;
- }
- for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
- var currentItem = arrayToSearch[i];
- if (filterCallback(currentItem)) {
- return currentItem;
- }
- }
- };
- helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
- // Default to end of the array
- if (helpers.isNullOrUndef(startIndex)) {
- startIndex = arrayToSearch.length;
- }
- for (var i = startIndex - 1; i >= 0; i--) {
- var currentItem = arrayToSearch[i];
- if (filterCallback(currentItem)) {
- return currentItem;
- }
- }
- };
-
- // -- Math methods
- helpers.isNumber = function(n) {
- return !isNaN(parseFloat(n)) && isFinite(n);
- };
- helpers.almostEquals = function(x, y, epsilon) {
- return Math.abs(x - y) < epsilon;
- };
- helpers.almostWhole = function(x, epsilon) {
- var rounded = Math.round(x);
- return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
- };
- helpers._setMinAndMax = function(array, target) {
- var i, ilen, value;
-
- for (i = 0, ilen = array.length; i < ilen; i++) {
- value = array[i];
- if (!isNaN(value)) {
- target.min = Math.min(target.min, value);
- target.max = Math.max(target.max, value);
- }
- }
- };
- helpers._setMinAndMaxByKey = function(array, target, property) {
- var i, ilen, value;
-
- for (i = 0, ilen = array.length; i < ilen; i++) {
- value = array[i][property];
- if (!isNaN(value)) {
- target.min = Math.min(target.min, value);
- target.max = Math.max(target.max, value);
- }
- }
- };
- helpers.sign = Math.sign ?
- function(x) {
- return Math.sign(x);
- } :
- function(x) {
- x = +x; // convert to a number
- if (x === 0 || isNaN(x)) {
- return x;
- }
- return x > 0 ? 1 : -1;
- };
- helpers.toRadians = function(degrees) {
- return degrees * (Math.PI / 180);
- };
- helpers.toDegrees = function(radians) {
- return radians * (180 / Math.PI);
- };
-
- /**
- * Returns the number of decimal places
- * i.e. the number of digits after the decimal point, of the value of this Number.
- * @param {number} x - A number.
- * @returns {number} The number of decimal places.
- * @private
- */
- helpers._decimalPlaces = function(x) {
- if (!helpers.isFinite(x)) {
- return;
- }
- var e = 1;
- var p = 0;
- while (Math.round(x * e) / e !== x) {
- e *= 10;
- p++;
- }
- return p;
- };
-
- // Gets the angle from vertical upright to the point about a centre.
- helpers.getAngleFromPoint = function(centrePoint, anglePoint) {
- var distanceFromXCenter = anglePoint.x - centrePoint.x;
- var distanceFromYCenter = anglePoint.y - centrePoint.y;
- var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
-
- var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
-
- if (angle < (-0.5 * Math.PI)) {
- angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
- }
-
- return {
- angle: angle,
- distance: radialDistanceFromCenter
- };
- };
- helpers.distanceBetweenPoints = function(pt1, pt2) {
- return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
- };
-
- helpers.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
- // Props to Rob Spencer at scaled innovation for his post on splining between points
- // http://scaledinnovation.com/analytics/splines/aboutSplines.html
-
- // This function must also respect "skipped" points
-
- var previous = firstPoint.skip ? middlePoint : firstPoint;
- var current = middlePoint;
- var next = afterPoint.skip ? middlePoint : afterPoint;
-
- var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
- var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
-
- var s01 = d01 / (d01 + d12);
- var s12 = d12 / (d01 + d12);
-
- // If all points are the same, s01 & s02 will be inf
- s01 = isNaN(s01) ? 0 : s01;
- s12 = isNaN(s12) ? 0 : s12;
-
- var fa = t * s01; // scaling factor for triangle Ta
- var fb = t * s12;
-
- return {
- previous: {
- x: current.x - fa * (next.x - previous.x),
- y: current.y - fa * (next.y - previous.y)
- },
- next: {
- x: current.x + fb * (next.x - previous.x),
- y: current.y + fb * (next.y - previous.y)
- }
- };
- };
- helpers.EPSILON = Number.EPSILON || 1e-14;
- helpers.splineCurveMonotone = function(points) {
- // This function calculates Bézier control points in a similar way than |splineCurve|,
- // but preserves monotonicity of the provided data and ensures no local extremums are added
- // between the dataset discrete points due to the interpolation.
- // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
-
- var pointsWithTangents = (points || []).map(function(point) {
- return {
- model: point._model,
- deltaK: 0,
- mK: 0
- };
- });
-
- // Calculate slopes (deltaK) and initialize tangents (mK)
- var pointsLen = pointsWithTangents.length;
- var i, pointBefore, pointCurrent, pointAfter;
- for (i = 0; i < pointsLen; ++i) {
- pointCurrent = pointsWithTangents[i];
- if (pointCurrent.model.skip) {
- continue;
- }
-
- pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
- pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
- if (pointAfter && !pointAfter.model.skip) {
- var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
-
- // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
- pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
- }
-
- if (!pointBefore || pointBefore.model.skip) {
- pointCurrent.mK = pointCurrent.deltaK;
- } else if (!pointAfter || pointAfter.model.skip) {
- pointCurrent.mK = pointBefore.deltaK;
- } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
- pointCurrent.mK = 0;
- } else {
- pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
- }
- }
-
- // Adjust tangents to ensure monotonic properties
- var alphaK, betaK, tauK, squaredMagnitude;
- for (i = 0; i < pointsLen - 1; ++i) {
- pointCurrent = pointsWithTangents[i];
- pointAfter = pointsWithTangents[i + 1];
- if (pointCurrent.model.skip || pointAfter.model.skip) {
- continue;
- }
-
- if (helpers.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
- pointCurrent.mK = pointAfter.mK = 0;
- continue;
- }
-
- alphaK = pointCurrent.mK / pointCurrent.deltaK;
- betaK = pointAfter.mK / pointCurrent.deltaK;
- squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
- if (squaredMagnitude <= 9) {
- continue;
- }
-
- tauK = 3 / Math.sqrt(squaredMagnitude);
- pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
- pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
- }
-
- // Compute control points
- var deltaX;
- for (i = 0; i < pointsLen; ++i) {
- pointCurrent = pointsWithTangents[i];
- if (pointCurrent.model.skip) {
- continue;
- }
-
- pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
- pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
- if (pointBefore && !pointBefore.model.skip) {
- deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
- pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
- pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
- }
- if (pointAfter && !pointAfter.model.skip) {
- deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
- pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
- pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
- }
- }
- };
- // Implementation of the nice number algorithm used in determining where axis labels will go
- helpers.niceNum = function(range, round) {
- var exponent = Math.floor(helpers.math.log10(range));
- var fraction = range / Math.pow(10, exponent);
- var niceFraction;
-
- if (round) {
- if (fraction < 1.5) {
- niceFraction = 1;
- } else if (fraction < 3) {
- niceFraction = 2;
- } else if (fraction < 7) {
- niceFraction = 5;
- } else {
- niceFraction = 10;
- }
- } else if (fraction <= 1.0) {
- niceFraction = 1;
- } else if (fraction <= 2) {
- niceFraction = 2;
- } else if (fraction <= 5) {
- niceFraction = 5;
- } else {
- niceFraction = 10;
- }
-
- return niceFraction * Math.pow(10, exponent);
- };
- // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
- helpers.requestAnimFrame = (function() {
- if (typeof window === 'undefined') {
- return function(callback) {
- callback();
- };
- }
- return window.requestAnimationFrame ||
- window.webkitRequestAnimationFrame ||
- window.mozRequestAnimationFrame ||
- window.oRequestAnimationFrame ||
- window.msRequestAnimationFrame ||
- function(callback) {
- return window.setTimeout(callback, 1000 / 60);
- };
- }());
- // -- DOM methods
- helpers.getRelativePosition = function(evt, chart) {
- var mouseX, mouseY;
- var e = evt.originalEvent || evt;
- var canvas = evt.target || evt.srcElement;
- var boundingRect = canvas.getBoundingClientRect();
-
- var touches = e.touches;
- if (touches && touches.length > 0) {
- mouseX = touches[0].clientX;
- mouseY = touches[0].clientY;
-
- } else {
- mouseX = e.clientX;
- mouseY = e.clientY;
- }
-
- // Scale mouse coordinates into canvas coordinates
- // by following the pattern laid out by 'jerryj' in the comments of
- // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
- var paddingLeft = parseFloat(helpers.getStyle(canvas, 'padding-left'));
- var paddingTop = parseFloat(helpers.getStyle(canvas, 'padding-top'));
- var paddingRight = parseFloat(helpers.getStyle(canvas, 'padding-right'));
- var paddingBottom = parseFloat(helpers.getStyle(canvas, 'padding-bottom'));
- var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
- var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
-
- // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
- // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
- mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
- mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
-
- return {
- x: mouseX,
- y: mouseY
- };
-
- };
-
- // Private helper function to convert max-width/max-height values that may be percentages into a number
- function parseMaxStyle(styleValue, node, parentProperty) {
- var valueInPixels;
- if (typeof styleValue === 'string') {
- valueInPixels = parseInt(styleValue, 10);
-
- if (styleValue.indexOf('%') !== -1) {
- // percentage * size in dimension
- valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
- }
- } else {
- valueInPixels = styleValue;
- }
-
- return valueInPixels;
- }
-
- /**
- * Returns if the given value contains an effective constraint.
- * @private
- */
- function isConstrainedValue(value) {
- return value !== undefined && value !== null && value !== 'none';
- }
-
- /**
- * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
- * @param {HTMLElement} domNode - the node to check the constraint on
- * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
- * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
- * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
- */
- function getConstraintDimension(domNode, maxStyle, percentageProperty) {
- var view = document.defaultView;
- var parentNode = helpers._getParentNode(domNode);
- var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
- var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
- var hasCNode = isConstrainedValue(constrainedNode);
- var hasCContainer = isConstrainedValue(constrainedContainer);
- var infinity = Number.POSITIVE_INFINITY;
-
- if (hasCNode || hasCContainer) {
- return Math.min(
- hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
- hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
- }
-
- return 'none';
- }
- // returns Number or undefined if no constraint
- helpers.getConstraintWidth = function(domNode) {
- return getConstraintDimension(domNode, 'max-width', 'clientWidth');
- };
- // returns Number or undefined if no constraint
- helpers.getConstraintHeight = function(domNode) {
- return getConstraintDimension(domNode, 'max-height', 'clientHeight');
- };
- /**
- * @private
- */
- helpers._calculatePadding = function(container, padding, parentDimension) {
- padding = helpers.getStyle(container, padding);
-
- return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
- };
- /**
- * @private
- */
- helpers._getParentNode = function(domNode) {
- var parent = domNode.parentNode;
- if (parent && parent.toString() === '[object ShadowRoot]') {
- parent = parent.host;
- }
- return parent;
- };
- helpers.getMaximumWidth = function(domNode) {
- var container = helpers._getParentNode(domNode);
- if (!container) {
- return domNode.clientWidth;
- }
-
- var clientWidth = container.clientWidth;
- var paddingLeft = helpers._calculatePadding(container, 'padding-left', clientWidth);
- var paddingRight = helpers._calculatePadding(container, 'padding-right', clientWidth);
-
- var w = clientWidth - paddingLeft - paddingRight;
- var cw = helpers.getConstraintWidth(domNode);
- return isNaN(cw) ? w : Math.min(w, cw);
- };
- helpers.getMaximumHeight = function(domNode) {
- var container = helpers._getParentNode(domNode);
- if (!container) {
- return domNode.clientHeight;
- }
-
- var clientHeight = container.clientHeight;
- var paddingTop = helpers._calculatePadding(container, 'padding-top', clientHeight);
- var paddingBottom = helpers._calculatePadding(container, 'padding-bottom', clientHeight);
-
- var h = clientHeight - paddingTop - paddingBottom;
- var ch = helpers.getConstraintHeight(domNode);
- return isNaN(ch) ? h : Math.min(h, ch);
- };
- helpers.getStyle = function(el, property) {
- return el.currentStyle ?
- el.currentStyle[property] :
- document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
- };
- helpers.retinaScale = function(chart, forceRatio) {
- var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
- if (pixelRatio === 1) {
- return;
- }
-
- var canvas = chart.canvas;
- var height = chart.height;
- var width = chart.width;
-
- canvas.height = height * pixelRatio;
- canvas.width = width * pixelRatio;
- chart.ctx.scale(pixelRatio, pixelRatio);
-
- // If no style has been set on the canvas, the render size is used as display size,
- // making the chart visually bigger, so let's enforce it to the "correct" values.
- // See https://github.com/chartjs/Chart.js/issues/3575
- if (!canvas.style.height && !canvas.style.width) {
- canvas.style.height = height + 'px';
- canvas.style.width = width + 'px';
- }
- };
- // -- Canvas methods
- helpers.fontString = function(pixelSize, fontStyle, fontFamily) {
- return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
- };
- helpers.longestText = function(ctx, font, arrayOfThings, cache) {
- cache = cache || {};
- var data = cache.data = cache.data || {};
- var gc = cache.garbageCollect = cache.garbageCollect || [];
-
- if (cache.font !== font) {
- data = cache.data = {};
- gc = cache.garbageCollect = [];
- cache.font = font;
- }
-
- ctx.font = font;
- var longest = 0;
- var ilen = arrayOfThings.length;
- var i, j, jlen, thing, nestedThing;
- for (i = 0; i < ilen; i++) {
- thing = arrayOfThings[i];
-
- // Undefined strings and arrays should not be measured
- if (thing !== undefined && thing !== null && helpers.isArray(thing) !== true) {
- longest = helpers.measureText(ctx, data, gc, longest, thing);
- } else if (helpers.isArray(thing)) {
- // if it is an array lets measure each element
- // to do maybe simplify this function a bit so we can do this more recursively?
- for (j = 0, jlen = thing.length; j < jlen; j++) {
- nestedThing = thing[j];
- // Undefined strings and arrays should not be measured
- if (nestedThing !== undefined && nestedThing !== null && !helpers.isArray(nestedThing)) {
- longest = helpers.measureText(ctx, data, gc, longest, nestedThing);
- }
- }
- }
- }
-
- var gcLen = gc.length / 2;
- if (gcLen > arrayOfThings.length) {
- for (i = 0; i < gcLen; i++) {
- delete data[gc[i]];
- }
- gc.splice(0, gcLen);
- }
- return longest;
- };
- helpers.measureText = function(ctx, data, gc, longest, string) {
- var textWidth = data[string];
- if (!textWidth) {
- textWidth = data[string] = ctx.measureText(string).width;
- gc.push(string);
- }
- if (textWidth > longest) {
- longest = textWidth;
- }
- return longest;
- };
-
- helpers.color = !color ?
- function(value) {
- console.error('Color.js not found!');
- return value;
- } :
- function(value) {
- if (value instanceof CanvasGradient) {
- value = defaults.global.defaultColor;
- }
-
- return color(value);
- };
-
- helpers.getHoverColor = function(colorValue) {
- return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
- colorValue :
- helpers.color(colorValue).saturate(0.5).darken(0.1).rgbString();
- };
-}; | true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/core/core.interaction.js | @@ -1,6 +1,7 @@
'use strict';
-var helpers = require('../helpers/index');
+import helpers from '../helpers/index';
+import {isNumber} from '../helpers/helpers.math';
/**
* Helper function to get relative position for an event
@@ -16,7 +17,7 @@ function getRelativePosition(e, chart) {
};
}
- return helpers.getRelativePosition(e, chart);
+ return helpers.dom.getRelativePosition(e, chart);
}
/**
@@ -55,7 +56,7 @@ function evaluateItemsAtIndex(chart, axis, position, handler) {
return false;
}
const index = iScale.getIndexForPixel(position[axis]);
- if (!helpers.isNumber(index)) {
+ if (!isNumber(index)) {
return false;
}
indices.push(index);
@@ -163,7 +164,7 @@ function getNearestItems(chart, position, axis, intersect) {
* Contains interaction related functions
* @namespace Chart.Interaction
*/
-module.exports = {
+export default {
// Helper function for different modes
modes: {
/** | true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/core/core.scale.js | @@ -636,7 +636,7 @@ class Scale extends Element {
maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)
- tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
- labelRotation = helpers.toDegrees(Math.min(
+ labelRotation = helpers.math.toDegrees(Math.min(
Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
));
@@ -699,7 +699,7 @@ class Scale extends Element {
if (isHorizontal) {
// A horizontal axis is more constrained by the height.
var isRotated = me.labelRotation !== 0;
- var angleRadians = helpers.toRadians(me.labelRotation);
+ var angleRadians = helpers.math.toRadians(me.labelRotation);
var cosRotation = Math.cos(angleRadians);
var sinRotation = Math.sin(angleRadians);
@@ -931,7 +931,7 @@ class Scale extends Element {
var optionTicks = me.options.ticks;
// Calculate space needed by label in axis direction.
- var rot = helpers.toRadians(me.labelRotation);
+ var rot = helpers.math.toRadians(me.labelRotation);
var cos = Math.abs(Math.cos(rot));
var sin = Math.abs(Math.sin(rot));
@@ -1103,7 +1103,7 @@ class Scale extends Element {
const fonts = parseTickFontOptions(optionTicks);
const tickPadding = optionTicks.padding;
const tl = getTickMarkLength(options.gridLines);
- const rotation = -helpers.toRadians(me.labelRotation);
+ const rotation = -helpers.math.toRadians(me.labelRotation);
const items = [];
let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
| true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/elements/element.arc.js | @@ -2,7 +2,7 @@
import defaults from '../core/core.defaults';
import Element from '../core/core.element';
-import helpers from '../helpers';
+import {getAngleFromPoint} from '../helpers/helpers.math';
const TAU = Math.PI * 2;
defaults._set('global', {
@@ -101,7 +101,7 @@ class Arc extends Element {
var vm = this._view;
if (vm) {
- var pointRelativePosition = helpers.getAngleFromPoint(vm, {x: chartX, y: chartY});
+ var pointRelativePosition = getAngleFromPoint(vm, {x: chartX, y: chartY});
var angle = pointRelativePosition.angle;
var distance = pointRelativePosition.distance;
| true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/helpers/helpers.curve.js | @@ -0,0 +1,130 @@
+import {almostEquals, sign} from './helpers.math';
+
+const EPSILON = Number.EPSILON || 1e-14;
+
+export function splineCurve(firstPoint, middlePoint, afterPoint, t) {
+ // Props to Rob Spencer at scaled innovation for his post on splining between points
+ // http://scaledinnovation.com/analytics/splines/aboutSplines.html
+
+ // This function must also respect "skipped" points
+
+ var previous = firstPoint.skip ? middlePoint : firstPoint;
+ var current = middlePoint;
+ var next = afterPoint.skip ? middlePoint : afterPoint;
+
+ var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
+ var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
+
+ var s01 = d01 / (d01 + d12);
+ var s12 = d12 / (d01 + d12);
+
+ // If all points are the same, s01 & s02 will be inf
+ s01 = isNaN(s01) ? 0 : s01;
+ s12 = isNaN(s12) ? 0 : s12;
+
+ var fa = t * s01; // scaling factor for triangle Ta
+ var fb = t * s12;
+
+ return {
+ previous: {
+ x: current.x - fa * (next.x - previous.x),
+ y: current.y - fa * (next.y - previous.y)
+ },
+ next: {
+ x: current.x + fb * (next.x - previous.x),
+ y: current.y + fb * (next.y - previous.y)
+ }
+ };
+}
+
+export function splineCurveMonotone(points) {
+ // This function calculates Bézier control points in a similar way than |splineCurve|,
+ // but preserves monotonicity of the provided data and ensures no local extremums are added
+ // between the dataset discrete points due to the interpolation.
+ // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
+
+ var pointsWithTangents = (points || []).map(function(point) {
+ return {
+ model: point._model,
+ deltaK: 0,
+ mK: 0
+ };
+ });
+
+ // Calculate slopes (deltaK) and initialize tangents (mK)
+ var pointsLen = pointsWithTangents.length;
+ var i, pointBefore, pointCurrent, pointAfter;
+ for (i = 0; i < pointsLen; ++i) {
+ pointCurrent = pointsWithTangents[i];
+ if (pointCurrent.model.skip) {
+ continue;
+ }
+
+ pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
+ pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
+ if (pointAfter && !pointAfter.model.skip) {
+ var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
+
+ // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
+ pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
+ }
+
+ if (!pointBefore || pointBefore.model.skip) {
+ pointCurrent.mK = pointCurrent.deltaK;
+ } else if (!pointAfter || pointAfter.model.skip) {
+ pointCurrent.mK = pointBefore.deltaK;
+ } else if (sign(pointBefore.deltaK) !== sign(pointCurrent.deltaK)) {
+ pointCurrent.mK = 0;
+ } else {
+ pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
+ }
+ }
+
+ // Adjust tangents to ensure monotonic properties
+ var alphaK, betaK, tauK, squaredMagnitude;
+ for (i = 0; i < pointsLen - 1; ++i) {
+ pointCurrent = pointsWithTangents[i];
+ pointAfter = pointsWithTangents[i + 1];
+ if (pointCurrent.model.skip || pointAfter.model.skip) {
+ continue;
+ }
+
+ if (almostEquals(pointCurrent.deltaK, 0, EPSILON)) {
+ pointCurrent.mK = pointAfter.mK = 0;
+ continue;
+ }
+
+ alphaK = pointCurrent.mK / pointCurrent.deltaK;
+ betaK = pointAfter.mK / pointCurrent.deltaK;
+ squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
+ if (squaredMagnitude <= 9) {
+ continue;
+ }
+
+ tauK = 3 / Math.sqrt(squaredMagnitude);
+ pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
+ pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
+ }
+
+ // Compute control points
+ var deltaX;
+ for (i = 0; i < pointsLen; ++i) {
+ pointCurrent = pointsWithTangents[i];
+ if (pointCurrent.model.skip) {
+ continue;
+ }
+
+ pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
+ pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
+ if (pointBefore && !pointBefore.model.skip) {
+ deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
+ pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
+ pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
+ }
+ if (pointAfter && !pointAfter.model.skip) {
+ deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
+ pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
+ pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
+ }
+ }
+} | true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/helpers/helpers.dom.js | @@ -0,0 +1,175 @@
+/**
+ * Returns if the given value contains an effective constraint.
+ * @private
+ */
+function isConstrainedValue(value) {
+ return value !== undefined && value !== null && value !== 'none';
+}
+
+/**
+ * @private
+ */
+function _getParentNode(domNode) {
+ var parent = domNode.parentNode;
+ if (parent && parent.toString() === '[object ShadowRoot]') {
+ parent = parent.host;
+ }
+ return parent;
+}
+
+// Private helper function to convert max-width/max-height values that may be percentages into a number
+function parseMaxStyle(styleValue, node, parentProperty) {
+ var valueInPixels;
+ if (typeof styleValue === 'string') {
+ valueInPixels = parseInt(styleValue, 10);
+
+ if (styleValue.indexOf('%') !== -1) {
+ // percentage * size in dimension
+ valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
+ }
+ } else {
+ valueInPixels = styleValue;
+ }
+
+ return valueInPixels;
+}
+
+/**
+ * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
+ * @param {HTMLElement} domNode - the node to check the constraint on
+ * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
+ * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
+ * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
+ */
+function getConstraintDimension(domNode, maxStyle, percentageProperty) {
+ var view = document.defaultView;
+ var parentNode = _getParentNode(domNode);
+ var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
+ var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
+ var hasCNode = isConstrainedValue(constrainedNode);
+ var hasCContainer = isConstrainedValue(constrainedContainer);
+ var infinity = Number.POSITIVE_INFINITY;
+
+ if (hasCNode || hasCContainer) {
+ return Math.min(
+ hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
+ hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
+ }
+
+ return 'none';
+}
+
+export function getStyle(el, property) {
+ return el.currentStyle ?
+ el.currentStyle[property] :
+ document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
+}
+
+// returns Number or undefined if no constraint
+function getConstraintWidth(domNode) {
+ return getConstraintDimension(domNode, 'max-width', 'clientWidth');
+}
+
+// returns Number or undefined if no constraint
+function getConstraintHeight(domNode) {
+ return getConstraintDimension(domNode, 'max-height', 'clientHeight');
+}
+
+/**
+ * @private
+ */
+function _calculatePadding(container, padding, parentDimension) {
+ padding = getStyle(container, padding);
+
+ return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
+}
+
+export function getRelativePosition(evt, chart) {
+ var mouseX, mouseY;
+ var e = evt.originalEvent || evt;
+ var canvasElement = evt.target || evt.srcElement;
+ var boundingRect = canvasElement.getBoundingClientRect();
+
+ var touches = e.touches;
+ if (touches && touches.length > 0) {
+ mouseX = touches[0].clientX;
+ mouseY = touches[0].clientY;
+
+ } else {
+ mouseX = e.clientX;
+ mouseY = e.clientY;
+ }
+
+ // Scale mouse coordinates into canvas coordinates
+ // by following the pattern laid out by 'jerryj' in the comments of
+ // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
+ var paddingLeft = parseFloat(getStyle(canvasElement, 'padding-left'));
+ var paddingTop = parseFloat(getStyle(canvasElement, 'padding-top'));
+ var paddingRight = parseFloat(getStyle(canvasElement, 'padding-right'));
+ var paddingBottom = parseFloat(getStyle(canvasElement, 'padding-bottom'));
+ var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
+ var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
+
+ // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
+ // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
+ mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvasElement.width / chart.currentDevicePixelRatio);
+ mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvasElement.height / chart.currentDevicePixelRatio);
+
+ return {
+ x: mouseX,
+ y: mouseY
+ };
+}
+
+export function getMaximumWidth(domNode) {
+ var container = _getParentNode(domNode);
+ if (!container) {
+ return domNode.clientWidth;
+ }
+
+ var clientWidth = container.clientWidth;
+ var paddingLeft = _calculatePadding(container, 'padding-left', clientWidth);
+ var paddingRight = _calculatePadding(container, 'padding-right', clientWidth);
+
+ var w = clientWidth - paddingLeft - paddingRight;
+ var cw = getConstraintWidth(domNode);
+ return isNaN(cw) ? w : Math.min(w, cw);
+}
+
+export function getMaximumHeight(domNode) {
+ var container = _getParentNode(domNode);
+ if (!container) {
+ return domNode.clientHeight;
+ }
+
+ var clientHeight = container.clientHeight;
+ var paddingTop = _calculatePadding(container, 'padding-top', clientHeight);
+ var paddingBottom = _calculatePadding(container, 'padding-bottom', clientHeight);
+
+ var h = clientHeight - paddingTop - paddingBottom;
+ var ch = getConstraintHeight(domNode);
+ return isNaN(ch) ? h : Math.min(h, ch);
+}
+
+export function retinaScale(chart, forceRatio) {
+ var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
+ if (pixelRatio === 1) {
+ return;
+ }
+
+ var canvasElement = chart.canvas;
+ var height = chart.height;
+ var width = chart.width;
+
+ canvasElement.height = height * pixelRatio;
+ canvasElement.width = width * pixelRatio;
+ chart.ctx.scale(pixelRatio, pixelRatio);
+
+ // If no style has been set on the canvas, the render size is used as display size,
+ // making the chart visually bigger, so let's enforce it to the "correct" values.
+ // See https://github.com/chartjs/Chart.js/issues/3575
+ if (!canvasElement.style.height && !canvasElement.style.width) {
+ canvasElement.style.height = height + 'px';
+ canvasElement.style.width = width + 'px';
+ }
+} | true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/helpers/helpers.math.js | @@ -1,5 +1,7 @@
'use strict';
+import {isFinite as isFiniteNumber} from './helpers.core';
+
/**
* @alias Chart.helpers.math
* @namespace
@@ -38,3 +40,103 @@ export const log10 = Math.log10 || function(x) {
return isPowerOf10 ? powerOf10 : exponent;
};
+
+
+export function isNumber(n) {
+ return !isNaN(parseFloat(n)) && isFinite(n);
+}
+
+export function almostEquals(x, y, epsilon) {
+ return Math.abs(x - y) < epsilon;
+}
+
+export function almostWhole(x, epsilon) {
+ var rounded = Math.round(x);
+ return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
+}
+
+export function _setMinAndMax(array, target) {
+ var i, ilen, value;
+
+ for (i = 0, ilen = array.length; i < ilen; i++) {
+ value = array[i];
+ if (!isNaN(value)) {
+ target.min = Math.min(target.min, value);
+ target.max = Math.max(target.max, value);
+ }
+ }
+}
+
+export function _setMinAndMaxByKey(array, target, property) {
+ var i, ilen, value;
+
+ for (i = 0, ilen = array.length; i < ilen; i++) {
+ value = array[i][property];
+ if (!isNaN(value)) {
+ target.min = Math.min(target.min, value);
+ target.max = Math.max(target.max, value);
+ }
+ }
+}
+
+export const sign = Math.sign ?
+ function(x) {
+ return Math.sign(x);
+ } :
+ function(x) {
+ x = +x; // convert to a number
+ if (x === 0 || isNaN(x)) {
+ return x;
+ }
+ return x > 0 ? 1 : -1;
+ };
+
+export function toRadians(degrees) {
+ return degrees * (Math.PI / 180);
+}
+
+export function toDegrees(radians) {
+ return radians * (180 / Math.PI);
+}
+
+/**
+ * Returns the number of decimal places
+ * i.e. the number of digits after the decimal point, of the value of this Number.
+ * @param {number} x - A number.
+ * @returns {number} The number of decimal places.
+ * @private
+ */
+export function _decimalPlaces(x) {
+ if (!isFiniteNumber(x)) {
+ return;
+ }
+ var e = 1;
+ var p = 0;
+ while (Math.round(x * e) / e !== x) {
+ e *= 10;
+ p++;
+ }
+ return p;
+}
+
+// Gets the angle from vertical upright to the point about a centre.
+export function getAngleFromPoint(centrePoint, anglePoint) {
+ var distanceFromXCenter = anglePoint.x - centrePoint.x;
+ var distanceFromYCenter = anglePoint.y - centrePoint.y;
+ var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
+
+ var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
+
+ if (angle < (-0.5 * Math.PI)) {
+ angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
+ }
+
+ return {
+ angle: angle,
+ distance: radialDistanceFromCenter
+ };
+}
+
+export function distanceBetweenPoints(pt1, pt2) {
+ return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
+} | true |
Other | chartjs | Chart.js | c8bdca62e89b4d6d9f334cec7a8bfa673725014c.json | Move all helpers to src/helpers (#6841)
* Move all helpers into src/helpers
* Move curve helpers to their own file
* DOM helpers moved to their own file
* Update migration docs
* Remove migration docs on new functions | src/helpers/index.js | @@ -1,17 +1,200 @@
'use strict';
+import color from 'chartjs-color';
+
import * as coreHelpers from './helpers.core';
import * as canvas from './helpers.canvas';
+import * as curve from './helpers.curve';
+import * as dom from './helpers.dom';
import * as easing from './helpers.easing';
import * as options from './helpers.options';
import * as math from './helpers.math';
import * as rtl from './helpers.rtl';
+const colorHelper = !color ?
+ function(value) {
+ console.error('Color.js not found!');
+ return value;
+ } :
+ function(value) {
+ if (value instanceof CanvasGradient || value instanceof CanvasPattern) {
+ // TODO: figure out what this should be. Previously returned
+ // the default color
+ return value;
+ }
+
+ return color(value);
+ };
+
+function measureText(ctx, data, gc, longest, string) {
+ var textWidth = data[string];
+ if (!textWidth) {
+ textWidth = data[string] = ctx.measureText(string).width;
+ gc.push(string);
+ }
+ if (textWidth > longest) {
+ longest = textWidth;
+ }
+ return longest;
+}
+
export default {
...coreHelpers,
canvas,
+ curve,
+ dom,
easing,
options,
math,
rtl,
+
+ where: function(collection, filterCallback) {
+ if (coreHelpers.isArray(collection) && Array.prototype.filter) {
+ return collection.filter(filterCallback);
+ }
+ var filtered = [];
+
+ coreHelpers.each(collection, function(item) {
+ if (filterCallback(item)) {
+ filtered.push(item);
+ }
+ });
+
+ return filtered;
+ },
+ findIndex: Array.prototype.findIndex ?
+ function(array, callback, scope) {
+ return array.findIndex(callback, scope);
+ } :
+ function(array, callback, scope) {
+ scope = scope === undefined ? array : scope;
+ for (var i = 0, ilen = array.length; i < ilen; ++i) {
+ if (callback.call(scope, array[i], i, array)) {
+ return i;
+ }
+ }
+ return -1;
+ },
+ findNextWhere: function(arrayToSearch, filterCallback, startIndex) {
+ // Default to start of the array
+ if (coreHelpers.isNullOrUndef(startIndex)) {
+ startIndex = -1;
+ }
+ for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
+ var currentItem = arrayToSearch[i];
+ if (filterCallback(currentItem)) {
+ return currentItem;
+ }
+ }
+ },
+ findPreviousWhere: function(arrayToSearch, filterCallback, startIndex) {
+ // Default to end of the array
+ if (coreHelpers.isNullOrUndef(startIndex)) {
+ startIndex = arrayToSearch.length;
+ }
+ for (var i = startIndex - 1; i >= 0; i--) {
+ var currentItem = arrayToSearch[i];
+ if (filterCallback(currentItem)) {
+ return currentItem;
+ }
+ }
+ },
+ // Implementation of the nice number algorithm used in determining where axis labels will go
+ niceNum: function(range, round) {
+ var exponent = Math.floor(math.log10(range));
+ var fraction = range / Math.pow(10, exponent);
+ var niceFraction;
+
+ if (round) {
+ if (fraction < 1.5) {
+ niceFraction = 1;
+ } else if (fraction < 3) {
+ niceFraction = 2;
+ } else if (fraction < 7) {
+ niceFraction = 5;
+ } else {
+ niceFraction = 10;
+ }
+ } else if (fraction <= 1.0) {
+ niceFraction = 1;
+ } else if (fraction <= 2) {
+ niceFraction = 2;
+ } else if (fraction <= 5) {
+ niceFraction = 5;
+ } else {
+ niceFraction = 10;
+ }
+
+ return niceFraction * Math.pow(10, exponent);
+ },
+ // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
+ requestAnimFrame: (function() {
+ if (typeof window === 'undefined') {
+ return function(callback) {
+ callback();
+ };
+ }
+ return window.requestAnimationFrame ||
+ window.webkitRequestAnimationFrame ||
+ window.mozRequestAnimationFrame ||
+ window.oRequestAnimationFrame ||
+ window.msRequestAnimationFrame ||
+ function(callback) {
+ return window.setTimeout(callback, 1000 / 60);
+ };
+ }()),
+ // -- Canvas methods
+ fontString: function(pixelSize, fontStyle, fontFamily) {
+ return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
+ },
+ longestText: function(ctx, font, arrayOfThings, cache) {
+ cache = cache || {};
+ var data = cache.data = cache.data || {};
+ var gc = cache.garbageCollect = cache.garbageCollect || [];
+
+ if (cache.font !== font) {
+ data = cache.data = {};
+ gc = cache.garbageCollect = [];
+ cache.font = font;
+ }
+
+ ctx.font = font;
+ var longest = 0;
+ var ilen = arrayOfThings.length;
+ var i, j, jlen, thing, nestedThing;
+ for (i = 0; i < ilen; i++) {
+ thing = arrayOfThings[i];
+
+ // Undefined strings and arrays should not be measured
+ if (thing !== undefined && thing !== null && coreHelpers.isArray(thing) !== true) {
+ longest = measureText(ctx, data, gc, longest, thing);
+ } else if (coreHelpers.isArray(thing)) {
+ // if it is an array lets measure each element
+ // to do maybe simplify this function a bit so we can do this more recursively?
+ for (j = 0, jlen = thing.length; j < jlen; j++) {
+ nestedThing = thing[j];
+ // Undefined strings and arrays should not be measured
+ if (nestedThing !== undefined && nestedThing !== null && !coreHelpers.isArray(nestedThing)) {
+ longest = measureText(ctx, data, gc, longest, nestedThing);
+ }
+ }
+ }
+ }
+
+ var gcLen = gc.length / 2;
+ if (gcLen > arrayOfThings.length) {
+ for (i = 0; i < gcLen; i++) {
+ delete data[gc[i]];
+ }
+ gc.splice(0, gcLen);
+ }
+ return longest;
+ },
+ measureText,
+ color: colorHelper,
+ getHoverColor: function(colorValue) {
+ return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
+ colorValue :
+ colorHelper(colorValue).saturate(0.5).darken(0.1).rgbString();
+ }
}; | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.