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 | b6c22d269a16097bc8c55d7cc01d37b7369391d4.json | Remove circular dependencies from helpers (#7898) | src/helpers/helpers.easing.js | @@ -1,4 +1,4 @@
-import {PI, TAU, HALF_PI} from './index';
+import {PI, TAU, HALF_PI} from './helpers.math';
/**
* Easing functions adapted from Robert Penner's easing equations. | true |
Other | chartjs | Chart.js | 64b45294861ca19c0713dec9f6854e71747571b0.json | Fix double env (#7892) | .github/workflows/npmpublish.yml | @@ -59,17 +59,15 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GH_AUTH_TOKEN }}
GH_AUTH_EMAIL: ${{ secrets.GH_AUTH_EMAIL }}
- env:
VERSION: ${{ github.event.release.tag_name }}
- name: Upload NPM package file
id: upload-npm-package-file
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ VERSION: ${{ github.event.release.tag_name }}
with:
upload_url: ${{ github.event.release.upload_url }}
asset_path: chart.js-$VERSION.tgz
asset_name: chart.js-$VERSION.tgz
asset_content_type: application/gzip
- env:
- VERSION: ${{ github.event.release.tag_name }} | false |
Other | chartjs | Chart.js | efa0ade501b774a71938437e78b429eb2b0a4d2a.json | Update workflow to use GitHub releaes (#7891) | .github/workflows/npmpublish.yml | @@ -32,44 +32,44 @@ jobs:
with:
node-version: 12
registry-url: https://registry.npmjs.org/
- # Since we created the release in the UI, we need to find it.
- # This step gets the release from the GITHUB_REF env var
- - name: Get release
- id: get_release
- uses: bruceadams/get-release@v1.2.2
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Setup and build
run: |
npm ci
npm install -g json
- json -I -f package.json -e "this.version=\"$GITHUB_REF\""
- json -I -f package-lock.json -e "this.version=\"$GITHUB_REF\""
+ json -I -f package.json -e "this.version=\"$VERSION\""
+ json -I -f package-lock.json -e "this.version=\"$VERSION\""
npm run build
- ./scripts/docs-config.sh "${GITHUB_REF:1}"
+ ./scripts/docs-config.sh "${VERSION:1}"
npm run docs
npm run typedoc
npm pack
+ env:
+ VERSION: ${{ github.event.release.tag_name }}
- name: Publish to NPM
run: ./scripts/publish.sh
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
- # On releases, GITHUB_REF is the tag name which is the version
+ VERSION: ${{ github.event.release.tag_name }}
+ # On releases, VERSION is the tag name which is the version
# However, it will include the leading "v", so we need to strip that
# first character off here since we want the docs folder to not have
# the "v" in it.
- name: Deploy Docs
- run: ./scripts/deploy-docs.sh "${GITHUB_REF:1}"
+ run: ./scripts/deploy-docs.sh "${VERSION:1}"
env:
GITHUB_TOKEN: ${{ secrets.GH_AUTH_TOKEN }}
GH_AUTH_EMAIL: ${{ secrets.GH_AUTH_EMAIL }}
+ env:
+ VERSION: ${{ github.event.release.tag_name }}
- name: Upload NPM package file
id: upload-npm-package-file
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
- upload_url: ${{ steps.get_release.outputs.upload_url }}
- asset_path: chart.js-$GITHUB_REF.tgz
- asset_name: chart.js-$GITHUB_REF.tgz
+ upload_url: ${{ github.event.release.upload_url }}
+ asset_path: chart.js-$VERSION.tgz
+ asset_name: chart.js-$VERSION.tgz
asset_content_type: application/gzip
+ env:
+ VERSION: ${{ github.event.release.tag_name }} | true |
Other | chartjs | Chart.js | efa0ade501b774a71938437e78b429eb2b0a4d2a.json | Update workflow to use GitHub releaes (#7891) | scripts/publish.sh | @@ -4,7 +4,7 @@ set -e
NPM_TAG="next"
-if [[ "$GITHUB_REF" =~ ^[^-]+$ ]]; then
+if [[ "$VERSION" =~ ^[^-]+$ ]]; then
echo "Release tag indicates a full release. Releasing as \"latest\"."
NPM_TAG="latest"
fi | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | docs/docs/axes/cartesian/index.mdx | @@ -49,8 +49,8 @@ The following options are common to all cartesian axes but do not apply to other
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
-| `alignment` | `string` | | `'center'` | The tick alignment along the axis. Can be `'start'`, `'center'`, or `'end'`.
-| `crossAlignment` | `string` | | `'near'` | The tick alignment perpendicular to the axis. Can be `'near'`, `'center'`, or `'far'`. See [Tick Alignment](#tick-alignment)
+| `align` | `string` | | `'center'` | The tick alignment along the axis. Can be `'start'`, `'center'`, or `'end'`.
+| `crossAlign` | `string` | | `'near'` | The tick alignment perpendicular to the axis. Can be `'near'`, `'center'`, or `'far'`. See [Tick Alignment](#tick-alignment)
| `sampleSize` | `number` | `ticks.length` | The number of ticks to examine when deciding how many labels will fit. Setting a smaller value will be faster, but may be less accurate when there is large variability in label length.
| `autoSkip` | `boolean` | `true` | If true, automatically calculates how many labels can be shown and hides labels accordingly. Labels will be rotated up to `maxRotation` before skipping any. Turn `autoSkip` off to show all labels no matter what.
| `autoSkipPadding` | `number` | `0` | Padding between the ticks on the horizontal axis when `autoSkip` is enabled.
@@ -62,7 +62,7 @@ The following options are common to all cartesian axes but do not apply to other
### Tick Alignment
-The alignment of ticks is primarily controlled using two settings on the tick configuration object: `alignment` and `crossAlignment`. The `alignment` setting configures how labels align with the tick mark along the axis direction (i.e. horizontal for a horizontal axis and vertical for a vertical axis). The `crossAlignment` setting configures how labels align with the tick mark in the perpendicular direction (i.e. vertical for a horizontal axis and horizontal for a vertical axis). In the example below, the `crossAlignment` setting is used to left align the labels on the Y axis.
+The alignment of ticks is primarily controlled using two settings on the tick configuration object: `align` and `crossAlign`. The `align` setting configures how labels align with the tick mark along the axis direction (i.e. horizontal for a horizontal axis and vertical for a vertical axis). The `crossAlign` setting configures how labels align with the tick mark in the perpendicular direction (i.e. vertical for a horizontal axis and horizontal for a vertical axis). In the example below, the `crossAlign` setting is used to left align the labels on the Y axis.
```jsx live
function exampleAlignment() {
@@ -105,7 +105,7 @@ function exampleAlignment() {
},
y: {
ticks: {
- crossAlignment: 'far',
+ crossAlign: 'far',
}
}
}
@@ -117,7 +117,7 @@ function exampleAlignment() {
}
```
-**Note:** the `crossAlignment` setting is not used the the tick rotation is not `0`, the axis position is `'center'` or the position is with respect to a data value.
+**Note:** the `crossAlign` setting is not used the the tick rotation is not `0`, the axis position is `'center'` or the position is with respect to a data value.
### Axis ID
| true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | samples/scales/label-text-alignment.html | @@ -87,13 +87,13 @@
x: {
display: true,
ticks: {
- alignment: xAlign,
+ align: xAlign,
}
},
y: {
display: true,
ticks: {
- alignment: yAlign
+ align: yAlign
}
}
}, | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | src/core/core.scale.js | @@ -62,8 +62,8 @@ defaults.set('scale', {
callback: Ticks.formatters.values,
minor: {},
major: {},
- alignment: 'center',
- crossAlignment: 'near',
+ align: 'center',
+ crossAlign: 'near',
}
});
@@ -763,10 +763,10 @@ export default class Scale extends Element {
paddingRight = labelsBelowTicks ?
sinRotation * (lastLabelSize.height - lastLabelSize.offset) :
cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset;
- } else if (tickOpts.alignment === 'start') {
+ } else if (tickOpts.align === 'start') {
paddingLeft = 0;
paddingRight = lastLabelSize.width;
- } else if (tickOpts.alignment === 'end') {
+ } else if (tickOpts.align === 'end') {
paddingLeft = firstLabelSize.width;
paddingRight = 0;
} else {
@@ -791,10 +791,10 @@ export default class Scale extends Element {
let paddingTop = lastLabelSize.height / 2;
let paddingBottom = firstLabelSize.height / 2;
- if (tickOpts.alignment === 'start') {
+ if (tickOpts.align === 'start') {
paddingTop = 0;
paddingBottom = firstLabelSize.height;
- } else if (tickOpts.alignment === 'end') {
+ } else if (tickOpts.align === 'end') {
paddingTop = lastLabelSize.height;
paddingBottom = 0;
}
@@ -1253,7 +1253,7 @@ export default class Scale extends Element {
const {position, ticks: optionTicks} = options;
const isHorizontal = me.isHorizontal();
const ticks = me.ticks;
- const {alignment, crossAlignment, padding} = optionTicks;
+ const {align, crossAlign, padding} = optionTicks;
const tl = getTickMarkLength(options.gridLines);
const tickAndPadding = tl + padding;
const rotation = -toRadians(me.labelRotation);
@@ -1296,9 +1296,9 @@ export default class Scale extends Element {
}
if (axis === 'y') {
- if (alignment === 'start') {
+ if (align === 'start') {
textBaseline = 'top';
- } else if (alignment === 'end') {
+ } else if (align === 'end') {
textBaseline = 'bottom';
}
}
@@ -1317,20 +1317,20 @@ export default class Scale extends Element {
if (isHorizontal) {
x = pixel;
if (position === 'top') {
- if (crossAlignment === 'near' || rotation !== 0) {
+ if (crossAlign === 'near' || rotation !== 0) {
textOffset = (Math.sin(rotation) * halfCount + 0.5) * lineHeight;
textOffset -= (rotation === 0 ? (lineCount - 0.5) : Math.cos(rotation) * halfCount) * lineHeight;
- } else if (crossAlignment === 'center') {
+ } else if (crossAlign === 'center') {
textOffset = -1 * (labelSizes.highest.height / 2);
textOffset -= halfCount * lineHeight;
} else {
textOffset = (-1 * labelSizes.highest.height) + (0.5 * lineHeight);
}
} else if (position === 'bottom') {
- if (crossAlignment === 'near' || rotation !== 0) {
+ if (crossAlign === 'near' || rotation !== 0) {
textOffset = Math.sin(rotation) * halfCount * lineHeight;
textOffset += (rotation === 0 ? 0.5 : Math.cos(rotation) * halfCount) * lineHeight;
- } else if (crossAlignment === 'center') {
+ } else if (crossAlign === 'center') {
textOffset = labelSizes.highest.height / 2;
textOffset -= halfCount * lineHeight;
} else {
@@ -1368,9 +1368,9 @@ export default class Scale extends Element {
let align = 'center';
- if (ticks.alignment === 'start') {
+ if (ticks.align === 'start') {
align = 'left';
- } else if (ticks.alignment === 'end') {
+ } else if (ticks.align === 'end') {
align = 'right';
}
@@ -1380,7 +1380,7 @@ export default class Scale extends Element {
_getYAxisLabelAlignment(tl) {
const me = this;
const {position, ticks} = me.options;
- const {crossAlignment, mirror, padding} = ticks;
+ const {crossAlign, mirror, padding} = ticks;
const labelSizes = me._getLabelSizes();
const tickAndPadding = tl + padding;
const widest = labelSizes.widest.width;
@@ -1395,9 +1395,9 @@ export default class Scale extends Element {
} else {
x = me.right - tickAndPadding;
- if (crossAlignment === 'near') {
+ if (crossAlign === 'near') {
textAlign = 'right';
- } else if (crossAlignment === 'center') {
+ } else if (crossAlign === 'center') {
textAlign = 'center';
x -= (widest / 2);
} else {
@@ -1412,9 +1412,9 @@ export default class Scale extends Element {
} else {
x = me.left + tickAndPadding;
- if (crossAlignment === 'near') {
+ if (crossAlign === 'near') {
textAlign = 'left';
- } else if (crossAlignment === 'center') {
+ } else if (crossAlign === 'center') {
textAlign = 'center';
x += widest / 2;
} else { | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/crossAlignment/cross-align-bottom-center.js | @@ -13,7 +13,7 @@ module.exports = {
scales: {
x: {
ticks: {
- crossAlignment: 'center',
+ crossAlign: 'center',
},
},
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/crossAlignment/cross-align-bottom-far.js | @@ -13,7 +13,7 @@ module.exports = {
scales: {
x: {
ticks: {
- crossAlignment: 'far',
+ crossAlign: 'far',
},
},
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/crossAlignment/cross-align-bottom-near.js | @@ -13,7 +13,7 @@ module.exports = {
scales: {
x: {
ticks: {
- crossAlignment: 'near',
+ crossAlign: 'near',
},
},
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/crossAlignment/cross-align-left-center.js | @@ -15,7 +15,7 @@ module.exports = {
y: {
position: 'left',
ticks: {
- crossAlignment: 'center',
+ crossAlign: 'center',
},
},
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/crossAlignment/cross-align-left-far.js | @@ -15,7 +15,7 @@ module.exports = {
y: {
position: 'left',
ticks: {
- crossAlignment: 'far',
+ crossAlign: 'far',
},
},
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/crossAlignment/cross-align-left-near.js | @@ -15,7 +15,7 @@ module.exports = {
y: {
position: 'left',
ticks: {
- crossAlignment: 'near',
+ crossAlign: 'near',
},
},
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/crossAlignment/cross-align-right-center.js | @@ -15,7 +15,7 @@ module.exports = {
y: {
position: 'right',
ticks: {
- crossAlignment: 'center',
+ crossAlign: 'center',
},
},
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/crossAlignment/cross-align-right-far.js | @@ -15,7 +15,7 @@ module.exports = {
y: {
position: 'right',
ticks: {
- crossAlignment: 'far',
+ crossAlign: 'far',
},
},
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/crossAlignment/cross-align-right-near.js | @@ -15,7 +15,7 @@ module.exports = {
y: {
position: 'right',
ticks: {
- crossAlignment: 'near',
+ crossAlign: 'near',
},
},
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/crossAlignment/cross-align-top-center.js | @@ -14,7 +14,7 @@ module.exports = {
x: {
position: 'top',
ticks: {
- crossAlignment: 'center',
+ crossAlign: 'center',
},
},
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/crossAlignment/cross-align-top-far.js | @@ -14,7 +14,7 @@ module.exports = {
x: {
position: 'top',
ticks: {
- crossAlignment: 'far',
+ crossAlign: 'far',
},
},
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/crossAlignment/cross-align-top-near.js | @@ -14,7 +14,7 @@ module.exports = {
x: {
position: 'top',
ticks: {
- crossAlignment: 'near',
+ crossAlign: 'near',
},
},
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/label-align-center.js | @@ -13,12 +13,12 @@ module.exports = {
scales: {
x: {
ticks: {
- alignment: 'center',
+ align: 'center',
},
},
y: {
ticks: {
- alignment: 'center',
+ align: 'center',
}
}
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/label-align-end.js | @@ -13,12 +13,12 @@ module.exports = {
scales: {
x: {
ticks: {
- alignment: 'end',
+ align: 'end',
},
},
y: {
ticks: {
- alignment: 'end',
+ align: 'end',
}
}
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | test/fixtures/core.scale/label-align-start.js | @@ -13,12 +13,12 @@ module.exports = {
scales: {
x: {
ticks: {
- alignment: 'start',
+ align: 'start',
},
},
y: {
ticks: {
- alignment: 'start',
+ align: 'start',
}
}
} | true |
Other | chartjs | Chart.js | 1ca60808b4ccf630ea91cfe7077ae821879eab5d.json | Shorten alignment settings for axes (#7886)
* Rename crossAlignment to crossAlign
* Update alignment to align for cartesian axes | types/scales/index.d.ts | @@ -132,7 +132,7 @@ export interface ICartesianScaleOptions extends ICoreScaleOptions {
* The label alignment
* @default 'center'
*/
- alignment: 'start' | 'center' | 'end';
+ align: 'start' | 'center' | 'end';
/**
* If true, automatically calculates how many labels can be shown and hides labels accordingly. Labels will be rotated up to maxRotation before skipping any. Turn autoSkip off to show all labels no matter what.
* @default true
@@ -149,7 +149,7 @@ export interface ICartesianScaleOptions extends ICoreScaleOptions {
* This only applies when the rotation is 0 and the axis position is one of "top", "left", "right", or "bottom"
* @default 'near'
*/
- crossAlignment: 'near' | 'center' | 'far';
+ crossAlign: 'near' | 'center' | 'far';
/**
* Distance in pixels to offset the label from the centre point of the tick (in the x direction for the x axis, and the y direction for the y axis). Note: this can cause labels at the edges to be cropped by the edge of the canvas | true |
Other | chartjs | Chart.js | ff354cc5b8245049887f24cf855d19d928d6d8de.json | Remove release branch workflow (#7827)
* GitHub actions uses locked install for CI
* Add initial GitHub action to publish to NPM
* Detect the NPM tag (latest vs next) depending on the git tag
* Deploy docs from releases & master commits
* Remove Travis CI
* Update repo badge to use actions status
* Remove Travis env vars and update docs-config to take a parameter
* Update publish script regex to match other scripts
* Deploy docs action only runs in one spot | .github/workflows/ci.yml | @@ -41,7 +41,7 @@ jobs:
shell: bash
- name: Build and Test
run: |
- npm install
+ npm ci
npm run build
npm test
- name: Package | true |
Other | chartjs | Chart.js | ff354cc5b8245049887f24cf855d19d928d6d8de.json | Remove release branch workflow (#7827)
* GitHub actions uses locked install for CI
* Add initial GitHub action to publish to NPM
* Detect the NPM tag (latest vs next) depending on the git tag
* Deploy docs from releases & master commits
* Remove Travis CI
* Update repo badge to use actions status
* Remove Travis env vars and update docs-config to take a parameter
* Update publish script regex to match other scripts
* Deploy docs action only runs in one spot | .github/workflows/deploy-docs.yml | @@ -0,0 +1,28 @@
+# This workflow publishes new documentation to https://chartjs.org/docs/master after every commit
+name: CI
+
+on:
+ push:
+ branches:
+ - master
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v2
+ - name: Use Node.js
+ uses: actions/setup-node@v1
+ - name: Package & Deploy Docs
+ run: |
+ npm ci
+ npm run build
+ ./scripts/docs-config.sh "master"
+ npm run docs
+ npm run typedoc
+ npm pack
+ ./scripts/deploy-docs.sh "master"
+ env:
+ GITHUB_TOKEN: ${{ secrets.GH_AUTH_TOKEN }}
+ GH_AUTH_EMAIL: ${{ secrets.GH_AUTH_EMAIL }} | true |
Other | chartjs | Chart.js | ff354cc5b8245049887f24cf855d19d928d6d8de.json | Remove release branch workflow (#7827)
* GitHub actions uses locked install for CI
* Add initial GitHub action to publish to NPM
* Detect the NPM tag (latest vs next) depending on the git tag
* Deploy docs from releases & master commits
* Remove Travis CI
* Update repo badge to use actions status
* Remove Travis env vars and update docs-config to take a parameter
* Update publish script regex to match other scripts
* Deploy docs action only runs in one spot | .github/workflows/npmpublish.yml | @@ -0,0 +1,75 @@
+# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
+# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
+
+name: Node.js Package
+
+on:
+ release:
+ types: [published]
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: Use Node.js
+ uses: actions/setup-node@v1
+ - name: Setup xvfb
+ run: |
+ Xvfb :99 -screen 0 1024x768x24 &
+ echo "::set-env name=DISPLAY:::99.0"
+ - name: Test
+ run: |
+ npm ci
+ npm test
+
+ publish-npm:
+ needs: test
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - uses: actions/setup-node@v1
+ with:
+ node-version: 12
+ registry-url: https://registry.npmjs.org/
+ # Since we created the release in the UI, we need to find it.
+ # This step gets the release from the GITHUB_REF env var
+ - name: Get release
+ id: get_release
+ uses: bruceadams/get-release@v1.2.2
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ - name: Setup and build
+ run: |
+ npm ci
+ npm install -g json
+ json -I -f package.json -e "this.version=\"$GITHUB_REF\""
+ json -I -f package-lock.json -e "this.version=\"$GITHUB_REF\""
+ npm run build
+ ./scripts/docs-config.sh "${GITHUB_REF:1}"
+ npm run docs
+ npm run typedoc
+ npm pack
+ - name: Publish to NPM
+ run: ./scripts/publish.sh
+ env:
+ NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
+ # On releases, GITHUB_REF is the tag name which is the version
+ # However, it will include the leading "v", so we need to strip that
+ # first character off here since we want the docs folder to not have
+ # the "v" in it.
+ - name: Deploy Docs
+ run: ./scripts/deploy-docs.sh "${GITHUB_REF:1}"
+ env:
+ GITHUB_TOKEN: ${{ secrets.GH_AUTH_TOKEN }}
+ GH_AUTH_EMAIL: ${{ secrets.GH_AUTH_EMAIL }}
+ - name: Upload NPM package file
+ id: upload-npm-package-file
+ uses: actions/upload-release-asset@v1
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ with:
+ upload_url: ${{ steps.get_release.outputs.upload_url }}
+ asset_path: chart.js-$GITHUB_REF.tgz
+ asset_name: chart.js-$GITHUB_REF.tgz
+ asset_content_type: application/gzip | true |
Other | chartjs | Chart.js | ff354cc5b8245049887f24cf855d19d928d6d8de.json | Remove release branch workflow (#7827)
* GitHub actions uses locked install for CI
* Add initial GitHub action to publish to NPM
* Detect the NPM tag (latest vs next) depending on the git tag
* Deploy docs from releases & master commits
* Remove Travis CI
* Update repo badge to use actions status
* Remove Travis env vars and update docs-config to take a parameter
* Update publish script regex to match other scripts
* Deploy docs action only runs in one spot | .travis.yml | @@ -1,59 +0,0 @@
-language: node_js
-node_js:
- - lts/*
-
-before_install:
- - "export CHROME_BIN=/usr/bin/google-chrome"
-
-services:
- - xvfb
-
-script:
- - npm run build
- - npm test
- - ./scripts/docs-config.sh
- - npm run docs
- - npm run typedoc
- - npm pack
- - cat ./coverage/lcov.info | ./node_modules/.bin/coveralls || true
-
-sudo: required
-dist: bionic
-
-addons:
- chrome: stable
- firefox: latest
-
-# IMPORTANT: scripts require GITHUB_AUTH_TOKEN and GITHUB_AUTH_EMAIL environment variables
-# IMPORTANT: scripts has to be set executables in the Git repository (error 127)
-# https://github.com/travis-ci/travis-ci/issues/5538#issuecomment-225025939
-
-deploy:
-- provider: script
- script: ./scripts/deploy.sh
- skip_cleanup: true
- on:
- all_branches: true
-- provider: script
- script: ./scripts/release.sh
- skip_cleanup: true
- on:
- all_branches: true
- condition: $TRAVIS_BRANCH =~ ^(release.*)$
-- provider: releases
- api_key: $GITHUB_AUTH_TOKEN
- skip_cleanup: true
- file_glob: true
- file:
- - ./dist/*.css
- - ./dist/*.js
- - ./dist/*.zip
- on:
- tags: true
-- provider: npm
- email: $NPM_AUTH_EMAIL
- api_key: $NPM_AUTH_TOKEN
- skip_cleanup: true
- on:
- tags: true
- tag: next | true |
Other | chartjs | Chart.js | ff354cc5b8245049887f24cf855d19d928d6d8de.json | Remove release branch workflow (#7827)
* GitHub actions uses locked install for CI
* Add initial GitHub action to publish to NPM
* Detect the NPM tag (latest vs next) depending on the git tag
* Deploy docs from releases & master commits
* Remove Travis CI
* Update repo badge to use actions status
* Remove Travis env vars and update docs-config to take a parameter
* Update publish script regex to match other scripts
* Deploy docs action only runs in one spot | README.md | @@ -5,7 +5,7 @@
<p align="center">
<a href="https://www.chartjs.org/docs/latest/getting-started/installation.html"><img src="https://img.shields.io/github/release/chartjs/Chart.js.svg?style=flat-square&maxAge=600" alt="Downloads"></a>
- <a href="https://travis-ci.org/chartjs/Chart.js"><img src="https://img.shields.io/travis/chartjs/Chart.js.svg?style=flat-square&maxAge=600" alt="Builds"></a>
+ <a href="https://github.com/chartjs/Chart.js/actions?query=workflow%3ACI+branch%3Amaster"><img alt="GitHub Workflow Status" src="https://img.shields.io/github/workflow/status/chartjs/Chart.js/CI"></a>
<a href="https://coveralls.io/github/chartjs/Chart.js?branch=master"><img src="https://img.shields.io/coveralls/chartjs/Chart.js.svg?style=flat-square&maxAge=600" alt="Coverage"></a>
<a href="https://github.com/chartjs/awesome"><img src="https://awesome.re/badge-flat2.svg" alt="Awesome"></a>
<a href="https://chartjs-slack.herokuapp.com/"><img src="https://img.shields.io/badge/slack-chartjs-blue.svg?style=flat-square&maxAge=3600" alt="Slack"></a> | true |
Other | chartjs | Chart.js | ff354cc5b8245049887f24cf855d19d928d6d8de.json | Remove release branch workflow (#7827)
* GitHub actions uses locked install for CI
* Add initial GitHub action to publish to NPM
* Detect the NPM tag (latest vs next) depending on the git tag
* Deploy docs from releases & master commits
* Remove Travis CI
* Update repo badge to use actions status
* Remove Travis env vars and update docs-config to take a parameter
* Update publish script regex to match other scripts
* Deploy docs action only runs in one spot | scripts/deploy-docs.sh | @@ -4,20 +4,9 @@ set -e
TARGET_DIR='gh-pages'
TARGET_BRANCH='master'
-TARGET_REPO_URL="https://$GITHUB_AUTH_TOKEN@github.com/chartjs/chartjs.github.io.git"
+TARGET_REPO_URL="https://$GITHUB_TOKEN@github.com/chartjs/chartjs.github.io.git"
-# Note: this code also exists in docs-config.sh
-# Make sure that this script is executed only for the release and master branches
-VERSION_REGEX='[[:digit:]]+.[[:digit:]]+.[[:digit:]]+(-.*)?'
-if [[ "$TRAVIS_BRANCH" =~ ^release.*$ ]]; then
- # Travis executes this script from the repository root, so at the same level than package.json
- VERSION=$(node -p -e "require('./package.json').version")
-elif [ "$TRAVIS_BRANCH" == "master" ]; then
- VERSION="master"
-else
- echo "Skipping deploy because this is not the master or release branch"
- exit 0
-fi
+VERSION=$1
function move_sample_scripts {
local subdirectory=$1
@@ -47,7 +36,7 @@ function update_tagged_files {
if [ "$VERSION" == "master" ]; then
update_with_tag master
elif [[ "$VERSION" =~ ^[^-]+$ ]]; then
- update_with_tag lastest
+ update_with_tag latest
else
update_with_tag next
fi
@@ -75,9 +64,9 @@ update_tagged_files
git add --all
git remote add auth-origin $TARGET_REPO_URL
-git config --global user.email "$GITHUB_AUTH_EMAIL"
+git config --global user.email "$GH_AUTH_EMAIL"
git config --global user.name "Chart.js"
-git commit -m "Deploy $VERSION from $TRAVIS_REPO_SLUG" -m "Commit: $TRAVIS_COMMIT"
+git commit -m "Deploy $VERSION from $GITHUB_REPOSITORY" -m "Commit: $GITHUB_SHA"
git push -q auth-origin $TARGET_BRANCH
git remote rm auth-origin
| true |
Other | chartjs | Chart.js | ff354cc5b8245049887f24cf855d19d928d6d8de.json | Remove release branch workflow (#7827)
* GitHub actions uses locked install for CI
* Add initial GitHub action to publish to NPM
* Detect the NPM tag (latest vs next) depending on the git tag
* Deploy docs from releases & master commits
* Remove Travis CI
* Update repo badge to use actions status
* Remove Travis env vars and update docs-config to take a parameter
* Update publish script regex to match other scripts
* Deploy docs action only runs in one spot | scripts/docs-config.sh | @@ -2,18 +2,7 @@
set -e
-# Note: this code also exists in deploy.sh
-# Make sure that this script is executed only for the release and master branches
-VERSION_REGEX='[[:digit:]]+.[[:digit:]]+.[[:digit:]]+(-.*)?'
-if [[ "$TRAVIS_BRANCH" =~ ^release.*$ ]]; then
- # Travis executes this script from the repository root, so at the same level than package.json
- VERSION=$(node -p -e "require('./package.json').version")
-elif [ "$TRAVIS_BRANCH" == "master" ]; then
- VERSION="master"
-else
- echo "Skipping docs configuration because this is not the master or release branch"
- exit 0
-fi
+VERSION=$1
# Note: this code also exists in deploy.sh
# tag is next|latest|master
@@ -23,7 +12,7 @@ function update_config {
if [ "$VERSION" == "master" ]; then
tag=master
elif [[ "$VERSION" =~ ^[^-]+$ ]]; then
- tag=lastest
+ tag=latest
else
tag=next
fi | true |
Other | chartjs | Chart.js | ff354cc5b8245049887f24cf855d19d928d6d8de.json | Remove release branch workflow (#7827)
* GitHub actions uses locked install for CI
* Add initial GitHub action to publish to NPM
* Detect the NPM tag (latest vs next) depending on the git tag
* Deploy docs from releases & master commits
* Remove Travis CI
* Update repo badge to use actions status
* Remove Travis env vars and update docs-config to take a parameter
* Update publish script regex to match other scripts
* Deploy docs action only runs in one spot | scripts/publish.sh | @@ -0,0 +1,12 @@
+#!/bin/bash
+
+set -e
+
+NPM_TAG="next"
+
+if [[ "$GITHUB_REF" =~ ^[^-]+$ ]]; then
+ echo "Release tag indicates a full release. Releasing as \"latest\"."
+ NPM_TAG="latest"
+fi
+
+npm publish --tag "$NPM_TAG" | true |
Other | chartjs | Chart.js | ff354cc5b8245049887f24cf855d19d928d6d8de.json | Remove release branch workflow (#7827)
* GitHub actions uses locked install for CI
* Add initial GitHub action to publish to NPM
* Detect the NPM tag (latest vs next) depending on the git tag
* Deploy docs from releases & master commits
* Remove Travis CI
* Update repo badge to use actions status
* Remove Travis env vars and update docs-config to take a parameter
* Update publish script regex to match other scripts
* Deploy docs action only runs in one spot | scripts/release.sh | @@ -1,29 +0,0 @@
-#!/bin/bash
-
-set -e
-
-if [[ ! "$TRAVIS_BRANCH" =~ ^release.*$ ]]; then
- echo "Skipping release because this is not the 'release' branch"
- exit 0
-fi
-
-# Travis executes this script from the repository root, so at the same level than package.json
-VERSION=$(node -p -e "require('./package.json').version")
-
-# Make sure that the associated tag doesn't already exist
-GITTAG=$(git ls-remote origin refs/tags/v$VERSION)
-if [ "$GITTAG" != "" ]; then
- echo "Tag for package.json version already exists, aborting release"
- exit 1
-fi
-
-git remote add auth-origin https://$GITHUB_AUTH_TOKEN@github.com/$TRAVIS_REPO_SLUG.git
-git config --global user.email "$GITHUB_AUTH_EMAIL"
-git config --global user.name "Chart.js"
-git checkout --detach --quiet
-git add -f dist/*.js
-git commit -m "Release $VERSION"
-git tag -a "v$VERSION" -m "Version $VERSION"
-git push -q auth-origin refs/tags/v$VERSION 2>/dev/null
-git remote rm auth-origin
-git checkout -f @{-1} | true |
Other | chartjs | Chart.js | 0d95c7974c2bc44a891c3a8d159f4127ad2e7e92.json | Fix typo in const name (#7872) | src/helpers/helpers.dom.js | @@ -104,9 +104,9 @@ function getContainerSize(canvas, width, height) {
const rect = container.getBoundingClientRect(); // this is the border box of the container
const containerStyle = getComputedStyle(container);
const containerBorder = getPositionedStyle(containerStyle, 'border', 'width');
- const contarinerPadding = getPositionedStyle(containerStyle, 'padding');
- width = rect.width - contarinerPadding.width - containerBorder.width;
- height = rect.height - contarinerPadding.height - containerBorder.height;
+ const containerPadding = getPositionedStyle(containerStyle, 'padding');
+ width = rect.width - containerPadding.width - containerBorder.width;
+ height = rect.height - containerPadding.height - containerBorder.height;
maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth');
maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight');
} | false |
Other | chartjs | Chart.js | 168965fa3899a19fc6acbb8863d8ac100b817b8e.json | Enable custom sorting of the legend items (#7851) | docs/docs/configuration/legend.md | @@ -54,6 +54,7 @@ The legend label configuration is nested below the legend configuration using th
| `padding` | `number` | `10` | Padding between rows of colored boxes.
| `generateLabels` | `function` | | Generates legend items for each thing in the legend. Default implementation returns the text + styling for the color box. See [Legend Item](#legend-item-interface) for details.
| `filter` | `function` | `null` | Filters legend items out of the legend. Receives 2 parameters, a [Legend Item](#legend-item-interface) and the chart data.
+| `sort` | `function` | `null` | Sorts legend items. Receives 3 parameters, two [Legend Items](#legend-item-interface) and the chart data.
| `usePointStyle` | `boolean` | `false` | Label style will match corresponding point style (size is based on the mimimum value between boxWidth and font.size).
## Legend Title Configuration | true |
Other | chartjs | Chart.js | 168965fa3899a19fc6acbb8863d8ac100b817b8e.json | Enable custom sorting of the legend items (#7851) | src/plugins/plugin.legend.js | @@ -160,6 +160,10 @@ export class Legend extends Element {
legendItems = legendItems.filter((item) => labelOpts.filter(item, me.chart.data));
}
+ if (labelOpts.sort) {
+ legendItems = legendItems.sort((a, b) => labelOpts.sort(a, b, me.chart.data));
+ }
+
if (me.options.reverse) {
legendItems.reverse();
} | true |
Other | chartjs | Chart.js | 168965fa3899a19fc6acbb8863d8ac100b817b8e.json | Enable custom sorting of the legend items (#7851) | test/specs/plugin.legend.tests.js | @@ -311,6 +311,85 @@ describe('Legend block tests', function() {
}]);
});
+ it('should sort items', function() {
+ var chart = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'dataset1',
+ backgroundColor: '#f31',
+ borderCapStyle: 'round',
+ borderDash: [2, 2],
+ borderDashOffset: 5.5,
+ data: []
+ }, {
+ label: 'dataset2',
+ hidden: true,
+ borderJoinStyle: 'round',
+ data: []
+ }, {
+ label: 'dataset3',
+ borderWidth: 10,
+ borderColor: 'green',
+ pointStyle: 'crossRot',
+ fill: false,
+ data: []
+ }],
+ labels: []
+ },
+ options: {
+ legend: {
+ labels: {
+ sort: function(a, b) {
+ return b.datasetIndex > a.datasetIndex ? 1 : -1;
+ }
+ }
+ }
+ }
+ });
+
+ expect(chart.legend.legendItems).toEqual([{
+ text: 'dataset3',
+ fillStyle: 'rgba(0,0,0,0.1)',
+ hidden: false,
+ lineCap: 'butt',
+ lineDash: [],
+ lineDashOffset: 0,
+ lineJoin: 'miter',
+ lineWidth: 10,
+ strokeStyle: 'green',
+ pointStyle: undefined,
+ rotation: undefined,
+ datasetIndex: 2
+ }, {
+ text: 'dataset2',
+ fillStyle: 'rgba(0,0,0,0.1)',
+ hidden: true,
+ lineCap: 'butt',
+ lineDash: [],
+ lineDashOffset: 0,
+ lineJoin: 'round',
+ lineWidth: 3,
+ strokeStyle: 'rgba(0,0,0,0.1)',
+ pointStyle: undefined,
+ rotation: undefined,
+ datasetIndex: 1
+ }, {
+ text: 'dataset1',
+ fillStyle: '#f31',
+ hidden: false,
+ lineCap: 'round',
+ lineDash: [2, 2],
+ lineDashOffset: 5.5,
+ lineJoin: 'miter',
+ lineWidth: 3,
+ strokeStyle: 'rgba(0,0,0,0.1)',
+ pointStyle: undefined,
+ rotation: undefined,
+ datasetIndex: 0
+ }]);
+ });
+
it('should not throw when the label options are missing', function() {
var makeChart = function() {
window.acquireChart({ | true |
Other | chartjs | Chart.js | 168965fa3899a19fc6acbb8863d8ac100b817b8e.json | Enable custom sorting of the legend items (#7851) | types/plugins/index.d.ts | @@ -165,6 +165,11 @@ export interface ILegendOptions {
*/
filter(item: ILegendItem, data: IChartData): boolean;
+ /**
+ * Sorts the legend items
+ */
+ sort(a: ILegendItem, b: ILegendItem, data: IChartData): number;
+
/**
* Label style will match corresponding point style (size is based on the mimimum value between boxWidth and font.size).
* @default false | true |
Other | chartjs | Chart.js | 8d36927b290bfe28b2ecb7393ccf5c0a473fd08a.json | Normalize context creation for option resolution (#7847)
* Normalize context creation for option resolution
* Pass mode to _computeAngle | src/controllers/controller.bubble.js | @@ -109,18 +109,11 @@ export default class BubbleController extends DatasetController {
resolveDataElementOptions(index, mode) {
const me = this;
const chart = me.chart;
- const dataset = me.getDataset();
const parsed = me.getParsed(index);
let values = super.resolveDataElementOptions(index, mode);
// Scriptable options
- const context = {
- chart,
- dataPoint: parsed,
- dataIndex: index,
- dataset,
- datasetIndex: me.index
- };
+ const context = me.getContext(index, mode === 'active');
// In case values were cached (and thus frozen), we need to clone the values
if (values.$shared) { | true |
Other | chartjs | Chart.js | 8d36927b290bfe28b2ecb7393ccf5c0a473fd08a.json | Normalize context creation for option resolution (#7847)
* Normalize context creation for option resolution
* Pass mode to _computeAngle | src/controllers/controller.polarArea.js | @@ -59,12 +59,12 @@ export default class PolarAreaController extends DatasetController {
me._cachedMeta.count = me.countVisibleElements();
for (i = 0; i < start; ++i) {
- angle += me._computeAngle(i);
+ angle += me._computeAngle(i, mode);
}
for (i = start; i < start + count; i++) {
const arc = arcs[i];
let startAngle = angle;
- let endAngle = angle + me._computeAngle(i);
+ let endAngle = angle + me._computeAngle(i, mode);
let outerRadius = this.chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(dataset.data[i]) : 0;
angle = endAngle;
@@ -109,7 +109,7 @@ export default class PolarAreaController extends DatasetController {
/**
* @private
*/
- _computeAngle(index) {
+ _computeAngle(index, mode) {
const me = this;
const meta = me._cachedMeta;
const count = meta.count;
@@ -120,13 +120,7 @@ export default class PolarAreaController extends DatasetController {
}
// Scriptable options
- const context = {
- chart: me.chart,
- dataPoint: this.getParsed(index),
- dataIndex: index,
- dataset,
- datasetIndex: me.index
- };
+ const context = me.getContext(index, mode === 'active');
return resolve([
me.chart.options.elements.arc.angle, | true |
Other | chartjs | Chart.js | 8d36927b290bfe28b2ecb7393ccf5c0a473fd08a.json | Normalize context creation for option resolution (#7847)
* Normalize context creation for option resolution
* Pass mode to _computeAngle | src/core/core.datasetController.js | @@ -693,9 +693,9 @@ export default class DatasetController {
}
/**
- * @private
+ * @protected
*/
- _getContext(index, active) {
+ getContext(index, active) {
return {
chart: this.chart,
dataPoint: this.getParsed(index),
@@ -764,7 +764,7 @@ export default class DatasetController {
const datasetOpts = me._config;
const options = me.chart.options.elements[type] || {};
const values = {};
- const context = me._getContext(index, active);
+ const context = me.getContext(index, active);
const keys = optionKeys(optionNames);
for (let i = 0, ilen = keys.length; i < ilen; ++i) {
@@ -798,7 +798,7 @@ export default class DatasetController {
}
const info = {cacheable: true};
- const context = me._getContext(index, active);
+ const context = me.getContext(index, active);
const chartAnim = resolve([chart.options.animation], context, index, info);
const datasetAnim = resolve([me._config.animation], context, index, info);
let config = chartAnim && mergeIf({}, [datasetAnim, chartAnim]); | true |
Other | chartjs | Chart.js | 8d36927b290bfe28b2ecb7393ccf5c0a473fd08a.json | Normalize context creation for option resolution (#7847)
* Normalize context creation for option resolution
* Pass mode to _computeAngle | src/core/core.scale.js | @@ -1013,6 +1013,19 @@ export default class Scale extends Element {
0;
}
+ /**
+ * @protected
+ */
+ getContext(index) {
+ const ticks = this.ticks || [];
+ return {
+ chart: this.chart,
+ scale: this,
+ tick: ticks[index],
+ index
+ };
+ }
+
/**
* Returns a subset of ticks to be plotted to avoid overlapping labels.
* @param {Tick[]} ticks
@@ -1105,12 +1118,7 @@ export default class Scale extends Element {
const tl = getTickMarkLength(gridLines);
const items = [];
- let context = {
- chart,
- scale: me,
- tick: ticks[0],
- index: 0,
- };
+ let context = this.getContext(0);
const axisWidth = gridLines.drawBorder ? resolve([gridLines.borderWidth, gridLines.lineWidth, 0], context, 0) : 0;
const axisHalfWidth = axisWidth / 2;
const alignBorderValue = function(pixel) {
@@ -1172,15 +1180,7 @@ export default class Scale extends Element {
}
for (i = 0; i < ticksLength; ++i) {
- /** @type {Tick|object} */
- const tick = ticks[i] || {};
-
- context = {
- chart,
- scale: me,
- tick,
- index: i,
- };
+ context = this.getContext(i);
const lineWidth = resolve([gridLines.lineWidth], context, i);
const lineColor = resolve([gridLines.color], context, i);
@@ -1318,12 +1318,7 @@ export default class Scale extends Element {
const gridLines = me.options.gridLines;
const ctx = me.ctx;
const chart = me.chart;
- let context = {
- chart,
- scale: me,
- tick: me.ticks[0],
- index: 0,
- };
+ let context = me.getContext(0);
const axisWidth = gridLines.drawBorder ? resolve([gridLines.borderWidth, gridLines.lineWidth, 0], context, 0) : 0;
const items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
let i, ilen;
@@ -1364,12 +1359,7 @@ export default class Scale extends Element {
if (axisWidth) {
// Draw the line at the edge of the axis
const firstLineWidth = axisWidth;
- context = {
- chart,
- scale: me,
- tick: me.ticks[me._ticksLength - 1],
- index: me._ticksLength - 1,
- };
+ context = me.getContext(me._ticksLength - 1);
const lastLineWidth = resolve([gridLines.lineWidth, 1], context, me._ticksLength - 1);
const borderValue = me._borderValue;
let x1, x2, y1, y2;
@@ -1597,13 +1587,7 @@ export default class Scale extends Element {
const me = this;
const chart = me.chart;
const options = me.options.ticks;
- const ticks = me.ticks || [];
- const context = {
- chart,
- scale: me,
- tick: ticks[index],
- index
- };
+ const context = me.getContext(index);
return toFont(resolve([options.font], context), chart.options.font);
}
} | true |
Other | chartjs | Chart.js | 8d36927b290bfe28b2ecb7393ccf5c0a473fd08a.json | Normalize context creation for option resolution (#7847)
* Normalize context creation for option resolution
* Pass mode to _computeAngle | src/scales/scale.radialLinear.js | @@ -96,12 +96,7 @@ function fitWithPointLabels(scale) {
for (i = 0; i < valueCount; i++) {
pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
- const context = {
- chart: scale.chart,
- scale,
- index: i,
- label: scale.pointLabels[i]
- };
+ const context = scale.getContext(i);
const plFont = toFont(resolve([scale.options.pointLabels.font], context, i), scale.chart.options.font);
scale.ctx.font = plFont.string;
textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);
@@ -185,12 +180,7 @@ function drawPointLabels(scale) {
const extra = (i === 0 ? tickBackdropHeight / 2 : 0);
const pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
- const context = {
- chart: scale.chart,
- scale,
- index: i,
- label: scale.pointLabels[i],
- };
+ const context = scale.getContext(i);
const plFont = toFont(resolve([pointLabelOpts.font], context, i), scale.chart.options.font);
ctx.font = plFont.string;
ctx.fillStyle = plFont.color;
@@ -208,12 +198,7 @@ function drawRadiusLine(scale, gridLineOpts, radius, index) {
const circular = gridLineOpts.circular;
const valueCount = scale.chart.data.labels.length;
- const context = {
- chart: scale.chart,
- scale,
- index,
- tick: scale.ticks[index],
- };
+ const context = scale.getContext(index);
const lineColor = resolve([gridLineOpts.color], context, index - 1);
const lineWidth = resolve([gridLineOpts.lineWidth], context, index - 1);
let pointPosition;
@@ -440,12 +425,7 @@ export default class RadialLinearScale extends LinearScaleBase {
ctx.save();
for (i = me.chart.data.labels.length - 1; i >= 0; i--) {
- const context = {
- chart: me.chart,
- scale: me,
- index: i,
- label: me.pointLabels[i],
- };
+ const context = me.getContext(i);
const lineWidth = resolve([angleLineOpts.lineWidth, gridLineOpts.lineWidth], context, i);
const color = resolve([angleLineOpts.color, gridLineOpts.color], context, i);
@@ -496,17 +476,11 @@ export default class RadialLinearScale extends LinearScaleBase {
ctx.textBaseline = 'middle';
me.ticks.forEach((tick, index) => {
- const context = {
- chart: me.chart,
- scale: me,
- index,
- tick,
- };
-
if (index === 0 && !opts.reverse) {
return;
}
+ const context = me.getContext(index);
const tickFont = me._resolveTickFontOptions(index);
ctx.font = tickFont.string;
offset = me.getDistanceFromCenterForValue(me.ticks[index].value); | true |
Other | chartjs | Chart.js | 1a9b452cda942a74692780cf6a25cfbe231b745c.json | Limit pixel values further to 16bit integer range (#7848) | src/core/core.scale.js | @@ -2,7 +2,7 @@ import defaults from './core.defaults';
import Element from './core.element';
import {_alignPixel, _measureText} from '../helpers/helpers.canvas';
import {callback as call, each, isArray, isFinite, isNullOrUndef, isObject, valueOrDefault} from '../helpers/helpers.core';
-import {_factorize, toDegrees, toRadians, _int32Range} from '../helpers/helpers.math';
+import {_factorize, toDegrees, toRadians, _int16Range} from '../helpers/helpers.math';
import {toFont, resolve, toPadding} from '../helpers/helpers.options';
import Ticks from './core.ticks';
@@ -981,7 +981,7 @@ export default class Scale extends Element {
decimal = 1 - decimal;
}
- return _int32Range(me._startPixel + decimal * me._length);
+ return _int16Range(me._startPixel + decimal * me._length);
}
/** | true |
Other | chartjs | Chart.js | 1a9b452cda942a74692780cf6a25cfbe231b745c.json | Limit pixel values further to 16bit integer range (#7848) | src/helpers/helpers.math.js | @@ -173,6 +173,6 @@ export function _limitValue(value, min, max) {
return Math.max(min, Math.min(max, value));
}
-export function _int32Range(value) {
- return _limitValue(value, -2147483648, 2147483647);
+export function _int16Range(value) {
+ return _limitValue(value, -32768, 32767);
} | true |
Other | chartjs | Chart.js | 8438da9e8426f8b707b1b0dbb87d43ae32ffc7d1.json | Provide method to lookup a chart from a canvas (#7843)
* Provide method to lookup a chart from a canvas
* Throw an error during construction if a canvas is in use
* Migration docs for new constructor behaviour | docs/docs/developers/api.md | @@ -204,3 +204,11 @@ Sets the visibility for the given dataset to true. Updates the chart and animate
```javascript
chart.show(1); // shows dataset at index 1 and does 'show' animation.
```
+
+## Static: getChart(key)
+
+Finds the chart instance from the given key. If the key is a `string`, it is interpreted as the ID of the Canvas node for the Chart. The key can also be a `CanvasRenderingContext2D` or an `HTMLDOMElement`. This will return `undefined` if no Chart is found. To be found, the chart must have previously been created.
+
+```javascript
+const chart = Chart.getChart("canvas-id")
+```
\ No newline at end of file | true |
Other | chartjs | Chart.js | 8438da9e8426f8b707b1b0dbb87d43ae32ffc7d1.json | Provide method to lookup a chart from a canvas (#7843)
* Provide method to lookup a chart from a canvas
* Throw an error during construction if a canvas is in use
* Migration docs for new constructor behaviour | docs/docs/getting-started/v3-migration.md | @@ -21,6 +21,7 @@ Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released
* Distributed files are now in lower case. For example: `dist/chart.js`.
* Chart.js is no longer providing the `Chart.bundle.js` and `Chart.bundle.min.js`. Please see the [installation](installation.md) and [integration](integration.md) docs for details on the recommended way to setup Chart.js if you were using these builds.
* `moment` is no longer specified as an npm dependency. If you are using the `time` or `timeseries` scales, you must include one of [the available adapters](https://github.com/chartjs/awesome#adapters) and corresponding date library. You no longer need to exclude moment from your build.
+* The `Chart` constructor will throw an error if the canvas/context provided is already in use
* Chart.js 3 is tree-shakeable. So if you are using it as an `npm` module in a project, you need to import and register the controllers, elements, scales and plugins you want to use. You will not have to call `register` if importing Chart.js via a `script` tag, but will not get the tree shaking benefits in this case. Here is an example of registering components:
```javascript | true |
Other | chartjs | Chart.js | 8438da9e8426f8b707b1b0dbb87d43ae32ffc7d1.json | Provide method to lookup a chart from a canvas (#7843)
* Provide method to lookup a chart from a canvas
* Throw an error during construction if a canvas is in use
* Migration docs for new constructor behaviour | src/core/core.controller.js | @@ -222,6 +222,14 @@ class Chart {
config = initConfig(config);
const initialCanvas = getCanvas(item);
+ const existingChart = Chart.getChart(initialCanvas);
+ if (existingChart) {
+ throw new Error(
+ 'Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' +
+ ' must be destroyed before the canvas can be reused.'
+ );
+ }
+
this.platform = me._initializePlatform(initialCanvas, config);
const context = me.platform.acquireContext(initialCanvas, config);
@@ -1155,6 +1163,11 @@ Chart.instances = {};
Chart.registry = registry;
Chart.version = version;
+Chart.getChart = (key) => {
+ const canvas = getCanvas(key);
+ return Object.values(Chart.instances).filter((c) => c.canvas === canvas).pop();
+};
+
// @ts-ignore
const invalidatePlugins = () => each(Chart.instances, (chart) => chart._plugins.invalidate());
| true |
Other | chartjs | Chart.js | 8438da9e8426f8b707b1b0dbb87d43ae32ffc7d1.json | Provide method to lookup a chart from a canvas (#7843)
* Provide method to lookup a chart from a canvas
* Throw an error during construction if a canvas is in use
* Migration docs for new constructor behaviour | test/specs/core.controller.tests.js | @@ -10,6 +10,33 @@ describe('Chart', function() {
expect(chart instanceof Chart).toBeTruthy();
});
+ it('should throw an error if the canvas is already in use', function() {
+ var config = {
+ type: 'line',
+ data: {
+ datasets: [{
+ data: [1, 2, 3, 4]
+ }],
+ labels: ['A', 'B', 'C', 'D']
+ }
+ };
+ var chart = acquireChart(config);
+ var canvas = chart.canvas;
+
+ function createChart() {
+ return new Chart(canvas, config);
+ }
+
+ expect(createChart).toThrow(new Error(
+ 'Canvas is already in use. ' +
+ 'Chart with ID \'' + chart.id + '\'' +
+ ' must be destroyed before the canvas can be reused.'
+ ));
+
+ chart.destroy();
+ expect(createChart).not.toThrow();
+ });
+
describe('config initialization', function() {
it('should create missing config.data properties', function() {
var chart = acquireChart({});
@@ -1440,4 +1467,48 @@ describe('Chart', function() {
expect(chart.getDataVisibility(1)).toBe(false);
});
});
+
+ describe('getChart', function() {
+ it('should get the chart from the canvas ID', function() {
+ var chart = acquireChart({
+ type: 'pie',
+ data: {
+ datasets: [{
+ data: [1, 2, 3]
+ }]
+ }
+ });
+ chart.canvas.id = 'myID';
+
+ expect(Chart.getChart('myID')).toBe(chart);
+ });
+
+ it('should get the chart from an HTMLCanvasElement', function() {
+ var chart = acquireChart({
+ type: 'pie',
+ data: {
+ datasets: [{
+ data: [1, 2, 3]
+ }]
+ }
+ });
+ expect(Chart.getChart(chart.canvas)).toBe(chart);
+ });
+
+ it('should get the chart from an CanvasRenderingContext2D', function() {
+ var chart = acquireChart({
+ type: 'pie',
+ data: {
+ datasets: [{
+ data: [1, 2, 3]
+ }]
+ }
+ });
+ expect(Chart.getChart(chart.ctx)).toBe(chart);
+ });
+
+ it('should return undefined when a chart is not found or bad data is provided', function() {
+ expect(Chart.getChart(1)).toBeUndefined();
+ });
+ });
}); | true |
Other | chartjs | Chart.js | 8438da9e8426f8b707b1b0dbb87d43ae32ffc7d1.json | Provide method to lookup a chart from a canvas (#7843)
* Provide method to lookup a chart from a canvas
* Throw an error during construction if a canvas is in use
* Migration docs for new constructor behaviour | types/core/index.d.ts | @@ -302,6 +302,7 @@ export declare class Chart<
static readonly version: string;
static readonly instances: { [key: string]: Chart };
static readonly registry: Registry;
+ static getChart(key: string | CanvasRenderingContext2D | HTMLCanvasElement) : Chart | undefined;
static register(...items: IChartComponentLike[]): void;
static unregister(...items: IChartComponentLike[]): void;
} | true |
Other | chartjs | Chart.js | d332ebc63d46e4cc7657662cc47835ec94f5b52d.json | Remove enum types (#7841)
* Remove type enum
* Add declare keyword to UpdateModeEnum | docs/docs/developers/charts.md | @@ -155,21 +155,14 @@ new Chart(ctx, {
If you want your new chart type to be statically typed, you must provide a `.d.ts` TypeScript declaration file. Chart.js provides a way to augment built-in types with user-defined ones, by using the concept of "declaration merging".
-There are three main declarations that can be augmented when adding a new chart type:
-
-* `ChartTypeEnum` enumeration must contain an entry for the new type.
-* `IChartTypeRegistry` must contains the declarations for the new type, either by extending an existing entry in `IChartTypeRegistry` or by creating a new one.
+When adding a new chart type, `IChartTypeRegistry` must contains the declarations for the new type, either by extending an existing entry in `IChartTypeRegistry` or by creating a new one.
For example, to provide typings for a new chart type that extends from a bubble chart, you would add a `.d.ts` containing:
```javascript
import { IChartTypeRegistry } from 'chart.js'
declare module 'chart.js' {
- enum ChartTypeEnum {
- derivedBubble = 'derivedBubble'
- }
-
interface IChartTypeRegistry {
derivedBubble: IChartTypeRegistry['bubble']
} | true |
Other | chartjs | Chart.js | d332ebc63d46e4cc7657662cc47835ec94f5b52d.json | Remove enum types (#7841)
* Remove type enum
* Add declare keyword to UpdateModeEnum | types/core/index.d.ts | @@ -315,7 +315,7 @@ export declare type ChartItem =
| { canvas: HTMLCanvasElement | OffscreenCanvas }
| ArrayLike<CanvasRenderingContext2D | HTMLCanvasElement | OffscreenCanvas>;
-export enum UpdateModeEnum {
+export declare enum UpdateModeEnum {
resize = 'resize',
reset = 'reset',
none = 'none', | true |
Other | chartjs | Chart.js | d332ebc63d46e4cc7657662cc47835ec94f5b52d.json | Remove enum types (#7841)
* Remove type enum
* Add declare keyword to UpdateModeEnum | types/interfaces.d.ts | @@ -45,17 +45,6 @@ export type DeepPartial<T> = T extends {}
export type DistributiveArray<T> = T extends unknown ? T[] : never
-export enum ScaleTypeEnum {
- linear = 'linear',
- logarithmic = 'logarithmic',
- category = 'category',
- radialLinear = 'radialLinear',
- time = 'time',
- timeseries = 'timeseries',
-}
-
-export type IScaleType = keyof typeof ScaleTypeEnum;
-
export interface ICartesianScaleTypeRegistry {
linear: {
options: ILinearScaleOptions;
@@ -83,18 +72,7 @@ export interface IRadialScaleTypeRegistry {
export interface IScaleTypeRegistry extends ICartesianScaleTypeRegistry, IRadialScaleTypeRegistry {
}
-export enum ChartTypeEnum {
- bar = 'bar',
- bubble = 'bubble',
- doughnut = 'doughnut',
- line = 'line',
- pie = 'pie',
- polarArea = 'polarArea',
- radar = 'radar',
- scatter = 'scatter',
-}
-
-export type IChartType = keyof typeof ChartTypeEnum;
+export type IScaleType = keyof IScaleTypeRegistry;
export interface IChartTypeRegistry {
bar: {
@@ -147,6 +125,8 @@ export interface IChartTypeRegistry {
};
}
+export type IChartType = keyof IChartTypeRegistry;
+
export type IScaleOptions<SCALES extends IScaleType = IScaleType> = DeepPartial<
{ [key in IScaleType]: { type: key } & IScaleTypeRegistry[key]['options'] }[SCALES]
>; | true |
Other | chartjs | Chart.js | 2ac0436bd497e7b660f5d2ff7104d1f6a4331358.json | Use full height for fullWidth box when left/right (#7836)
Use full height for fullWidth box when left/right | src/core/core.layouts.js | @@ -47,12 +47,14 @@ function setLayoutDims(layouts, params) {
let i, ilen, layout;
for (i = 0, ilen = layouts.length; i < ilen; ++i) {
layout = layouts[i];
- // store width used instead of chartArea.w in fitBoxes
- layout.width = layout.horizontal
- ? layout.box.fullWidth && params.availableWidth
- : params.vBoxMaxWidth;
- // store height used instead of chartArea.h in fitBoxes
- layout.height = layout.horizontal && params.hBoxMaxHeight;
+ // store dimensions used instead of available chartArea in fitBoxes
+ if (layout.horizontal) {
+ layout.width = layout.box.fullWidth && params.availableWidth;
+ layout.height = params.hBoxMaxHeight;
+ } else {
+ layout.width = params.vBoxMaxWidth;
+ layout.height = layout.box.fullWidth && params.availableHeight;
+ }
}
}
@@ -187,8 +189,8 @@ function placeBoxes(boxes, chartArea, params) {
} else {
box.left = x;
box.right = x + box.width;
- box.top = chartArea.top;
- box.bottom = chartArea.top + chartArea.h;
+ box.top = box.fullWidth ? userPadding.top : chartArea.top;
+ box.bottom = box.fullWidth ? params.outerHeight - userPadding.right : chartArea.top + chartArea.h;
box.height = box.bottom - box.top;
x = box.right;
}
@@ -344,6 +346,7 @@ export default {
outerHeight: height,
padding,
availableWidth,
+ availableHeight,
vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length,
hBoxMaxHeight: availableHeight / 2
}); | false |
Other | chartjs | Chart.js | 5c0d13981c34753163088d2bafb96f837ff2bc67.json | Include dist/chunks in the NPM package (#7830)
* Include all files in the dist folder
* Bump version for beta3
* Update lockfile | package-lock.json | @@ -1,6 +1,6 @@
{
"name": "chart.js",
- "version": "3.0.0-beta.2",
+ "version": "3.0.0-beta.3",
"lockfileVersion": 1,
"requires": true,
"dependencies": { | true |
Other | chartjs | Chart.js | 5c0d13981c34753163088d2bafb96f837ff2bc67.json | Include dist/chunks in the NPM package (#7830)
* Include all files in the dist folder
* Bump version for beta3
* Update lockfile | package.json | @@ -2,7 +2,7 @@
"name": "chart.js",
"homepage": "https://www.chartjs.org",
"description": "Simple HTML5 charts using the canvas element.",
- "version": "3.0.0-beta.2",
+ "version": "3.0.0-beta.3",
"license": "MIT",
"jsdelivr": "dist/chart.min.js",
"unpkg": "dist/chart.min.js",
@@ -25,8 +25,8 @@
"url": "https://github.com/chartjs/Chart.js/issues"
},
"files": [
- "dist/*.js",
- "dist/*.d.ts",
+ "dist/**/*.js",
+ "dist/**/*.d.ts",
"helpers/**/*.js",
"helpers/**/*.d.ts"
], | true |
Other | chartjs | Chart.js | b36d55d0936bf591d5ab58ae3d6a076f8f2d62e1.json | Add onLeave to legend config docs (#6088) | docs/configuration/legend.md | @@ -12,6 +12,7 @@ The legend configuration is passed into the `options.legend` namespace. The glob
| `fullWidth` | `boolean` | `true` | Marks that this box should take the full width of the canvas (pushing down other boxes). This is unlikely to need to be changed in day-to-day use.
| `onClick` | `function` | | A callback that is called when a click event is registered on a label item.
| `onHover` | `function` | | A callback that is called when a 'mousemove' event is registered on top of a label item.
+| `onLeave` | `function` | | A callback that is called when a 'mousemove' event is registered outside of a previously hovered label item.
| `reverse` | `boolean` | `false` | Legend will show datasets in reverse order.
| `labels` | `object` | | See the [Legend Label Configuration](#legend-label-configuration) section below.
| false |
Other | chartjs | Chart.js | f3b18373e67c8e0aab6b29379787725a88dd7391.json | Add onLeave callback to legend (#6059) | samples/legend/callbacks.html | @@ -0,0 +1,124 @@
+<!doctype html>
+<html>
+<head>
+ <title>Legend Callbacks</title>
+ <script src="../../dist/Chart.min.js"></script>
+ <script src="../utils.js"></script>
+ <style>
+ body, html {
+ height: 100%;
+ font-family: sans-serif;
+ }
+ canvas{
+ -moz-user-select: none;
+ -webkit-user-select: none;
+ -ms-user-select: none;
+ }
+
+ #log {
+ position: absolute;
+ right: 0;
+ top: 0;
+ bottom: 0;
+ background-color: #EEE;
+ float: right;
+ width: 20%;
+ padding: 8px;
+ overflow-y: auto;
+ white-space: pre;
+ line-height: 1.5em;
+ }
+ </style>
+</head>
+
+<body>
+ <div id="log"></div>
+ <div style="width:75%;">
+ <canvas id="canvas"></canvas>
+ </div>
+ <script>
+ var logEntry = 1;
+ var logElement = document.getElementById('log');
+ var utils = Samples.utils;
+ var inputs = {
+ min: 20,
+ max: 80,
+ count: 8,
+ decimals: 2,
+ continuity: 1
+ };
+ var config;
+
+ function log(text) {
+ logElement.innerText += logEntry + '. ' + text + '\n';
+ logElement.scrollTop = logElement.scrollHeight;
+ logEntry++;
+ }
+
+ function generateData() {
+ return utils.numbers(inputs);
+ }
+ function generateLabels() {
+ return utils.months({count: inputs.count});
+ }
+
+ utils.srand(42);
+
+ config = {
+ type: 'line',
+ data: {
+ labels: generateLabels(),
+ datasets: [{
+ label: 'My First dataset',
+ backgroundColor: utils.color(0),
+ borderColor: utils.color(0),
+ data: generateData(),
+ fill: false,
+ }, {
+ label: 'My Second dataset',
+ fill: false,
+ backgroundColor: utils.color(1),
+ borderColor: utils.color(1),
+ data: generateData(),
+ }]
+ },
+ options: {
+ legend: {
+ onHover: function(event, legendItem) {
+ log('onHover: ' + legendItem.text);
+ },
+ onLeave: function(event, legendItem) {
+ log('onLeave: ' + legendItem.text);
+ },
+ onClick: function(event, legendItem) {
+ log('onClick:' + legendItem.text);
+ }
+ },
+ title: {
+ display: true,
+ text: 'Chart.js Line Chart'
+ },
+ scales: {
+ xAxes: [{
+ display: true,
+ scaleLabel: {
+ display: true,
+ labelString: 'Month'
+ }
+ }],
+ yAxes: [{
+ display: true,
+ scaleLabel: {
+ display: true,
+ labelString: 'Value'
+ }
+ }]
+ }
+ }
+ };
+
+ new Chart(document.getElementById('canvas'), config);
+ </script>
+</body>
+
+</html> | true |
Other | chartjs | Chart.js | f3b18373e67c8e0aab6b29379787725a88dd7391.json | Add onLeave callback to legend (#6059) | samples/samples.js | @@ -148,6 +148,9 @@
}, {
title: 'Point style',
path: 'legend/point-style.html'
+ }, {
+ title: 'Callbacks',
+ path: 'legend/callbacks.html'
}]
}, {
title: 'Tooltip', | true |
Other | chartjs | Chart.js | f3b18373e67c8e0aab6b29379787725a88dd7391.json | Add onLeave callback to legend (#6059) | src/plugins/plugin.legend.js | @@ -30,6 +30,7 @@ defaults._set('global', {
},
onHover: null,
+ onLeave: null,
labels: {
boxWidth: 40,
@@ -106,6 +107,11 @@ var Legend = Element.extend({
// Contains hit boxes for each dataset (in dataset order)
this.legendHitBoxes = [];
+ /**
+ * @private
+ */
+ this._hoveredItem = null;
+
// Are we in doughnut mode which has a different data type
this.doughnutMode = false;
},
@@ -458,20 +464,42 @@ var Legend = Element.extend({
}
},
+ /**
+ * @private
+ */
+ _getLegendItemAt: function(x, y) {
+ var me = this;
+ var i, hitBox, lh;
+
+ if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
+ // See if we are touching one of the dataset boxes
+ lh = me.legendHitBoxes;
+ for (i = 0; i < lh.length; ++i) {
+ hitBox = lh[i];
+
+ if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
+ // Touching an element
+ return me.legendItems[i];
+ }
+ }
+ }
+
+ return null;
+ },
+
/**
* Handle an event
* @private
* @param {IEvent} event - The event to handle
- * @return {boolean} true if a change occured
*/
handleEvent: function(e) {
var me = this;
var opts = me.options;
var type = e.type === 'mouseup' ? 'click' : e.type;
- var changed = false;
+ var hoveredItem;
if (type === 'mousemove') {
- if (!opts.onHover) {
+ if (!opts.onHover && !opts.onLeave) {
return;
}
} else if (type === 'click') {
@@ -483,33 +511,26 @@ var Legend = Element.extend({
}
// Chart event already has relative position in it
- var x = e.x;
- var y = e.y;
+ hoveredItem = me._getLegendItemAt(e.x, e.y);
- if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
- // See if we are touching one of the dataset boxes
- var lh = me.legendHitBoxes;
- for (var i = 0; i < lh.length; ++i) {
- var hitBox = lh[i];
-
- if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
- // Touching an element
- if (type === 'click') {
- // use e.native for backwards compatibility
- opts.onClick.call(me, e.native, me.legendItems[i]);
- changed = true;
- break;
- } else if (type === 'mousemove') {
- // use e.native for backwards compatibility
- opts.onHover.call(me, e.native, me.legendItems[i]);
- changed = true;
- break;
- }
+ if (type === 'click') {
+ if (hoveredItem && opts.onClick) {
+ // use e.native for backwards compatibility
+ opts.onClick.call(me, e.native, hoveredItem);
+ }
+ } else {
+ if (opts.onLeave && hoveredItem !== me._hoveredItem) {
+ if (me._hoveredItem) {
+ opts.onLeave.call(me, e.native, me._hoveredItem);
}
+ me._hoveredItem = hoveredItem;
}
- }
- return changed;
+ if (opts.onHover && hoveredItem) {
+ // use e.native for backwards compatibility
+ opts.onHover.call(me, e.native, hoveredItem);
+ }
+ }
}
});
| true |
Other | chartjs | Chart.js | f3b18373e67c8e0aab6b29379787725a88dd7391.json | Add onLeave callback to legend (#6059) | test/specs/plugin.legend.tests.js | @@ -11,6 +11,7 @@ describe('Legend block tests', function() {
// a callback that will handle
onClick: jasmine.any(Function),
onHover: null,
+ onLeave: null,
labels: {
boxWidth: 40,
@@ -653,4 +654,53 @@ describe('Legend block tests', function() {
expect(chart.legend.options).toEqual(jasmine.objectContaining(Chart.defaults.global.legend));
});
});
+
+ describe('callbacks', function() {
+ it('should call onClick, onHover and onLeave at the correct times', function() {
+ var clickItem = null;
+ var hoverItem = null;
+ var leaveItem = null;
+
+ var chart = acquireChart({
+ type: 'line',
+ data: {
+ labels: ['A', 'B', 'C', 'D'],
+ datasets: [{
+ data: [10, 20, 30, 100]
+ }]
+ },
+ options: {
+ legend: {
+ onClick: function(_, item) {
+ clickItem = item;
+ },
+ onHover: function(_, item) {
+ hoverItem = item;
+ },
+ onLeave: function(_, item) {
+ leaveItem = item;
+ }
+ }
+ }
+ });
+
+ var hb = chart.legend.legendHitBoxes[0];
+ var el = {
+ x: hb.left + (hb.width / 2),
+ y: hb.top + (hb.height / 2)
+ };
+
+ jasmine.triggerMouseEvent(chart, 'click', el);
+
+ expect(clickItem).toBe(chart.legend.legendItems[0]);
+
+ jasmine.triggerMouseEvent(chart, 'mousemove', el);
+
+ expect(hoverItem).toBe(chart.legend.legendItems[0]);
+
+ jasmine.triggerMouseEvent(chart, 'mousemove', chart.getDatasetMeta(0).data[0]);
+
+ expect(leaveItem).toBe(chart.legend.legendItems[0]);
+ });
+ });
}); | true |
Other | chartjs | Chart.js | f2b099b835bf5d6dfe3a7d3097997ec11983c3ed.json | Initialize date adapter with chart options (#6016) | docs/axes/cartesian/time.md | @@ -28,6 +28,7 @@ The following options are provided by the time scale. You may also set options p
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
+| `adapters.date` | `object` | `{}` | Options for adapter for external date library if that adapter needs or supports options
| `distribution` | `string` | `'linear'` | How data is plotted. [more...](#scale-distribution)
| `bounds` | `string` | `'data'` | Determines the scale bounds. [more...](#scale-bounds)
| `ticks.source` | `string` | `'auto'` | How ticks are generated. [more...](#ticks-source) | true |
Other | chartjs | Chart.js | f2b099b835bf5d6dfe3a7d3097997ec11983c3ed.json | Initialize date adapter with chart options (#6016) | docs/getting-started/integration.md | @@ -25,7 +25,7 @@ import Chart from 'chart.js';
var myChart = new Chart(ctx, {...});
```
-**Note:** Moment.js is installed along Chart.js as dependency. If you don't want to use Momemt.js (either because you use a different date adapter or simply because don't need time functionalities), you will have to configure your bundler to exclude this dependency (e.g. using [`externals` for Webpack](https://webpack.js.org/configuration/externals/) or [`external` for Rollup](https://rollupjs.org/guide/en#peer-dependencies)).
+**Note:** Moment.js is installed along Chart.js as dependency. If you don't want to use Moment.js (either because you use a different date adapter or simply because don't need time functionalities), you will have to configure your bundler to exclude this dependency (e.g. using [`externals` for Webpack](https://webpack.js.org/configuration/externals/) or [`external` for Rollup](https://rollupjs.org/guide/en#peer-dependencies)).
```javascript
// Webpack | true |
Other | chartjs | Chart.js | f2b099b835bf5d6dfe3a7d3097997ec11983c3ed.json | Initialize date adapter with chart options (#6016) | src/adapters/adapter.moment.js | @@ -3,8 +3,7 @@
'use strict';
var moment = require('moment');
-var adapter = require('../core/core.adapters')._date;
-var helpers = require('../helpers/helpers.core');
+var adapters = require('../core/core.adapters');
var FORMATS = {
datetime: 'MMM D, YYYY, h:mm:ss a',
@@ -19,7 +18,7 @@ var FORMATS = {
year: 'YYYY'
};
-helpers.merge(adapter, moment ? {
+adapters._date.override(moment ? {
_id: 'moment', // DEBUG ONLY
formats: function() { | true |
Other | chartjs | Chart.js | f2b099b835bf5d6dfe3a7d3097997ec11983c3ed.json | Initialize date adapter with chart options (#6016) | src/core/core.adapters.js | @@ -6,6 +6,8 @@
'use strict';
+var helpers = require('../helpers/index');
+
function abstract() {
throw new Error(
'This method is not implemented: either no adapter can ' +
@@ -27,8 +29,14 @@ function abstract() {
* @name Unit
*/
-/** @lends Chart._adapters._date */
-module.exports._date = {
+/**
+ * @class
+ */
+function DateAdapter(options) {
+ this.options = options || {};
+}
+
+helpers.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
/**
* Returns a map of time formats for the supported formatting units defined
* in Unit as well as 'datetime' representing a detailed date/time string.
@@ -104,4 +112,10 @@ module.exports._date = {
_create: function(value) {
return value;
}
+});
+
+DateAdapter.override = function(members) {
+ helpers.extend(DateAdapter.prototype, members);
};
+
+module.exports._date = DateAdapter; | true |
Other | chartjs | Chart.js | f2b099b835bf5d6dfe3a7d3097997ec11983c3ed.json | Initialize date adapter with chart options (#6016) | src/scales/scale.time.js | @@ -1,6 +1,6 @@
'use strict';
-var adapter = require('../core/core.adapters')._date;
+var adapters = require('../core/core.adapters');
var defaults = require('../core/core.defaults');
var helpers = require('../helpers/index');
var Scale = require('../core/core.scale');
@@ -177,7 +177,9 @@ function interpolate(table, skey, sval, tkey) {
return prev[tkey] + offset;
}
-function toTimestamp(input, options) {
+function toTimestamp(scale, input) {
+ var adapter = scale._adapter;
+ var options = scale.options.time;
var parser = options.parser;
var format = parser || options.format;
var value = input;
@@ -211,19 +213,19 @@ function toTimestamp(input, options) {
return value;
}
-function parse(input, scale) {
+function parse(scale, input) {
if (helpers.isNullOrUndef(input)) {
return null;
}
var options = scale.options.time;
- var value = toTimestamp(scale.getRightValue(input), options);
+ var value = toTimestamp(scale, scale.getRightValue(input));
if (value === null) {
return value;
}
if (options.round) {
- value = +adapter.startOf(value, options.round);
+ value = +scale._adapter.startOf(value, options.round);
}
return value;
@@ -276,13 +278,13 @@ function determineUnitForAutoTicks(minUnit, min, max, capacity) {
/**
* Figures out what unit to format a set of ticks with
*/
-function determineUnitForFormatting(ticks, minUnit, min, max) {
+function determineUnitForFormatting(scale, ticks, minUnit, min, max) {
var ilen = UNITS.length;
var i, unit;
for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) {
unit = UNITS[i];
- if (INTERVALS[unit].common && adapter.diff(max, min, unit) >= ticks.length) {
+ if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= ticks.length) {
return unit;
}
}
@@ -304,7 +306,9 @@ function determineMajorUnit(unit) {
* Important: this method can return ticks outside the min and max range, it's the
* responsibility of the calling code to clamp values if needed.
*/
-function generate(min, max, capacity, options) {
+function generate(scale, min, max, capacity) {
+ var adapter = scale._adapter;
+ var options = scale.options;
var timeOpts = options.time;
var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
var major = determineMajorUnit(minor);
@@ -388,13 +392,13 @@ function computeOffsets(table, ticks, min, max, options) {
return {start: start, end: end};
}
-function ticksFromTimestamps(values, majorUnit) {
+function ticksFromTimestamps(scale, values, majorUnit) {
var ticks = [];
var i, ilen, value, major;
for (i = 0, ilen = values.length; i < ilen; ++i) {
value = values[i];
- major = majorUnit ? value === +adapter.startOf(value, majorUnit) : false;
+ major = majorUnit ? value === +scale._adapter.startOf(value, majorUnit) : false;
ticks.push({
value: value,
@@ -426,6 +430,7 @@ var defaultConfig = {
*/
bounds: 'data',
+ adapters: {},
time: {
parser: false, // false == a pattern string from https://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment
format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from https://momentjs.com/docs/#/parsing/string-format/
@@ -465,6 +470,7 @@ module.exports = Scale.extend({
var me = this;
var options = me.options;
var time = options.time || (options.time = {});
+ var adapter = me._adapter = new adapters._date(options.adapters.date);
// DEPRECATIONS: output a message only one time per update
if (time.format) {
@@ -493,6 +499,7 @@ module.exports = Scale.extend({
determineDataLimits: function() {
var me = this;
var chart = me.chart;
+ var adapter = me._adapter;
var timeOpts = me.options.time;
var unit = timeOpts.unit || 'day';
var min = MAX_INTEGER;
@@ -505,7 +512,7 @@ module.exports = Scale.extend({
// Convert labels to timestamps
for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
- labels.push(parse(dataLabels[i], me));
+ labels.push(parse(me, dataLabels[i]));
}
// Convert data to timestamps
@@ -518,7 +525,7 @@ module.exports = Scale.extend({
datasets[i] = [];
for (j = 0, jlen = data.length; j < jlen; ++j) {
- timestamp = parse(data[j], me);
+ timestamp = parse(me, data[j]);
timestamps.push(timestamp);
datasets[i][j] = timestamp;
}
@@ -546,8 +553,8 @@ module.exports = Scale.extend({
max = Math.max(max, timestamps[timestamps.length - 1]);
}
- min = parse(timeOpts.min, me) || min;
- max = parse(timeOpts.max, me) || max;
+ min = parse(me, timeOpts.min) || min;
+ max = parse(me, timeOpts.max) || max;
// In case there is no valid min/max, set limits based on unit time option
min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
@@ -586,7 +593,7 @@ module.exports = Scale.extend({
break;
case 'auto':
default:
- timestamps = generate(min, max, me.getLabelCapacity(min), options);
+ timestamps = generate(me, min, max, me.getLabelCapacity(min), options);
}
if (options.bounds === 'ticks' && timestamps.length) {
@@ -595,8 +602,8 @@ module.exports = Scale.extend({
}
// Enforce limits with user min/max options
- min = parse(timeOpts.min, me) || min;
- max = parse(timeOpts.max, me) || max;
+ min = parse(me, timeOpts.min) || min;
+ max = parse(me, timeOpts.max) || max;
// Remove ticks outside the min/max range
for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
@@ -610,7 +617,7 @@ module.exports = Scale.extend({
me.max = max;
// PRIVATE
- me._unit = timeOpts.unit || determineUnitForFormatting(ticks, timeOpts.minUnit, me.min, me.max);
+ me._unit = timeOpts.unit || determineUnitForFormatting(me, ticks, timeOpts.minUnit, me.min, me.max);
me._majorUnit = determineMajorUnit(me._unit);
me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
me._offsets = computeOffsets(me._table, ticks, min, max, options);
@@ -619,11 +626,12 @@ module.exports = Scale.extend({
ticks.reverse();
}
- return ticksFromTimestamps(ticks, me._majorUnit);
+ return ticksFromTimestamps(me, ticks, me._majorUnit);
},
getLabelForIndex: function(index, datasetIndex) {
var me = this;
+ var adapter = me._adapter;
var data = me.chart.data;
var timeOpts = me.options.time;
var label = data.labels && index < data.labels.length ? data.labels[index] : '';
@@ -633,12 +641,12 @@ module.exports = Scale.extend({
label = me.getRightValue(value);
}
if (timeOpts.tooltipFormat) {
- return adapter.format(toTimestamp(label, timeOpts), timeOpts.tooltipFormat);
+ return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
}
if (typeof label === 'string') {
return label;
}
- return adapter.format(toTimestamp(label, timeOpts), timeOpts.displayFormats.datetime);
+ return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
},
/**
@@ -647,6 +655,7 @@ module.exports = Scale.extend({
*/
tickFormatFunction: function(time, index, ticks, format) {
var me = this;
+ var adapter = me._adapter;
var options = me.options;
var formats = options.time.displayFormats;
var minorFormat = formats[me._unit];
@@ -696,7 +705,7 @@ module.exports = Scale.extend({
}
if (time === null) {
- time = parse(value, me);
+ time = parse(me, value);
}
if (time !== null) {
@@ -719,7 +728,7 @@ module.exports = Scale.extend({
var time = interpolate(me._table, 'pos', pos, 'time');
// DEPRECATION, we should return time directly
- return adapter._create(time);
+ return me._adapter._create(time);
},
/** | true |
Other | chartjs | Chart.js | f2b099b835bf5d6dfe3a7d3097997ec11983c3ed.json | Initialize date adapter with chart options (#6016) | test/specs/scale.time.tests.js | @@ -76,6 +76,7 @@ describe('Time scale tests', function() {
scaleLabel: Chart.defaults.scale.scaleLabel,
bounds: 'data',
distribution: 'linear',
+ adapters: {},
ticks: {
beginAtZero: false,
minRotation: 0, | true |
Other | chartjs | Chart.js | 1c01272c9af8261a114524e6781e5e67105735fb.json | Improve autoSkip documentation (#6079) | docs/axes/cartesian/README.md | @@ -26,8 +26,8 @@ The following options are common to all cartesian axes but do not apply to other
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
-| `autoSkip` | `boolean` | `true` | If true, automatically calculates how many labels that can be shown and hides labels accordingly. Turn it off to show all labels no matter what.
-| `autoSkipPadding` | `number` | `0` | Padding between the ticks on the horizontal axis when `autoSkip` is enabled. *Note: Only applicable to horizontal scales.*
+| `autoSkip` | `boolean` | `true` | If true, automatically calculates how many labels can be shown and hides labels accordingly. Labels will be rotated up to `maxRotation` before skipping any. Turn `autoSkip` off to show all labels no matter what.
+| `autoSkipPadding` | `number` | `0` | Padding between the ticks on the horizontal axis when `autoSkip` is enabled.
| `labelOffset` | `number` | `0` | Distance in pixels to offset the label from the centre point of the tick (in the x direction for the x axis, and the y direction for the y axis). *Note: this can cause labels at the edges to be cropped by the edge of the canvas*
| `maxRotation` | `number` | `90` | Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. *Note: Only applicable to horizontal scales.*
| `minRotation` | `number` | `0` | Minimum rotation for tick labels. *Note: Only applicable to horizontal scales.* | false |
Other | chartjs | Chart.js | 32aeeac82cdc371b6eb15e0b3442d307e2f36df7.json | Add crosshair plugin to extensions page (#6070) | docs/notes/extensions.md | @@ -15,6 +15,7 @@ In addition, many charts can be found on the [npm registry](https://www.npmjs.co
- <a href="https://github.com/chartjs/chartjs-plugin-annotation" target="_blank">chartjs-plugin-annotation</a> - Draws lines and boxes on chart area.
- <a href="https://github.com/nagix/chartjs-plugin-colorschemes" target="_blank">chartjs-plugin-colorschemes</a> - Enables automatic coloring using predefined color schemes.
+ - <a href="https://github.com/abelheinsbroek/chartjs-plugin-crosshair" target="_blank">chartjs-plugin-crosshair</a> - Adds a data crosshair to line and scatter charts
- <a href="https://github.com/chartjs/chartjs-plugin-datalabels" target="_blank">chartjs-plugin-datalabels</a> - Displays labels on data for any type of charts.
- <a href="https://github.com/chartjs/chartjs-plugin-deferred" target="_blank">chartjs-plugin-deferred</a> - Defers initial chart update until chart scrolls into viewport.
- <a href="https://github.com/compwright/chartjs-plugin-draggable" target="_blank">chartjs-plugin-draggable</a> - Makes select chart elements draggable with the mouse. | false |
Other | chartjs | Chart.js | 58d7891ba23f154d3d799445c7ccb6dda2926468.json | Add examples of scriptable charts (#6042)
* Add example of scriptable pie chart
* Add example of scriptable line chart
* Add example of scriptable polar area chart
* Add example of scriptable radar chart | samples/samples.js | @@ -181,6 +181,18 @@
}, {
title: 'Bubble Chart',
path: 'scriptable/bubble.html'
+ }, {
+ title: 'Pie Chart',
+ path: 'scriptable/pie.html'
+ }, {
+ title: 'Line Chart',
+ path: 'scriptable/line.html'
+ }, {
+ title: 'Polar Area Chart',
+ path: 'scriptable/polar.html'
+ }, {
+ title: 'Radar Chart',
+ path: 'scriptable/radar.html'
}]
}, {
title: 'Advanced', | true |
Other | chartjs | Chart.js | 58d7891ba23f154d3d799445c7ccb6dda2926468.json | Add examples of scriptable charts (#6042)
* Add example of scriptable pie chart
* Add example of scriptable line chart
* Add example of scriptable polar area chart
* Add example of scriptable radar chart | samples/scriptable/line.html | @@ -0,0 +1,115 @@
+<!DOCTYPE html>
+<html lang="en-US">
+<head>
+ <meta charset="utf-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=Edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Scriptable > Line | Chart.js sample</title>
+ <link rel="stylesheet" type="text/css" href="../style.css">
+ <script src="../../dist/Chart.min.js"></script>
+ <script src="../utils.js"></script>
+</head>
+<body>
+ <div class="content">
+ <div class="wrapper"><canvas id="chart-0"></canvas></div>
+ <div class="toolbar">
+ <button onclick="randomize(this)">Randomize</button>
+ <button onclick="addDataset(this)">Add Dataset</button>
+ <button onclick="removeDataset(this)">Remove Dataset</button>
+ </div>
+ </div>
+
+ <script>
+ var DATA_COUNT = 12;
+
+ var utils = Samples.utils;
+
+ utils.srand(110);
+
+ function alternatePointStyles(ctx) {
+ var index = ctx.dataIndex;
+ return index % 2 === 0 ? 'circle' : 'rect';
+ }
+
+ function makeHalfAsOpaque(ctx) {
+ var c = ctx.dataset.backgroundColor;
+ return utils.transparentize(c);
+ }
+
+ function adjustRadiusBasedOnData(ctx) {
+ var v = ctx.dataset.data[ctx.dataIndex];
+ return v < 10 ? 5
+ : v < 25 ? 7
+ : v < 50 ? 9
+ : v < 75 ? 11
+ : 15;
+ }
+
+ function generateData() {
+ return utils.numbers({
+ count: DATA_COUNT,
+ min: 0,
+ max: 100
+ });
+ }
+
+ var data = {
+ labels: utils.months({count: DATA_COUNT}),
+ datasets: [{
+ data: generateData(),
+ backgroundColor: '#4dc9f6',
+ borderColor: '#4dc9f6',
+ }]
+ };
+
+ var options = {
+ legend: false,
+ tooltips: true,
+ elements: {
+ line: {
+ fill: false,
+ },
+ point: {
+ hoverBackgroundColor: makeHalfAsOpaque,
+ radius: adjustRadiusBasedOnData,
+ pointStyle: alternatePointStyles,
+ hoverRadius: 15,
+ }
+ }
+ };
+
+ var chart = new Chart('chart-0', {
+ type: 'line',
+ data: data,
+ options: options
+ });
+
+
+ // eslint-disable-next-line no-unused-vars
+ function addDataset() {
+ var newColor = utils.color(chart.data.datasets.length);
+
+ chart.data.datasets.push({
+ data: generateData(),
+ backgroundColor: newColor,
+ borderColor: newColor
+ });
+ chart.update();
+ }
+
+ // eslint-disable-next-line no-unused-vars
+ function randomize() {
+ chart.data.datasets.forEach(function(dataset) {
+ dataset.data = generateData();
+ });
+ chart.update();
+ }
+
+ // eslint-disable-next-line no-unused-vars
+ function removeDataset() {
+ chart.data.datasets.shift();
+ chart.update();
+ }
+ </script>
+</body>
+</html> | true |
Other | chartjs | Chart.js | 58d7891ba23f154d3d799445c7ccb6dda2926468.json | Add examples of scriptable charts (#6042)
* Add example of scriptable pie chart
* Add example of scriptable line chart
* Add example of scriptable polar area chart
* Add example of scriptable radar chart | samples/scriptable/pie.html | @@ -0,0 +1,110 @@
+<!DOCTYPE html>
+<html lang="en-US">
+<head>
+ <meta charset="utf-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=Edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Scriptable > Pie | Chart.js sample</title>
+ <link rel="stylesheet" type="text/css" href="../style.css">
+ <script src="../../dist/Chart.min.js"></script>
+ <script src="../utils.js"></script>
+</head>
+<body>
+ <div class="content">
+ <div class="wrapper"><canvas id="chart-0"></canvas></div>
+ <div class="toolbar">
+ <button onclick="randomize()">Randomize</button>
+ <button onclick="addDataset()">Add Dataset</button>
+ <button onclick="removeDataset()">Remove Dataset</button>
+ <button onclick="togglePieDoughnut()">Toggle Doughnut View</button>
+ </div>
+ </div>
+ <script>
+ var DATA_COUNT = 5;
+
+ var utils = Samples.utils;
+
+ utils.srand(110);
+
+ function colorize(opaque, hover, ctx) {
+ var v = ctx.dataset.data[ctx.dataIndex];
+ var c = v < -50 ? '#D60000'
+ : v < 0 ? '#F46300'
+ : v < 50 ? '#0358B6'
+ : '#44DE28';
+
+ var opacity = hover ? 1 - Math.abs(v / 150) - 0.2 : 1 - Math.abs(v / 150);
+
+ return opaque ? c : utils.transparentize(c, opacity);
+ }
+
+ function hoverColorize(ctx) {
+ return colorize(false, true, ctx);
+ }
+
+ function generateData() {
+ return utils.numbers({
+ count: DATA_COUNT,
+ min: -100,
+ max: 100
+ });
+ }
+
+ var data = {
+ datasets: [{
+ data: generateData(),
+ }]
+ };
+
+ var options = {
+ legend: false,
+ tooltips: false,
+ elements: {
+ arc: {
+ backgroundColor: colorize.bind(null, false, false),
+ hoverBackgroundColor: hoverColorize
+ }
+ }
+ };
+
+ var chart = new Chart('chart-0', {
+ type: 'pie',
+ data: data,
+ options: options
+ });
+
+ // eslint-disable-next-line no-unused-vars
+ function randomize() {
+ chart.data.datasets.forEach(function(dataset) {
+ dataset.data = generateData();
+ });
+ chart.update();
+ }
+
+ // eslint-disable-next-line no-unused-vars
+ function addDataset() {
+ chart.data.datasets.push({
+ data: generateData()
+ });
+ chart.update();
+ }
+
+ // eslint-disable-next-line no-unused-vars
+ function removeDataset() {
+ chart.data.datasets.shift();
+ chart.update();
+ }
+
+ // eslint-disable-next-line no-unused-vars
+ function togglePieDoughnut() {
+ if (chart.options.cutoutPercentage) {
+ chart.options.cutoutPercentage = 0;
+ } else {
+ chart.options.cutoutPercentage = 50;
+ }
+ chart.update();
+ }
+
+ </script>
+</body>
+</html> | true |
Other | chartjs | Chart.js | 58d7891ba23f154d3d799445c7ccb6dda2926468.json | Add examples of scriptable charts (#6042)
* Add example of scriptable pie chart
* Add example of scriptable line chart
* Add example of scriptable polar area chart
* Add example of scriptable radar chart | samples/scriptable/polar.html | @@ -0,0 +1,98 @@
+<!DOCTYPE html>
+<html lang="en-US">
+<head>
+ <meta charset="utf-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=Edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Scriptable > Polar Area | Chart.js sample</title>
+ <link rel="stylesheet" type="text/css" href="../style.css">
+ <script src="../../dist/Chart.min.js"></script>
+ <script src="../utils.js"></script>
+</head>
+<body>
+ <div class="content">
+ <div class="wrapper"><canvas id="chart-0"></canvas></div>
+ <div class="toolbar">
+ <button onclick="randomize()">Randomize</button>
+ <button onclick="addData()">Add Data</button>
+ <button onclick="removeData()">Remove Data</button>
+ </div>
+ </div>
+ <script>
+ var DATA_COUNT = 7;
+
+ var utils = Samples.utils;
+
+ utils.srand(110);
+
+ function colorize(opaque, hover, ctx) {
+ var v = ctx.dataset.data[ctx.dataIndex];
+ var c = v < 35 ? '#D60000'
+ : v < 55 ? '#F46300'
+ : v < 75 ? '#0358B6'
+ : '#44DE28';
+
+ var opacity = hover ? 1 - Math.abs(v / 150) - 0.2 : 1 - Math.abs(v / 150);
+
+ return opaque ? c : utils.transparentize(c, opacity);
+ }
+
+ function hoverColorize(ctx) {
+ return colorize(false, true, ctx);
+ }
+
+ function generateData() {
+ return utils.numbers({
+ count: DATA_COUNT,
+ min: 0,
+ max: 100
+ });
+ }
+
+ var data = {
+ datasets: [{
+ data: generateData(),
+ }]
+ };
+
+ var options = {
+ legend: false,
+ tooltips: false,
+ elements: {
+ arc: {
+ backgroundColor: colorize.bind(null, false, false),
+ hoverBackgroundColor: hoverColorize
+ }
+ }
+ };
+
+ var chart = new Chart('chart-0', {
+ type: 'polarArea',
+ data: data,
+ options: options
+ });
+
+ // eslint-disable-next-line no-unused-vars
+ function randomize() {
+ chart.data.datasets.forEach(function(dataset) {
+ dataset.data = generateData();
+ });
+ chart.update();
+ }
+
+ // eslint-disable-next-line no-unused-vars
+ var addData = function() {
+ var newData = Math.round(Math.random() * 100);
+ chart.data.datasets[0].data.push(newData);
+ chart.update();
+ };
+
+ // eslint-disable-next-line no-unused-vars
+ function removeData() {
+ chart.data.datasets[0].data.pop();
+ chart.update();
+ }
+
+ </script>
+</body>
+</html> | true |
Other | chartjs | Chart.js | 58d7891ba23f154d3d799445c7ccb6dda2926468.json | Add examples of scriptable charts (#6042)
* Add example of scriptable pie chart
* Add example of scriptable line chart
* Add example of scriptable polar area chart
* Add example of scriptable radar chart | samples/scriptable/radar.html | @@ -0,0 +1,112 @@
+<!DOCTYPE html>
+<html lang="en-US">
+<head>
+ <meta charset="utf-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=Edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Scriptable > Radar | Chart.js sample</title>
+ <link rel="stylesheet" type="text/css" href="../style.css">
+ <script src="../../dist/Chart.min.js"></script>
+ <script src="../utils.js"></script>
+</head>
+<body>
+ <div class="content">
+ <div class="wrapper"><canvas id="chart-0"></canvas></div>
+ <div class="toolbar">
+ <button onclick="randomize(this)">Randomize</button>
+ <button onclick="addDataset(this)">Add Dataset</button>
+ <button onclick="removeDataset(this)">Remove Dataset</button>
+ </div>
+ </div>
+
+ <script>
+ var DATA_COUNT = 7;
+
+ var utils = Samples.utils;
+
+ utils.srand(110);
+
+ function alternatePointStyles(ctx) {
+ var index = ctx.dataIndex;
+ return index % 2 === 0 ? 'circle' : 'rect';
+ }
+
+ function makeHalfAsOpaque(ctx) {
+ var c = ctx.dataset.backgroundColor;
+ return utils.transparentize(c);
+ }
+
+ function adjustRadiusBasedOnData(ctx) {
+ var v = ctx.dataset.data[ctx.dataIndex];
+ return v < 10 ? 5
+ : v < 25 ? 7
+ : v < 50 ? 9
+ : v < 75 ? 11
+ : 15;
+ }
+
+ function generateData() {
+ return utils.numbers({
+ count: DATA_COUNT,
+ min: 0,
+ max: 100
+ });
+ }
+
+ var data = {
+ labels: [['Eating', 'Dinner'], ['Drinking', 'Water'], 'Sleeping', ['Designing', 'Graphics'], 'Coding', 'Cycling', 'Running'],
+ datasets: [{
+ data: generateData(),
+ backgroundColor: Chart.helpers.color('#4dc9f6').alpha(0.2).rgbString(),
+ borderColor: '#4dc9f6',
+ }]
+ };
+
+ var options = {
+ legend: false,
+ tooltips: true,
+ elements: {
+ point: {
+ hoverBackgroundColor: makeHalfAsOpaque,
+ radius: adjustRadiusBasedOnData,
+ pointStyle: alternatePointStyles,
+ hoverRadius: 15,
+ }
+ }
+ };
+
+ var chart = new Chart('chart-0', {
+ type: 'radar',
+ data: data,
+ options: options
+ });
+
+
+ // eslint-disable-next-line no-unused-vars
+ function addDataset() {
+ var newColor = utils.color(chart.data.datasets.length);
+
+ chart.data.datasets.push({
+ data: generateData(),
+ backgroundColor: Chart.helpers.color(newColor).alpha(0.2).rgbString(),
+ borderColor: newColor
+ });
+ chart.update();
+ }
+
+ // eslint-disable-next-line no-unused-vars
+ function randomize() {
+ chart.data.datasets.forEach(function(dataset) {
+ dataset.data = generateData();
+ });
+ chart.update();
+ }
+
+ // eslint-disable-next-line no-unused-vars
+ function removeDataset() {
+ chart.data.datasets.shift();
+ chart.update();
+ }
+ </script>
+</body>
+</html> | true |
Other | chartjs | Chart.js | 5fc934eae1237e78f6db3ab065c71ee9412b9047.json | Fix responsive resize on rtl page (#6063) | src/platforms/platform.dom.css | @@ -19,6 +19,7 @@
.chartjs-size-monitor-expand,
.chartjs-size-monitor-shrink {
position: absolute;
+ direction: ltr;
left: 0;
top: 0;
right: 0; | true |
Other | chartjs | Chart.js | 5fc934eae1237e78f6db3ab065c71ee9412b9047.json | Fix responsive resize on rtl page (#6063) | test/specs/core.controller.tests.js | @@ -379,6 +379,46 @@ describe('Chart', function() {
});
});
+ it('should resize the canvas when parent is RTL and width changes', function(done) {
+ var chart = acquireChart({
+ options: {
+ responsive: true,
+ maintainAspectRatio: false
+ }
+ }, {
+ canvas: {
+ style: ''
+ },
+ wrapper: {
+ style: 'width: 300px; height: 350px; position: relative; direction: rtl'
+ }
+ });
+
+ expect(chart).toBeChartOfSize({
+ dw: 300, dh: 350,
+ rw: 300, rh: 350,
+ });
+
+ var wrapper = chart.canvas.parentNode;
+ wrapper.style.width = '455px';
+ waitForResize(chart, function() {
+ expect(chart).toBeChartOfSize({
+ dw: 455, dh: 350,
+ rw: 455, rh: 350,
+ });
+
+ wrapper.style.width = '150px';
+ waitForResize(chart, function() {
+ expect(chart).toBeChartOfSize({
+ dw: 150, dh: 350,
+ rw: 150, rh: 350,
+ });
+
+ done();
+ });
+ });
+ });
+
it('should resize the canvas when parent height changes', function(done) {
var chart = acquireChart({
options: { | true |
Other | chartjs | Chart.js | ef507e11bd6936a0a60cbd66822aa6aef23df828.json | Handle inextensible `dataset.data` array (#6060) | src/core/core.datasetController.js | @@ -225,7 +225,9 @@ helpers.extend(DatasetController.prototype, {
unlistenArrayEvents(me._data, me);
}
- listenArrayEvents(data, me);
+ if (data && Object.isExtensible(data)) {
+ listenArrayEvents(data, me);
+ }
me._data = data;
}
| true |
Other | chartjs | Chart.js | ef507e11bd6936a0a60cbd66822aa6aef23df828.json | Handle inextensible `dataset.data` array (#6060) | test/specs/core.datasetController.tests.js | @@ -38,6 +38,86 @@ describe('Chart.DatasetController', function() {
});
});
+ describe('inextensible data', function() {
+ it('should handle a frozen data object', function() {
+ function createChart() {
+ var data = Object.freeze([0, 1, 2, 3, 4, 5]);
+ expect(Object.isExtensible(data)).toBeFalsy();
+
+ var chart = acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ data: data
+ }]
+ }
+ });
+
+ var dataset = chart.data.datasets[0];
+ dataset.data = Object.freeze([5, 4, 3, 2, 1, 0]);
+ expect(Object.isExtensible(dataset.data)).toBeFalsy();
+ chart.update();
+
+ // Tests that the unlisten path also works for frozen objects
+ chart.destroy();
+ }
+
+ expect(createChart).not.toThrow();
+ });
+
+ it('should handle a sealed data object', function() {
+ function createChart() {
+ var data = Object.seal([0, 1, 2, 3, 4, 5]);
+ expect(Object.isExtensible(data)).toBeFalsy();
+
+ var chart = acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ data: data
+ }]
+ }
+ });
+
+ var dataset = chart.data.datasets[0];
+ dataset.data = Object.seal([5, 4, 3, 2, 1, 0]);
+ expect(Object.isExtensible(dataset.data)).toBeFalsy();
+ chart.update();
+
+ // Tests that the unlisten path also works for frozen objects
+ chart.destroy();
+ }
+
+ expect(createChart).not.toThrow();
+ });
+
+ it('should handle an unextendable data object', function() {
+ function createChart() {
+ var data = Object.preventExtensions([0, 1, 2, 3, 4, 5]);
+ expect(Object.isExtensible(data)).toBeFalsy();
+
+ var chart = acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ data: data
+ }]
+ }
+ });
+
+ var dataset = chart.data.datasets[0];
+ dataset.data = Object.preventExtensions([5, 4, 3, 2, 1, 0]);
+ expect(Object.isExtensible(dataset.data)).toBeFalsy();
+ chart.update();
+
+ // Tests that the unlisten path also works for frozen objects
+ chart.destroy();
+ }
+
+ expect(createChart).not.toThrow();
+ });
+ });
+
it('should synchronize metadata when data are inserted or removed', function() {
var data = [0, 1, 2, 3, 4, 5];
var chart = acquireChart({ | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | .gitignore | @@ -9,6 +9,8 @@
/package-lock.json
.DS_Store
.idea
+.project
+.settings
.vscode
bower.json
*.log | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/controllers/controller.bar.js | @@ -190,8 +190,8 @@ module.exports = DatasetController.extend({
/**
* Returns the stacks based on groups and bar visibility.
- * @param {Number} [last] - The dataset index
- * @returns {Array} The stack list
+ * @param {number} [last] - The dataset index
+ * @returns {string[]} The list of stack IDs
* @private
*/
_getStacks: function(last) {
@@ -226,9 +226,9 @@ module.exports = DatasetController.extend({
/**
* Returns the stack index for the given dataset based on groups and bar visibility.
- * @param {Number} [datasetIndex] - The dataset index
- * @param {String} [name] - The stack name to find
- * @returns {Number} The stack index
+ * @param {number} [datasetIndex] - The dataset index
+ * @param {string} [name] - The stack name to find
+ * @returns {number} The stack index
* @private
*/
getStackIndex: function(datasetIndex, name) { | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/controllers/controller.horizontalBar.js | @@ -1,4 +1,3 @@
-
'use strict';
var BarController = require('./controller.bar'); | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/core/core.animations.js | @@ -20,8 +20,8 @@ module.exports = {
/**
* @param {Chart} chart - The chart to animate.
* @param {Chart.Animation} animation - The animation that we will animate.
- * @param {Number} duration - The animation duration in ms.
- * @param {Boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
+ * @param {number} duration - The animation duration in ms.
+ * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
*/
addAnimation: function(chart, animation, duration, lazy) {
var animations = this.animations; | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/core/core.controller.js | @@ -736,8 +736,10 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
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
+ /**
+ * 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) {
return Interaction.modes.single(this, e);
},
@@ -970,7 +972,7 @@ helpers.extend(Chart.prototype, /** @lends Chart */ {
* Handle an event
* @private
* @param {IEvent} event the event to handle
- * @return {Boolean} true if the chart needs to re-render
+ * @return {boolean} true if the chart needs to re-render
*/
handleEvent: function(e) {
var me = this; | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/core/core.helpers.js | @@ -123,8 +123,8 @@ module.exports = function() {
/**
* 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.
+ * @param {number} x - A number.
+ * @returns {number} The number of decimal places.
*/
helpers.decimalPlaces = function(x) {
if (!helpers.isFinite(x)) {
@@ -173,9 +173,9 @@ module.exports = function() {
/**
* Returns the aligned pixel value to avoid anti-aliasing blur
* @param {Chart} chart - The chart instance.
- * @param {Number} pixel - A pixel value.
- * @param {Number} width - The width of the element.
- * @returns {Number} The aligned pixel value.
+ * @param {number} pixel - A pixel value.
+ * @param {number} width - The width of the element.
+ * @returns {number} The aligned pixel value.
* @private
*/
helpers._alignPixel = function(chart, pixel, width) {
@@ -430,11 +430,13 @@ module.exports = function() {
return value !== undefined && value !== null && value !== 'none';
}
- // Private helper to get a constraint dimension
- // @param domNode : the node to check the constraint on
- // @param maxStyle : the style that defines the maximum for the direction we are using (maxWidth / maxHeight)
- // @param percentageProperty : property of parent to use when calculating width as a percentage
- // @see https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser
+ /**
+ * 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); | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/core/core.interaction.js | @@ -6,7 +6,7 @@ var helpers = require('../helpers/index');
* Helper function to get relative position for an event
* @param {Event|IEvent} event - The event to get the position for
* @param {Chart} chart - The chart
- * @returns {Point} the event position
+ * @returns {object} the event position
*/
function getRelativePosition(e, chart) {
if (e.native) {
@@ -21,8 +21,8 @@ function getRelativePosition(e, chart) {
/**
* Helper function to traverse all of the visible elements in the chart
- * @param chart {chart} the chart
- * @param handler {Function} the callback to execute for each visible item
+ * @param {Chart} chart - the chart
+ * @param {function} handler - the callback to execute for each visible item
*/
function parseVisibleItems(chart, handler) {
var datasets = chart.data.datasets;
@@ -45,8 +45,8 @@ function parseVisibleItems(chart, handler) {
/**
* Helper function to get the items that intersect the event position
- * @param items {ChartElement[]} elements to filter
- * @param position {Point} the point to be nearest to
+ * @param {ChartElement[]} items - elements to filter
+ * @param {object} position - the point to be nearest to
* @return {ChartElement[]} the nearest items
*/
function getIntersectItems(chart, position) {
@@ -63,10 +63,10 @@ function getIntersectItems(chart, position) {
/**
* Helper function to get the items nearest to the event position considering all visible items in teh chart
- * @param chart {Chart} the chart to look at elements from
- * @param position {Point} the point to be nearest to
- * @param intersect {Boolean} if true, only consider items that intersect the position
- * @param distanceMetric {Function} function to provide the distance between points
+ * @param {Chart} chart - the chart to look at elements from
+ * @param {object} position - the point to be nearest to
+ * @param {boolean} intersect - if true, only consider items that intersect the position
+ * @param {function} distanceMetric - function to provide the distance between points
* @return {ChartElement[]} the nearest items
*/
function getNearestItems(chart, position, intersect, distanceMetric) {
@@ -80,7 +80,6 @@ function getNearestItems(chart, position, intersect, distanceMetric) {
var center = element.getCenterPoint();
var distance = distanceMetric(position, center);
-
if (distance < minDistance) {
nearestItems = [element];
minDistance = distance;
@@ -96,7 +95,7 @@ function getNearestItems(chart, position, intersect, distanceMetric) {
/**
* Get a distance metric function for two points based on the
* axis mode setting
- * @param {String} axis the axis mode. x|y|xy
+ * @param {string} axis - the axis mode. x|y|xy
*/
function getDistanceMetricForAxis(axis) {
var useX = axis.indexOf('x') !== -1;
@@ -179,9 +178,9 @@ module.exports = {
* If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
* @function Chart.Interaction.modes.index
* @since v2.4.0
- * @param chart {chart} the chart we are returning items from
- * @param e {Event} the event we are find things at
- * @param options {IInteractionOptions} options to use during interaction
+ * @param {Chart} chart - the chart we are returning items from
+ * @param {Event} e - the event we are find things at
+ * @param {IInteractionOptions} options - options to use during interaction
* @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
index: indexMode,
@@ -190,9 +189,9 @@ module.exports = {
* Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
* If the options.intersect is false, we find the nearest item and return the items in that dataset
* @function Chart.Interaction.modes.dataset
- * @param chart {chart} the chart we are returning items from
- * @param e {Event} the event we are find things at
- * @param options {IInteractionOptions} options to use during interaction
+ * @param {Chart} chart - the chart we are returning items from
+ * @param {Event} e - the event we are find things at
+ * @param {IInteractionOptions} options - options to use during interaction
* @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
dataset: function(chart, e, options) {
@@ -222,8 +221,8 @@ module.exports = {
* Point mode returns all elements that hit test based on the event position
* of the event
* @function Chart.Interaction.modes.intersect
- * @param chart {chart} the chart we are returning items from
- * @param e {Event} the event we are find things at
+ * @param {Chart} chart - the chart we are returning items from
+ * @param {Event} e - the event we are find things at
* @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
point: function(chart, e) {
@@ -234,9 +233,9 @@ module.exports = {
/**
* nearest mode returns the element closest to the point
* @function Chart.Interaction.modes.intersect
- * @param chart {chart} the chart we are returning items from
- * @param e {Event} the event we are find things at
- * @param options {IInteractionOptions} options to use
+ * @param {Chart} chart - the chart we are returning items from
+ * @param {Event} e - the event we are find things at
+ * @param {IInteractionOptions} options - options to use
* @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
nearest: function(chart, e, options) {
@@ -249,9 +248,9 @@ module.exports = {
/**
* x mode returns the elements that hit-test at the current x coordinate
* @function Chart.Interaction.modes.x
- * @param chart {chart} the chart we are returning items from
- * @param e {Event} the event we are find things at
- * @param options {IInteractionOptions} options to use
+ * @param {Chart} chart - the chart we are returning items from
+ * @param {Event} e - the event we are find things at
+ * @param {IInteractionOptions} options - options to use
* @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
x: function(chart, e, options) {
@@ -280,9 +279,9 @@ module.exports = {
/**
* y mode returns the elements that hit-test at the current y coordinate
* @function Chart.Interaction.modes.y
- * @param chart {chart} the chart we are returning items from
- * @param e {Event} the event we are find things at
- * @param options {IInteractionOptions} options to use
+ * @param {Chart} chart - the chart we are returning items from
+ * @param {Event} e - the event we are find things at
+ * @param {IInteractionOptions} options - options to use
* @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
y: function(chart, e, options) { | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/core/core.layouts.js | @@ -67,19 +67,19 @@ defaults._set('global', {
/**
* @interface ILayoutItem
- * @prop {String} position - The position of the item in the chart layout. Possible values are
+ * @prop {string} position - The position of the item in the chart layout. Possible values are
* 'left', 'top', 'right', 'bottom', and 'chartArea'
- * @prop {Number} weight - The weight used to sort the item. Higher weights are further away from the chart area
- * @prop {Boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
- * @prop {Function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
- * @prop {Function} update - Takes two parameters: width and height. Returns size of item
- * @prop {Function} getPadding - Returns an object with padding on the edges
- * @prop {Number} width - Width of item. Must be valid after update()
- * @prop {Number} height - Height of item. Must be valid after update()
- * @prop {Number} left - Left edge of the item. Set by layout system and cannot be used in update
- * @prop {Number} top - Top edge of the item. Set by layout system and cannot be used in update
- * @prop {Number} right - Right edge of the item. Set by layout system and cannot be used in update
- * @prop {Number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
+ * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
+ * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
+ * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
+ * @prop {function} update - Takes two parameters: width and height. Returns size of item
+ * @prop {function} getPadding - Returns an object with padding on the edges
+ * @prop {number} width - Width of item. Must be valid after update()
+ * @prop {number} height - Height of item. Must be valid after update()
+ * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
+ * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
+ * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
+ * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
*/
// The layout service is very self explanatory. It's responsible for the layout within a chart.
@@ -110,7 +110,7 @@ module.exports = {
/**
* Remove a layoutItem from a chart
* @param {Chart} chart - the chart to remove the box from
- * @param {Object} layoutItem - the item to remove from the layout
+ * @param {ILayoutItem} layoutItem - the item to remove from the layout
*/
removeBox: function(chart, layoutItem) {
var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
@@ -122,8 +122,8 @@ module.exports = {
/**
* Sets (or updates) options on the given `item`.
* @param {Chart} chart - the chart in which the item lives (or will be added to)
- * @param {Object} item - the item to configure with the given options
- * @param {Object} options - the new item options.
+ * @param {ILayoutItem} item - the item to configure with the given options
+ * @param {object} options - the new item options.
*/
configure: function(chart, item, options) {
var props = ['fullWidth', 'position', 'weight'];
@@ -143,8 +143,8 @@ module.exports = {
* Fits boxes of the given chart into the given size by having each box measure itself
* then running a fitting algorithm
* @param {Chart} chart - the chart
- * @param {Number} width - the width to fit into
- * @param {Number} height - the height to fit into
+ * @param {number} width - the width to fit into
+ * @param {number} height - the height to fit into
*/
update: function(chart, width, height) {
if (!chart) { | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/core/core.plugins.js | @@ -29,7 +29,7 @@ module.exports = {
/**
* Registers the given plugin(s) if not already registered.
- * @param {Array|Object} plugins plugin instance(s).
+ * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
*/
register: function(plugins) {
var p = this._plugins;
@@ -44,7 +44,7 @@ module.exports = {
/**
* Unregisters the given plugin(s) only if registered.
- * @param {Array|Object} plugins plugin instance(s).
+ * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
*/
unregister: function(plugins) {
var p = this._plugins;
@@ -69,7 +69,7 @@ module.exports = {
/**
* Returns the number of registered plugins?
- * @returns {Number}
+ * @returns {number}
* @since 2.1.5
*/
count: function() {
@@ -78,7 +78,7 @@ module.exports = {
/**
* Returns all registered plugin instances.
- * @returns {Array} array of plugin objects.
+ * @returns {IPlugin[]} array of plugin objects.
* @since 2.1.5
*/
getAll: function() {
@@ -89,10 +89,10 @@ module.exports = {
* Calls enabled plugins for `chart` on the specified hook and with the given args.
* This method immediately returns as soon as a plugin explicitly returns false. The
* returned value can be used, for instance, to interrupt the current action.
- * @param {Object} chart - The chart instance for which plugins should be called.
- * @param {String} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
+ * @param {Chart} chart - The chart instance for which plugins should be called.
+ * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
* @param {Array} [args] - Extra arguments to apply to the hook call.
- * @returns {Boolean} false if any of the plugins return false, else returns true.
+ * @returns {boolean} false if any of the plugins return false, else returns true.
*/
notify: function(chart, hook, args) {
var descriptors = this.descriptors(chart);
@@ -117,7 +117,7 @@ module.exports = {
/**
* Returns descriptors of enabled plugins for the given chart.
- * @returns {Array} [{ plugin, options }]
+ * @returns {object[]} [{ plugin, options }]
* @private
*/
descriptors: function(chart) {
@@ -179,204 +179,204 @@ module.exports = {
* @method IPlugin#beforeInit
* @desc Called before initializing `chart`.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Object} options - The plugin options.
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#afterInit
* @desc Called after `chart` has been initialized and before the first update.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Object} options - The plugin options.
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#beforeUpdate
* @desc Called before updating `chart`. If any plugin returns `false`, the update
* is cancelled (and thus subsequent render(s)) until another `update` is triggered.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Object} options - The plugin options.
- * @returns {Boolean} `false` to cancel the chart update.
+ * @param {object} options - The plugin options.
+ * @returns {boolean} `false` to cancel the chart update.
*/
/**
* @method IPlugin#afterUpdate
* @desc Called after `chart` has been updated and before rendering. Note that this
* hook will not be called if the chart update has been previously cancelled.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Object} options - The plugin options.
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#beforeDatasetsUpdate
* @desc Called before updating the `chart` datasets. If any plugin returns `false`,
* the datasets update is cancelled until another `update` is triggered.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Object} options - The plugin options.
- * @returns {Boolean} false to cancel the datasets update.
+ * @param {object} options - The plugin options.
+ * @returns {boolean} false to cancel the datasets update.
* @since version 2.1.5
*/
/**
* @method IPlugin#afterDatasetsUpdate
* @desc Called after the `chart` datasets have been updated. Note that this hook
* will not be called if the datasets update has been previously cancelled.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Object} options - The plugin options.
+ * @param {object} options - The plugin options.
* @since version 2.1.5
*/
/**
* @method IPlugin#beforeDatasetUpdate
* @desc Called before updating the `chart` dataset at the given `args.index`. If any plugin
* returns `false`, the datasets update is cancelled until another `update` is triggered.
* @param {Chart} chart - The chart instance.
- * @param {Object} args - The call arguments.
- * @param {Number} args.index - The dataset index.
- * @param {Object} args.meta - The dataset metadata.
- * @param {Object} options - The plugin options.
- * @returns {Boolean} `false` to cancel the chart datasets drawing.
+ * @param {object} args - The call arguments.
+ * @param {number} args.index - The dataset index.
+ * @param {object} args.meta - The dataset metadata.
+ * @param {object} options - The plugin options.
+ * @returns {boolean} `false` to cancel the chart datasets drawing.
*/
/**
* @method IPlugin#afterDatasetUpdate
* @desc Called after the `chart` datasets at the given `args.index` has been updated. Note
* that this hook will not be called if the datasets update has been previously cancelled.
* @param {Chart} chart - The chart instance.
- * @param {Object} args - The call arguments.
- * @param {Number} args.index - The dataset index.
- * @param {Object} args.meta - The dataset metadata.
- * @param {Object} options - The plugin options.
+ * @param {object} args - The call arguments.
+ * @param {number} args.index - The dataset index.
+ * @param {object} args.meta - The dataset metadata.
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#beforeLayout
* @desc Called before laying out `chart`. If any plugin returns `false`,
* the layout update is cancelled until another `update` is triggered.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Object} options - The plugin options.
- * @returns {Boolean} `false` to cancel the chart layout.
+ * @param {object} options - The plugin options.
+ * @returns {boolean} `false` to cancel the chart layout.
*/
/**
* @method IPlugin#afterLayout
* @desc Called after the `chart` has been layed out. Note that this hook will not
* be called if the layout update has been previously cancelled.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Object} options - The plugin options.
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#beforeRender
* @desc Called before rendering `chart`. If any plugin returns `false`,
* the rendering is cancelled until another `render` is triggered.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Object} options - The plugin options.
- * @returns {Boolean} `false` to cancel the chart rendering.
+ * @param {object} options - The plugin options.
+ * @returns {boolean} `false` to cancel the chart rendering.
*/
/**
* @method IPlugin#afterRender
* @desc Called after the `chart` has been fully rendered (and animation completed). Note
* that this hook will not be called if the rendering has been previously cancelled.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Object} options - The plugin options.
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#beforeDraw
* @desc Called before drawing `chart` at every animation frame specified by the given
* easing value. If any plugin returns `false`, the frame drawing is cancelled until
* another `render` is triggered.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
- * @param {Object} options - The plugin options.
- * @returns {Boolean} `false` to cancel the chart drawing.
+ * @param {number} easingValue - The current animation value, between 0.0 and 1.0.
+ * @param {object} options - The plugin options.
+ * @returns {boolean} `false` to cancel the chart drawing.
*/
/**
* @method IPlugin#afterDraw
* @desc Called after the `chart` has been drawn for the specific easing value. Note
* that this hook will not be called if the drawing has been previously cancelled.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
- * @param {Object} options - The plugin options.
+ * @param {number} easingValue - The current animation value, between 0.0 and 1.0.
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#beforeDatasetsDraw
* @desc Called before drawing the `chart` datasets. If any plugin returns `false`,
* the datasets drawing is cancelled until another `render` is triggered.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
- * @param {Object} options - The plugin options.
- * @returns {Boolean} `false` to cancel the chart datasets drawing.
+ * @param {number} easingValue - The current animation value, between 0.0 and 1.0.
+ * @param {object} options - The plugin options.
+ * @returns {boolean} `false` to cancel the chart datasets drawing.
*/
/**
* @method IPlugin#afterDatasetsDraw
* @desc Called after the `chart` datasets have been drawn. Note that this hook
* will not be called if the datasets drawing has been previously cancelled.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Number} easingValue - The current animation value, between 0.0 and 1.0.
- * @param {Object} options - The plugin options.
+ * @param {number} easingValue - The current animation value, between 0.0 and 1.0.
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#beforeDatasetDraw
* @desc Called before drawing the `chart` dataset at the given `args.index` (datasets
* are drawn in the reverse order). If any plugin returns `false`, the datasets drawing
* is cancelled until another `render` is triggered.
* @param {Chart} chart - The chart instance.
- * @param {Object} args - The call arguments.
- * @param {Number} args.index - The dataset index.
- * @param {Object} args.meta - The dataset metadata.
- * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
- * @param {Object} options - The plugin options.
- * @returns {Boolean} `false` to cancel the chart datasets drawing.
+ * @param {object} args - The call arguments.
+ * @param {number} args.index - The dataset index.
+ * @param {object} args.meta - The dataset metadata.
+ * @param {number} args.easingValue - The current animation value, between 0.0 and 1.0.
+ * @param {object} options - The plugin options.
+ * @returns {boolean} `false` to cancel the chart datasets drawing.
*/
/**
* @method IPlugin#afterDatasetDraw
* @desc Called after the `chart` datasets at the given `args.index` have been drawn
* (datasets are drawn in the reverse order). Note that this hook will not be called
* if the datasets drawing has been previously cancelled.
* @param {Chart} chart - The chart instance.
- * @param {Object} args - The call arguments.
- * @param {Number} args.index - The dataset index.
- * @param {Object} args.meta - The dataset metadata.
- * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
- * @param {Object} options - The plugin options.
+ * @param {object} args - The call arguments.
+ * @param {number} args.index - The dataset index.
+ * @param {object} args.meta - The dataset metadata.
+ * @param {number} args.easingValue - The current animation value, between 0.0 and 1.0.
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#beforeTooltipDraw
* @desc Called before drawing the `tooltip`. If any plugin returns `false`,
* the tooltip drawing is cancelled until another `render` is triggered.
* @param {Chart} chart - The chart instance.
- * @param {Object} args - The call arguments.
- * @param {Object} args.tooltip - The tooltip.
- * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
- * @param {Object} options - The plugin options.
- * @returns {Boolean} `false` to cancel the chart tooltip drawing.
+ * @param {object} args - The call arguments.
+ * @param {Tooltip} args.tooltip - The tooltip.
+ * @param {number} args.easingValue - The current animation value, between 0.0 and 1.0.
+ * @param {object} options - The plugin options.
+ * @returns {boolean} `false` to cancel the chart tooltip drawing.
*/
/**
* @method IPlugin#afterTooltipDraw
* @desc Called after drawing the `tooltip`. Note that this hook will not
* be called if the tooltip drawing has been previously cancelled.
* @param {Chart} chart - The chart instance.
- * @param {Object} args - The call arguments.
- * @param {Object} args.tooltip - The tooltip.
- * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0.
- * @param {Object} options - The plugin options.
+ * @param {object} args - The call arguments.
+ * @param {Tooltip} args.tooltip - The tooltip.
+ * @param {number} args.easingValue - The current animation value, between 0.0 and 1.0.
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#beforeEvent
* @desc Called before processing the specified `event`. If any plugin returns `false`,
* the event will be discarded.
* @param {Chart.Controller} chart - The chart instance.
* @param {IEvent} event - The event object.
- * @param {Object} options - The plugin options.
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#afterEvent
* @desc Called after the `event` has been consumed. Note that this hook
* will not be called if the `event` has been previously discarded.
* @param {Chart.Controller} chart - The chart instance.
* @param {IEvent} event - The event object.
- * @param {Object} options - The plugin options.
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#resize
* @desc Called after the chart as been resized.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Number} size - The new canvas display size (eq. canvas.style width & height).
- * @param {Object} options - The plugin options.
+ * @param {number} size - The new canvas display size (eq. canvas.style width & height).
+ * @param {object} options - The plugin options.
*/
/**
* @method IPlugin#destroy
* @desc Called after the chart as been destroyed.
* @param {Chart.Controller} chart - The chart instance.
- * @param {Object} options - The plugin options.
+ * @param {object} options - The plugin options.
*/ | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/core/core.scale.js | @@ -717,8 +717,10 @@ module.exports = Element.extend({
return false;
},
- // Actually draw the scale on the canvas
- // @param {rectangle} chartArea : the area of the chart to draw full grid lines on
+ /**
+ * Actually draw the scale on the canvas
+ * @param {object} chartArea - the area of the chart to draw full grid lines on
+ */
draw: function(chartArea) {
var me = this;
var options = me.options; | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/core/core.ticks.js | @@ -16,7 +16,7 @@ module.exports = {
* Formatter for value labels
* @method Chart.Ticks.formatters.values
* @param value the value to display
- * @return {String|Array} the label to display
+ * @return {string|string[]} the label to display
*/
values: function(value) {
return helpers.isArray(value) ? value : '' + value;
@@ -25,10 +25,10 @@ module.exports = {
/**
* Formatter for linear numeric ticks
* @method Chart.Ticks.formatters.linear
- * @param tickValue {Number} the value to be formatted
- * @param index {Number} the position of the tickValue parameter in the ticks array
- * @param ticks {Array<Number>} the list of ticks being converted
- * @return {String} string representation of the tickValue parameter
+ * @param tickValue {number} the value to be formatted
+ * @param index {number} the position of the tickValue parameter in the ticks array
+ * @param ticks {number[]} the list of ticks being converted
+ * @return {string} string representation of the tickValue parameter
*/
linear: function(tickValue, index, ticks) {
// If we have lots of ticks, don't use the ones | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/core/core.tooltip.js | @@ -107,7 +107,7 @@ var positioners = {
* Average mode places the tooltip at the average position of the elements shown
* @function Chart.Tooltip.positioners.average
* @param elements {ChartElement[]} the elements being displayed in the tooltip
- * @returns {Point} tooltip position
+ * @returns {object} tooltip position
*/
average: function(elements) {
if (!elements.length) {
@@ -139,8 +139,8 @@ var positioners = {
* Gets the tooltip position nearest of the item nearest to the event position
* @function Chart.Tooltip.positioners.nearest
* @param elements {Chart.Element[]} the tooltip elements
- * @param eventPosition {Point} the position of the event in canvas coordinates
- * @returns {Point} the tooltip position
+ * @param eventPosition {object} the position of the event in canvas coordinates
+ * @returns {object} the tooltip position
*/
nearest: function(elements, eventPosition) {
var x = eventPosition.x;
@@ -190,8 +190,8 @@ function pushOrConcat(base, toPush) {
/**
* Returns array of strings split by newline
- * @param {String} value - The value to split by newline.
- * @returns {Array} value if newline present - Returned from String split() method
+ * @param {string} value - The value to split by newline.
+ * @returns {string[]} value if newline present - Returned from String split() method
* @function
*/
function splitNewlines(str) {
@@ -202,9 +202,11 @@ function splitNewlines(str) {
}
-// Private helper to create a tooltip item model
-// @param element : the chart element (point, arc, bar) to create the tooltip item for
-// @return : new tooltip item
+/**
+ * Private helper to create a tooltip item model
+ * @param element - the chart element (point, arc, bar) to create the tooltip item for
+ * @return new tooltip item
+ */
function createTooltipItem(element) {
var xScale = element._xScale;
var yScale = element._yScale || element._scale; // handle radar || polarArea charts
@@ -228,7 +230,7 @@ function createTooltipItem(element) {
/**
* Helper to get the reset model for the tooltip
- * @param tooltipOpts {Object} the tooltip options
+ * @param tooltipOpts {object} the tooltip options
*/
function getBaseModel(tooltipOpts) {
var globalDefaults = defaults.global;
@@ -953,7 +955,7 @@ var exports = Element.extend({
* Handle an event
* @private
* @param {IEvent} event - The event to handle
- * @returns {Boolean} true if the tooltip changed
+ * @returns {boolean} true if the tooltip changed
*/
handleEvent: function(e) {
var me = this; | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/helpers/helpers.canvas.js | @@ -25,11 +25,11 @@ var exports = {
* Creates a "path" for a rectangle with rounded corners at position (x, y) with a
* given size (width, height) and the same `radius` for all corners.
* @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
- * @param {Number} x - The x axis of the coordinate for the rectangle starting point.
- * @param {Number} y - The y axis of the coordinate for the rectangle starting point.
- * @param {Number} width - The rectangle's width.
- * @param {Number} height - The rectangle's height.
- * @param {Number} radius - The rounded amount (in pixels) for the four corners.
+ * @param {number} x - The x axis of the coordinate for the rectangle starting point.
+ * @param {number} y - The y axis of the coordinate for the rectangle starting point.
+ * @param {number} width - The rectangle's width.
+ * @param {number} height - The rectangle's height.
+ * @param {number} radius - The rounded amount (in pixels) for the four corners.
* @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
*/
roundedRect: function(ctx, x, y, width, height, radius) {
@@ -174,9 +174,9 @@ var exports = {
/**
* Returns true if the point is inside the rectangle
- * @param {Object} point - The point to test
- * @param {Object} area - The rectangle
- * @returns {Boolean}
+ * @param {object} point - The point to test
+ * @param {object} area - The rectangle
+ * @returns {boolean}
* @private
*/
_isPointInArea: function(point, area) { | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/helpers/helpers.core.js | @@ -11,7 +11,7 @@ var helpers = {
/**
* Returns a unique id, sequentially generated from a global variable.
- * @returns {Number}
+ * @returns {number}
* @function
*/
uid: (function() {
@@ -24,7 +24,7 @@ var helpers = {
/**
* Returns true if `value` is neither null nor undefined, else returns false.
* @param {*} value - The value to test.
- * @returns {Boolean}
+ * @returns {boolean}
* @since 2.7.0
*/
isNullOrUndef: function(value) {
@@ -34,7 +34,7 @@ var helpers = {
/**
* Returns true if `value` is an array (including typed arrays), else returns false.
* @param {*} value - The value to test.
- * @returns {Boolean}
+ * @returns {boolean}
* @function
*/
isArray: function(value) {
@@ -51,7 +51,7 @@ var helpers = {
/**
* Returns true if `value` is an object (excluding null), else returns false.
* @param {*} value - The value to test.
- * @returns {Boolean}
+ * @returns {boolean}
* @since 2.7.0
*/
isObject: function(value) {
@@ -61,7 +61,7 @@ var helpers = {
/**
* Returns true if `value` is a finite number, else returns false
* @param {*} value - The value to test.
- * @returns {Boolean}
+ * @returns {boolean}
*/
isFinite: function(value) {
return (typeof value === 'number' || value instanceof Number) && isFinite(value);
@@ -80,7 +80,7 @@ var helpers = {
/**
* Returns value at the given `index` in array if defined, else returns `defaultValue`.
* @param {Array} value - The array to lookup for value at `index`.
- * @param {Number} index - The index in `value` to lookup for value.
+ * @param {number} index - The index in `value` to lookup for value.
* @param {*} defaultValue - The value to return if `value[index]` is undefined.
* @returns {*}
*/
@@ -91,9 +91,9 @@ var helpers = {
/**
* Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
* value returned by `fn`. If `fn` is not a function, this method returns undefined.
- * @param {Function} fn - The function to call.
+ * @param {function} fn - The function to call.
* @param {Array|undefined|null} args - The arguments with which `fn` should be called.
- * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`.
+ * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
* @returns {*}
*/
callback: function(fn, args, thisArg) {
@@ -106,10 +106,10 @@ var helpers = {
* Note(SB) for performance sake, this method should only be used when loopable type
* is unknown or in none intensive code (not called often and small loopable). Else
* it's preferable to use a regular for() loop and save extra function calls.
- * @param {Object|Array} loopable - The object or array to be iterated.
- * @param {Function} fn - The function to call for each item.
- * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`.
- * @param {Boolean} [reverse] - If true, iterates backward on the loopable.
+ * @param {object|Array} loopable - The object or array to be iterated.
+ * @param {function} fn - The function to call for each item.
+ * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
+ * @param {boolean} [reverse] - If true, iterates backward on the loopable.
*/
each: function(loopable, fn, thisArg, reverse) {
var i, len, keys;
@@ -138,7 +138,7 @@ var helpers = {
* @see https://stackoverflow.com/a/14853974
* @param {Array} a0 - The array to compare
* @param {Array} a1 - The array to compare
- * @returns {Boolean}
+ * @returns {boolean}
*/
arrayEquals: function(a0, a1) {
var i, ilen, v0, v1;
@@ -224,11 +224,11 @@ var helpers = {
/**
* Recursively deep copies `source` properties into `target` with the given `options`.
* IMPORTANT: `target` is not cloned and will be updated with `source` properties.
- * @param {Object} target - The target object in which all sources are merged into.
- * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
- * @param {Object} [options] - Merging options:
- * @param {Function} [options.merger] - The merge method (key, target, source, options)
- * @returns {Object} The `target` object.
+ * @param {object} target - The target object in which all sources are merged into.
+ * @param {object|object[]} source - Object(s) to merge into `target`.
+ * @param {object} [options] - Merging options:
+ * @param {function} [options.merger] - The merge method (key, target, source, options)
+ * @returns {object} The `target` object.
*/
merge: function(target, source, options) {
var sources = helpers.isArray(source) ? source : [source];
@@ -260,20 +260,20 @@ var helpers = {
/**
* Recursively deep copies `source` properties into `target` *only* if not defined in target.
* IMPORTANT: `target` is not cloned and will be updated with `source` properties.
- * @param {Object} target - The target object in which all sources are merged into.
- * @param {Object|Array(Object)} source - Object(s) to merge into `target`.
- * @returns {Object} The `target` object.
+ * @param {object} target - The target object in which all sources are merged into.
+ * @param {object|object[]} source - Object(s) to merge into `target`.
+ * @returns {object} The `target` object.
*/
mergeIf: function(target, source) {
return helpers.merge(target, source, {merger: helpers._mergerIf});
},
/**
* Applies the contents of two or more objects together into the first object.
- * @param {Object} target - The target object in which all objects are merged into.
- * @param {Object} arg1 - Object containing additional properties to merge in target.
- * @param {Object} argN - Additional objects containing properties to merge in target.
- * @returns {Object} The `target` object.
+ * @param {object} target - The target object in which all objects are merged into.
+ * @param {object} arg1 - Object containing additional properties to merge in target.
+ * @param {object} argN - Additional objects containing properties to merge in target.
+ * @returns {object} The `target` object.
*/
extend: function(target) {
var setFn = function(value, key) { | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/helpers/helpers.options.js | @@ -7,8 +7,8 @@ var valueOrDefault = helpers.valueOrDefault;
/**
* Converts the given font object into a CSS font string.
- * @param {Object} font - A font object.
- * @return {String} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
+ * @param {object} font - A font object.
+ * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
* @private
*/
function toFontString(font) {
@@ -29,9 +29,9 @@ function toFontString(font) {
module.exports = {
/**
* Converts the given line height `value` in pixels for a specific font `size`.
- * @param {Number|String} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
- * @param {Number} size - The font size (in pixels) used to resolve relative `value`.
- * @returns {Number} The effective line height in pixels (size * 1.2 if value is invalid).
+ * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
+ * @param {number} size - The font size (in pixels) used to resolve relative `value`.
+ * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
* @since 2.7.0
*/
@@ -58,9 +58,9 @@ module.exports = {
/**
* Converts the given value into a padding object with pre-computed width/height.
- * @param {Number|Object} value - If a number, set the value to all TRBL component,
+ * @param {number|object} value - If a number, set the value to all TRBL component,
* else, if and object, use defined properties and sets undefined ones to 0.
- * @returns {Object} The padding values (top, right, bottom, left, width, height)
+ * @returns {object} The padding values (top, right, bottom, left, width, height)
* @since 2.7.0
*/
toPadding: function(value) {
@@ -87,8 +87,8 @@ module.exports = {
/**
* Parses font options and returns the font object.
- * @param {Object} options - A object that contains font options to be parsed.
- * @return {Object} The font object.
+ * @param {object} options - A object that contains font options to be parsed.
+ * @return {object} The font object.
* @todo Support font.* options and renamed to toFont().
* @private
*/
@@ -110,10 +110,10 @@ module.exports = {
/**
* Evaluates the given `inputs` sequentially and returns the first defined value.
- * @param {Array[]} inputs - An array of values, falling back to the last value.
- * @param {Object} [context] - If defined and the current value is a function, the value
+ * @param {Array} inputs - An array of values, falling back to the last value.
+ * @param {object} [context] - If defined and the current value is a function, the value
* is called with `context` as first argument and the result becomes the new input.
- * @param {Number} [index] - If defined and the current value is an array, the value
+ * @param {number} [index] - If defined and the current value is an array, the value
* at `index` become the new input.
* @since 2.7.0
*/ | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/platforms/platform.dom.js | @@ -38,7 +38,7 @@ var EVENT_TYPES = {
* `element` has a size relative to its parent and this last one is not yet displayed,
* for example because of `display: none` on a parent node.
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
- * @returns {Number} Size in pixels or undefined if unknown.
+ * @returns {number} Size in pixels or undefined if unknown.
*/
function readUsedSize(element, property) {
var value = helpers.getStyle(element, property); | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/platforms/platform.js | @@ -22,7 +22,7 @@ module.exports = helpers.extend({
* Called at chart construction time, returns a context2d instance implementing
* the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
* @param {*} item - The native item from which to acquire context (platform specific)
- * @param {Object} options - The chart options
+ * @param {object} options - The chart options
* @returns {CanvasRenderingContext2D} context2d instance
*/
acquireContext: function() {},
@@ -31,24 +31,24 @@ module.exports = helpers.extend({
* Called at chart destruction time, releases any resources associated to the context
* previously returned by the acquireContext() method.
* @param {CanvasRenderingContext2D} context - The context2d instance
- * @returns {Boolean} true if the method succeeded, else false
+ * @returns {boolean} true if the method succeeded, else false
*/
releaseContext: function() {},
/**
* Registers the specified listener on the given chart.
* @param {Chart} chart - Chart from which to listen for event
- * @param {String} type - The ({@link IEvent}) type to listen for
- * @param {Function} listener - Receives a notification (an object that implements
+ * @param {string} type - The ({@link IEvent}) type to listen for
+ * @param {function} listener - Receives a notification (an object that implements
* the {@link IEvent} interface) when an event of the specified type occurs.
*/
addEventListener: function() {},
/**
* Removes the specified listener previously registered with addEventListener.
- * @param {Chart} chart -Chart from which to remove the listener
- * @param {String} type - The ({@link IEvent}) type to remove
- * @param {Function} listener - The listener function to remove from the event target.
+ * @param {Chart} chart - Chart from which to remove the listener
+ * @param {string} type - The ({@link IEvent}) type to remove
+ * @param {function} listener - The listener function to remove from the event target.
*/
removeEventListener: function() {}
@@ -65,10 +65,10 @@ module.exports = helpers.extend({
/**
* @interface IEvent
- * @prop {String} type - The event type name, possible values are:
+ * @prop {string} type - The event type name, possible values are:
* 'contextmenu', 'mouseenter', 'mousedown', 'mousemove', 'mouseup', 'mouseout',
* 'click', 'dblclick', 'keydown', 'keypress', 'keyup' and 'resize'
* @prop {*} native - The original native event (null for emulated events, e.g. 'resize')
- * @prop {Number} x - The mouse x position, relative to the canvas (null for incompatible events)
- * @prop {Number} y - The mouse y position, relative to the canvas (null for incompatible events)
+ * @prop {number} x - The mouse x position, relative to the canvas (null for incompatible events)
+ * @prop {number} y - The mouse y position, relative to the canvas (null for incompatible events)
*/ | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/plugins/plugin.legend.js | @@ -85,9 +85,9 @@ defaults._set('global', {
/**
* Helper function to get the box width based on the usePointStyle option
- * @param labelopts {Object} the label options on the legend
- * @param fontSize {Number} the label font size
- * @return {Number} width of the color box area
+ * @param {object} labelopts - the label options on the legend
+ * @param {number} fontSize - the label font size
+ * @return {number} width of the color box area
*/
function getBoxWidth(labelOpts, fontSize) {
return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
@@ -462,7 +462,7 @@ var Legend = Element.extend({
* Handle an event
* @private
* @param {IEvent} event - The event to handle
- * @return {Boolean} true if a change occured
+ * @return {boolean} true if a change occured
*/
handleEvent: function(e) {
var me = this; | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/scales/scale.linearbase.js | @@ -10,7 +10,7 @@ var isNullOrUndef = helpers.isNullOrUndef;
* Generate a set of linear ticks
* @param generationOptions the options used to generate the ticks
* @param dataRange the range of the data
- * @returns {Array<Number>} array of tick values
+ * @returns {number[]} array of tick values
*/
function generateTicks(generationOptions, dataRange) {
var ticks = []; | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/scales/scale.logarithmic.js | @@ -11,7 +11,7 @@ var valueOrDefault = helpers.valueOrDefault;
* Generate a set of logarithmic ticks
* @param generationOptions the options used to generate the ticks
* @param dataRange the range of the data
- * @returns {Array<Number>} array of tick values
+ * @returns {number[]} array of tick values
*/
function generateTicks(generationOptions, dataRange) {
var ticks = [];
@@ -251,8 +251,8 @@ module.exports = Scale.extend({
/**
* Returns the value of the first tick.
- * @param {Number} value - The minimum not zero value.
- * @return {Number} The first tick value.
+ * @param {number} value - The minimum not zero value.
+ * @return {number} The first tick value.
* @private
*/
_getFirstTickValue: function(value) { | true |
Other | chartjs | Chart.js | 2f874fde622ebd2c3b45c668861659f17e1254e9.json | Use lowercase for primitives in jsdocs (#6033) | src/scales/scale.time.js | @@ -88,8 +88,8 @@ function arrayUnique(items) {
* store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
* to create the lookup table. The table ALWAYS contains at least two items: min and max.
*
- * @param {Number[]} timestamps - timestamps sorted from lowest to highest.
- * @param {String} distribution - If 'linear', timestamps will be spread linearly along the min
+ * @param {number[]} timestamps - timestamps sorted from lowest to highest.
+ * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
* and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
* If 'series', timestamps will be positioned at the same distance from each other. In this
* case, only timestamps that break the time linearity are registered, meaning that in the | true |
Other | chartjs | Chart.js | 0ed652b39f7fc96cfcbfd916081d5d930850a231.json | Fix typo in radial linear scale docs (#6054) | docs/axes/radial/linear.md | @@ -1,6 +1,6 @@
# Linear Radial Axis
-The linear scale is use to chart numerical data. As the name suggests, linear interpolation is used to determine where a value lies in relation the center of the axis.
+The linear scale is used to chart numerical data. As the name suggests, linear interpolation is used to determine where a value lies in relation the center of the axis.
The following additional configuration options are provided by the radial linear scale.
| false |
Other | chartjs | Chart.js | 55128f74c1518ac82189c0acba2a6b40f77bf698.json | Move CSS in a separate file to be CSP-compliant (#6048)
In order to be compatible with any CSP, we need to prevent the automatic creation of the DOM 'style' element and offer our CSS as a separate file that can be manually loaded (`Chart.js` or `Chart.min.js`). Users can now opt-out the style injection using `Chart.platform.disableCSSInjection = true` (note that the style sheet is now injected on the first chart creation).
To prevent duplicating and maintaining the same CSS code at different places, move all these rules in `platform.dom.css` and write a minimal rollup plugin to inject that style as string in `platform.dom.js`. Additionally, this plugin extract the imported style in `./dist/Chart.js` and `./dist/Chart.min.js`. | docs/getting-started/integration.md | @@ -84,3 +84,18 @@ require(['moment'], function() {
});
});
```
+
+## Content Security Policy
+
+By default, Chart.js injects CSS directly into the DOM. For webpages secured using [Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), this requires to allow `style-src 'unsafe-inline'`. For stricter CSP environments, where only `style-src 'self'` is allowed, the following CSS file needs to be manually added to your webpage:
+
+```html
+<link rel="stylesheet" type="text/css" href="path/to/chartjs/dist/Chart.min.css">
+```
+
+And the style injection must be turned off **before creating the first chart**:
+
+```javascript
+// Disable automatic style injection
+Chart.platform.disableCSSInjection = true;
+``` | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.