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 | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/controller.bar.tests.js | @@ -5,8 +5,8 @@ describe('Bar controller tests', function() {
type: 'bar',
data: {
datasets: [
- { data: [] },
- { data: [] }
+ {data: []},
+ {data: []}
],
labels: []
}
@@ -30,8 +30,8 @@ describe('Bar controller tests', function() {
type: 'bar',
data: {
datasets: [
- { data: [] },
- { data: [] }
+ {data: []},
+ {data: []}
],
labels: []
},
@@ -57,10 +57,10 @@ describe('Bar controller tests', function() {
type: 'bar',
data: {
datasets: [
- { data: [], type: 'line' },
- { data: [], hidden: true },
- { data: [] },
- { data: [] }
+ {data: [], type: 'line'},
+ {data: [], hidden: true},
+ {data: []},
+ {data: []}
],
labels: []
}
@@ -75,10 +75,10 @@ describe('Bar controller tests', function() {
type: 'bar',
data: {
datasets: [
- { data: [] },
- { data: [], hidden: true },
- { data: [], type: 'line' },
- { data: [] }
+ {data: []},
+ {data: [], hidden: true},
+ {data: [], type: 'line'},
+ {data: []}
],
labels: []
}
@@ -94,8 +94,8 @@ describe('Bar controller tests', function() {
type: 'bar',
data: {
datasets: [
- { data: [] },
- { data: [10, 15, 0, -4] }
+ {data: []},
+ {data: [10, 15, 0, -4]}
],
labels: []
}
@@ -154,8 +154,9 @@ describe('Bar controller tests', function() {
expect(meta.data.length).toBe(2);
- [ { x: 122, y: 484 },
- { x: 234, y: 32 }
+ [
+ {x: 122, y: 484},
+ {x: 234, y: 32}
].forEach(function(expected, i) {
expect(meta.data[i]._datasetIndex).toBe(1);
expect(meta.data[i]._index).toBe(i);
@@ -251,10 +252,11 @@ describe('Bar controller tests', function() {
var meta0 = chart.getDatasetMeta(0);
- [ { b: 290, w: 91, x: 95, y: 161 },
- { b: 290, w: 91, x: 209, y: 419 },
- { b: 290, w: 91, x: 322, y: 161 },
- { b: 290, w: 91, x: 436, y: 419 }
+ [
+ {b: 290, w: 91, x: 95, y: 161},
+ {b: 290, w: 91, x: 209, y: 419},
+ {b: 290, w: 91, x: 322, y: 161},
+ {b: 290, w: 91, x: 436, y: 419}
].forEach(function(values, i) {
expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w);
@@ -264,10 +266,11 @@ describe('Bar controller tests', function() {
var meta1 = chart.getDatasetMeta(1);
- [ { b: 161, w: 91, x: 95, y: 32 },
- { b: 290, w: 91, x: 209, y: 97 },
- { b: 161, w: 91, x: 322, y: 161 },
- { b: 419, w: 91, x: 436, y: 471 }
+ [
+ {b: 161, w: 91, x: 95, y: 32},
+ {b: 290, w: 91, x: 209, y: 97},
+ {b: 161, w: 91, x: 322, y: 161},
+ {b: 419, w: 91, x: 436, y: 471}
].forEach(function(values, i) {
expect(meta1.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta1.data[i]._model.width).toBeCloseToPixel(values.w);
@@ -305,10 +308,11 @@ describe('Bar controller tests', function() {
var meta0 = chart.getDatasetMeta(0);
- [ { b: 290, w: 91, x: 95, y: 161 },
- { b: 290, w: 91, x: 209, y: 419 },
- { b: 290, w: 91, x: 322, y: 161 },
- { b: 290, w: 91, x: 436, y: 419 }
+ [
+ {b: 290, w: 91, x: 95, y: 161},
+ {b: 290, w: 91, x: 209, y: 419},
+ {b: 290, w: 91, x: 322, y: 161},
+ {b: 290, w: 91, x: 436, y: 419}
].forEach(function(values, i) {
expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w);
@@ -318,10 +322,11 @@ describe('Bar controller tests', function() {
var meta1 = chart.getDatasetMeta(1);
- [ { b: 161, w: 91, x: 95, y: 32 },
- { b: 290, w: 91, x: 209, y: 97 },
- { b: 161, w: 91, x: 322, y: 161 },
- { b: 419, w: 91, x: 436, y: 471 }
+ [
+ {b: 161, w: 91, x: 95, y: 32},
+ {b: 290, w: 91, x: 209, y: 97},
+ {b: 161, w: 91, x: 322, y: 161},
+ {b: 419, w: 91, x: 436, y: 471}
].forEach(function(values, i) {
expect(meta1.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta1.data[i]._model.width).toBeCloseToPixel(values.w); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/controller.bubble.tests.js | @@ -133,10 +133,11 @@ describe('Bubble controller tests', function() {
var meta = chart.getDatasetMeta(0);
- [ { r: 5, x: 38, y: 32 },
- { r: 1, x: 189, y: 484 },
- { r: 2, x: 341, y: 461 },
- { r: 1, x: 492, y: 32 }
+ [
+ {r: 5, x: 38, y: 32},
+ {r: 1, x: 189, y: 484},
+ {r: 2, x: 341, y: 461},
+ {r: 1, x: 492, y: 32}
].forEach(function(expected, i) {
expect(meta.data[i]._model.radius).toBe(expected.r);
expect(meta.data[i]._model.x).toBeCloseToPixel(expected.x); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/controller.doughnut.tests.js | @@ -78,10 +78,11 @@ describe('Doughnut controller tests', function() {
expect(meta.data.length).toBe(4);
- [ { c: 0 },
- { c: 0 },
- { c: 0, },
- { c: 0 }
+ [
+ {c: 0},
+ {c: 0},
+ {c: 0},
+ {c: 0}
].forEach(function(expected, i) {
expect(meta.data[i]._model.x).toBeCloseToPixel(256);
expect(meta.data[i]._model.y).toBeCloseToPixel(272);
@@ -96,14 +97,15 @@ describe('Doughnut controller tests', function() {
borderColor: 'rgb(0, 0, 255)',
borderWidth: 2
}));
- })
+ });
chart.update();
- [ { c: 1.7453292519, s: -1.5707963267, e: 0.1745329251 },
- { c: 2.0943951023, s: 0.1745329251, e: 2.2689280275 },
- { c: 0, s: 2.2689280275, e: 2.2689280275 },
- { c: 2.4434609527, s: 2.2689280275, e: 4.7123889803 }
+ [
+ {c: 1.7453292519, s: -1.5707963267, e: 0.1745329251},
+ {c: 2.0943951023, s: 0.1745329251, e: 2.2689280275},
+ {c: 0, s: 2.2689280275, e: 2.2689280275},
+ {c: 2.4434609527, s: 2.2689280275, e: 4.7123889803}
].forEach(function(expected, i) {
expect(meta.data[i]._model.x).toBeCloseToPixel(256);
expect(meta.data[i]._model.y).toBeCloseToPixel(272);
@@ -118,7 +120,7 @@ describe('Doughnut controller tests', function() {
borderColor: 'rgb(0, 0, 255)',
borderWidth: 2
}));
- })
+ });
// Change the amount of data and ensure that arcs are updated accordingly
chart.data.datasets[1].data = [1, 2]; // remove 2 elements from dataset 0
@@ -172,17 +174,18 @@ describe('Doughnut controller tests', function() {
expect(meta.data.length).toBe(2);
// Only startAngle, endAngle and circumference should be different.
- [ { c: Math.PI / 8, s: Math.PI, e: Math.PI + Math.PI / 8 },
- { c: 3 * Math.PI / 8, s: Math.PI + Math.PI / 8, e: Math.PI + Math.PI / 2 }
+ [
+ {c: Math.PI / 8, s: Math.PI, e: Math.PI + Math.PI / 8},
+ {c: 3 * Math.PI / 8, s: Math.PI + Math.PI / 8, e: Math.PI + Math.PI / 2}
].forEach(function(expected, i) {
expect(meta.data[i]._model.x).toBeCloseToPixel(495);
expect(meta.data[i]._model.y).toBeCloseToPixel(511);
expect(meta.data[i]._model.outerRadius).toBeCloseToPixel(478);
expect(meta.data[i]._model.innerRadius).toBeCloseToPixel(359);
- expect(meta.data[i]._model.circumference).toBeCloseTo(expected.c,8);
+ expect(meta.data[i]._model.circumference).toBeCloseTo(expected.c, 8);
expect(meta.data[i]._model.startAngle).toBeCloseTo(expected.s, 8);
expect(meta.data[i]._model.endAngle).toBeCloseTo(expected.e, 8);
- })
+ });
});
it ('should draw all arcs', function() { | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/controller.line.tests.js | @@ -165,12 +165,12 @@ describe('Line controller tests', function() {
var chart = window.acquireChart({
type: 'line',
data: {
- datasets: [{
- data: [10, 15, 0, -4],
- label: 'dataset',
- xAxisID: 'firstXScaleID',
- yAxisID: 'firstYScaleID'
- }],
+ datasets: [{
+ data: [10, 15, 0, -4],
+ label: 'dataset',
+ xAxisID: 'firstXScaleID',
+ yAxisID: 'firstYScaleID'
+ }],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
@@ -202,8 +202,9 @@ describe('Line controller tests', function() {
expect(meta.data.length).toBe(2);
- [ { x: 44, y: 484 },
- { x: 193, y: 32 }
+ [
+ {x: 44, y: 484},
+ {x: 193, y: 32}
].forEach(function(expected, i) {
expect(meta.data[i]._datasetIndex).toBe(0);
expect(meta.data[i]._index).toBe(i);
@@ -223,23 +224,23 @@ describe('Line controller tests', function() {
expect(meta.data.length).toBe(3); // should add a new meta data item
});
- it('should correctly calculate x scale for label and point', function(){
- var chart = window.acquireChart({
+ it('should correctly calculate x scale for label and point', function() {
+ var chart = window.acquireChart({
type: 'line',
- data: {
- labels: ["One"],
- datasets: [{
- data: [1],
- }]
+ data: {
+ labels: ['One'],
+ datasets: [{
+ data: [1],
+ }]
+ },
+ options: {
+ hover: {
+ mode: 'single'
},
- options: {
- hover: {
- mode: 'single'
- },
scales: {
yAxes: [{
ticks: {
- beginAtZero:true
+ beginAtZero: true
}
}]
}
@@ -252,7 +253,7 @@ describe('Line controller tests', function() {
expect(point._model.x).toBeCloseToPixel(267);
// 2 points
- chart.data.labels = ["One", "Two"];
+ chart.data.labels = ['One', 'Two'];
chart.data.datasets[0].data = [1, 2];
chart.update();
@@ -262,7 +263,7 @@ describe('Line controller tests', function() {
expect(points[1]._model.x).toBeCloseToPixel(498);
// 3 points
- chart.data.labels = ["One", "Two", "Three"];
+ chart.data.labels = ['One', 'Two', 'Three'];
chart.data.datasets[0].data = [1, 2, 3];
chart.update();
@@ -273,7 +274,7 @@ describe('Line controller tests', function() {
expect(points[2]._model.x).toBeCloseToPixel(493);
// 4 points
- chart.data.labels = ["One", "Two", "Three", "Four"];
+ chart.data.labels = ['One', 'Two', 'Three', 'Four'];
chart.data.datasets[0].data = [1, 2, 3, 4];
chart.update();
@@ -309,24 +310,26 @@ describe('Line controller tests', function() {
var meta0 = chart.getDatasetMeta(0);
- [ { x: 38, y: 161 },
- { x: 189, y: 419 },
- { x: 341, y: 161 },
- { x: 492, y: 419 }
+ [
+ {x: 38, y: 161},
+ {x: 189, y: 419},
+ {x: 341, y: 161},
+ {x: 492, y: 419}
].forEach(function(values, i) {
- expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
- expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
+ expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
+ expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
- [ { x: 38, y: 32 },
- { x: 189, y: 97 },
- { x: 341, y: 161 },
- { x: 492, y: 471 }
+ [
+ {x: 38, y: 32},
+ {x: 189, y: 97},
+ {x: 341, y: 161},
+ {x: 492, y: 471}
].forEach(function(values, i) {
- expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
- expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
+ expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
+ expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
});
});
@@ -362,24 +365,26 @@ describe('Line controller tests', function() {
var meta0 = chart.getDatasetMeta(0);
- [ { x: 76, y: 161 },
- { x: 215, y: 419 },
- { x: 353, y: 161 },
- { x: 492, y: 419 }
+ [
+ {x: 76, y: 161},
+ {x: 215, y: 419},
+ {x: 353, y: 161},
+ {x: 492, y: 419}
].forEach(function(values, i) {
- expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
- expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
+ expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
+ expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
- [ { x: 76, y: 32 },
- { x: 215, y: 97 },
- { x: 353, y: 161 },
- { x: 492, y: 471 }
+ [
+ {x: 76, y: 32},
+ {x: 215, y: 97},
+ {x: 353, y: 161},
+ {x: 492, y: 471}
].forEach(function(values, i) {
- expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
- expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
+ expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
+ expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
});
});
@@ -432,24 +437,26 @@ describe('Line controller tests', function() {
var meta0 = chart.getDatasetMeta(0);
- [ { x: 38, y: 161 },
- { x: 189, y: 419 },
- { x: 341, y: 161 },
- { x: 492, y: 419 }
+ [
+ {x: 38, y: 161},
+ {x: 189, y: 419},
+ {x: 341, y: 161},
+ {x: 492, y: 419}
].forEach(function(values, i) {
- expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
- expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
+ expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
+ expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
- [ { x: 38, y: 32 },
- { x: 189, y: 97 },
- { x: 341, y: 161 },
- { x: 492, y: 471 }
+ [
+ {x: 38, y: 32},
+ {x: 189, y: 97},
+ {x: 341, y: 161},
+ {x: 492, y: 471}
].forEach(function(values, i) {
- expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
- expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
+ expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
+ expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
});
});
@@ -478,24 +485,26 @@ describe('Line controller tests', function() {
var meta0 = chart.getDatasetMeta(0);
- [ { x: 38, y: 161 },
- { x: 189, y: 419 },
- { x: 341, y: 161 },
- { x: 492, y: 419 }
+ [
+ {x: 38, y: 161},
+ {x: 189, y: 419},
+ {x: 341, y: 161},
+ {x: 492, y: 419}
].forEach(function(values, i) {
- expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
- expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
+ expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
+ expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
- [ { x: 38, y: 32 },
- { x: 189, y: 97 },
- { x: 341, y: 161 },
- { x: 492, y: 471 }
+ [
+ {x: 38, y: 32},
+ {x: 189, y: 97},
+ {x: 341, y: 161},
+ {x: 492, y: 471}
].forEach(function(values, i) {
- expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
- expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
+ expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
+ expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
});
}); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/controller.polarArea.tests.js | @@ -2,14 +2,14 @@
describe('Polar area controller tests', function() {
it('should be constructed', function() {
var chart = window.acquireChart({
- type: 'polarArea',
- data: {
- datasets: [
- { data: [] },
- { data: [] }
- ],
- labels: []
- }
+ type: 'polarArea',
+ data: {
+ datasets: [
+ {data: []},
+ {data: []}
+ ],
+ labels: []
+ }
});
var meta = chart.getDatasetMeta(1);
@@ -28,8 +28,8 @@ describe('Polar area controller tests', function() {
type: 'polarArea',
data: {
datasets: [
- { data: [] },
- { data: [10, 15, 0, -4] }
+ {data: []},
+ {data: [10, 15, 0, -4]}
],
labels: []
}
@@ -45,14 +45,14 @@ describe('Polar area controller tests', function() {
it('should draw all elements', function() {
var chart = window.acquireChart({
- type: 'polarArea',
- data: {
- datasets: [{
- data: [10, 15, 0, -4],
- label: 'dataset2'
- }],
- labels: ['label1', 'label2', 'label3', 'label4']
- }
+ type: 'polarArea',
+ data: {
+ datasets: [{
+ data: [10, 15, 0, -4],
+ label: 'dataset2'
+ }],
+ labels: ['label1', 'label2', 'label3', 'label4']
+ }
});
var meta = chart.getDatasetMeta(0);
@@ -95,10 +95,11 @@ describe('Polar area controller tests', function() {
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(4);
- [ { o: 156, s: -0.5 * Math.PI, e: 0 },
- { o: 211, s: 0, e: 0.5 * Math.PI },
- { o: 45, s: 0.5 * Math.PI, e: Math.PI },
- { o: 0, s: Math.PI, e: 1.5 * Math.PI }
+ [
+ {o: 156, s: -0.5 * Math.PI, e: 0},
+ {o: 211, s: 0, e: 0.5 * Math.PI},
+ {o: 45, s: 0.5 * Math.PI, e: Math.PI},
+ {o: 0, s: Math.PI, e: 1.5 * Math.PI}
].forEach(function(expected, i) {
expect(meta.data[i]._model.x).toBeCloseToPixel(256);
expect(meta.data[i]._model.y).toBeCloseToPixel(272);
@@ -176,10 +177,11 @@ describe('Polar area controller tests', function() {
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(4);
- [ { o: 156, s: 0, e: 0.5 * Math.PI },
- { o: 211, s: 0.5 * Math.PI, e: Math.PI },
- { o: 45, s: Math.PI, e: 1.5 * Math.PI },
- { o: 0, s: 1.5 * Math.PI, e: 2.0 * Math.PI }
+ [
+ {o: 156, s: 0, e: 0.5 * Math.PI},
+ {o: 211, s: 0.5 * Math.PI, e: Math.PI},
+ {o: 45, s: Math.PI, e: 1.5 * Math.PI},
+ {o: 0, s: 1.5 * Math.PI, e: 2.0 * Math.PI}
].forEach(function(expected, i) {
expect(meta.data[i]._model.x).toBeCloseToPixel(256);
expect(meta.data[i]._model.y).toBeCloseToPixel(272);
@@ -230,7 +232,7 @@ describe('Polar area controller tests', function() {
expect(meta.data[0] instanceof Chart.elements.Arc).toBe(true);
expect(meta.data[1] instanceof Chart.elements.Arc).toBe(true);
- // add 3 items
+ // add 3 items
chart.data.labels = ['label1', 'label2', 'label3', 'label4', 'label5'];
chart.data.datasets[0].data = [1, 2, 3, 4, 5];
chart.update(); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/controller.radar.tests.js | @@ -32,8 +32,6 @@ describe('Radar controller tests', function() {
}
});
- var controller = new Chart.controllers.radar(chart, 0);
-
var meta = chart.getDatasetMeta(0);
expect(meta.dataset instanceof Chart.elements.Line).toBe(true); // line element
expect(meta.data.length).toBe(4); // 4 points created
@@ -130,10 +128,10 @@ describe('Radar controller tests', function() {
}));
[
- { x: 256, y: 272, cppx: 256, cppy: 272, cpnx: 256, cpny: 272},
- { x: 256, y: 272, cppx: 256, cppy: 272, cpnx: 256, cpny: 272},
- { x: 256, y: 272, cppx: 256, cppy: 272, cpnx: 256, cpny: 272},
- { x: 256, y: 272, cppx: 256, cppy: 272, cpnx: 256, cpny: 272},
+ {x: 256, y: 272, cppx: 256, cppy: 272, cpnx: 256, cpny: 272},
+ {x: 256, y: 272, cppx: 256, cppy: 272, cpnx: 256, cpny: 272},
+ {x: 256, y: 272, cppx: 256, cppy: 272, cpnx: 256, cpny: 272},
+ {x: 256, y: 272, cppx: 256, cppy: 272, cpnx: 256, cpny: 272},
].forEach(function(expected, i) {
expect(meta.data[i]._model.x).toBeCloseToPixel(expected.x);
expect(meta.data[i]._model.y).toBeCloseToPixel(expected.y);
@@ -157,10 +155,10 @@ describe('Radar controller tests', function() {
meta.controller.update();
[
- { x: 256, y: 133, cppx: 246, cppy: 133, cpnx: 272, cpny: 133 },
- { x: 464, y: 272, cppx: 464, cppy: 264, cpnx: 464, cpny: 278 },
- { x: 256, y: 272, cppx: 276.9, cppy: 272, cpnx: 250.4, cpny: 272 },
- { x: 200, y: 272, cppx: 200, cppy: 275, cpnx: 200, cpny: 261 },
+ {x: 256, y: 133, cppx: 246, cppy: 133, cpnx: 272, cpny: 133},
+ {x: 464, y: 272, cppx: 464, cppy: 264, cpnx: 464, cpny: 278},
+ {x: 256, y: 272, cppx: 276.9, cppy: 272, cpnx: 250.4, cpny: 272},
+ {x: 200, y: 272, cppx: 200, cppy: 275, cpnx: 200, cpny: 261},
].forEach(function(expected, i) {
expect(meta.data[i]._model.x).toBeCloseToPixel(expected.x);
expect(meta.data[i]._model.y).toBeCloseToPixel(expected.y);
@@ -218,10 +216,10 @@ describe('Radar controller tests', function() {
// Since tension is now 0, we don't care about the control points
[
- { x: 256, y: 133 },
- { x: 464, y: 272 },
- { x: 256, y: 272 },
- { x: 200, y: 272 },
+ {x: 256, y: 133},
+ {x: 464, y: 272},
+ {x: 256, y: 272},
+ {x: 200, y: 272},
].forEach(function(expected, i) {
expect(meta.data[i]._model.x).toBeCloseToPixel(expected.x);
expect(meta.data[i]._model.y).toBeCloseToPixel(expected.y);
@@ -454,4 +452,4 @@ describe('Radar controller tests', function() {
expect(point._model.borderWidth).toBe(5.5);
expect(point._model.radius).toBe(4.4);
});
-});
\ No newline at end of file
+}); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/core.element.tests.js | @@ -25,9 +25,9 @@ describe('Core element tests', function() {
element._model.numberProp = 100;
element._model.numberProp2 = 250;
element._model._underscoreProp = 200;
- element._model.stringProp = 'def'
+ element._model.stringProp = 'def';
element._model.newStringProp = 'newString';
- element._model.colorProp = 'rgb(255, 255, 0)'
+ element._model.colorProp = 'rgb(255, 255, 0)';
element.transition(0.25);
expect(element._view).toEqual({
@@ -42,4 +42,4 @@ describe('Core element tests', function() {
colorProp: 'rgb(64, 64, 0)',
});
});
-});
\ No newline at end of file
+}); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/core.helpers.tests.js | @@ -7,7 +7,7 @@ describe('Core helper tests', function() {
});
it('should iterate over an array and pass the extra data to that function', function() {
- var testData = [0, 9, "abc"];
+ var testData = [0, 9, 'abc'];
var scope = {}; // fake out the scope and ensure that 'this' is the correct thing
helpers.each(testData, function(item, index) {
@@ -183,20 +183,20 @@ describe('Core helper tests', function() {
display: true,
gridLines: {
- color: "rgba(0, 0, 0, 0.1)",
+ color: 'rgba(0, 0, 0, 0.1)',
drawBorder: true,
drawOnChartArea: true,
drawTicks: true, // draw ticks extending towards the label
tickMarkLength: 10,
lineWidth: 1,
offsetGridLines: false,
display: true,
- zeroLineColor: "rgba(0,0,0,0.25)",
+ zeroLineColor: 'rgba(0,0,0,0.25)',
zeroLineWidth: 1,
borderDash: [],
borderDashOffset: 0.0
},
- position: "right",
+ position: 'right',
scaleLabel: {
labelString: '',
display: false,
@@ -219,20 +219,20 @@ describe('Core helper tests', function() {
display: true,
gridLines: {
- color: "rgba(0, 0, 0, 0.1)",
+ color: 'rgba(0, 0, 0, 0.1)',
drawBorder: true,
drawOnChartArea: true,
drawTicks: true, // draw ticks extending towards the label,
tickMarkLength: 10,
lineWidth: 1,
offsetGridLines: false,
display: true,
- zeroLineColor: "rgba(0,0,0,0.25)",
+ zeroLineColor: 'rgba(0,0,0,0.25)',
zeroLineWidth: 1,
borderDash: [],
borderDashOffset: 0.0
},
- position: "left",
+ position: 'left',
scaleLabel: {
labelString: '',
display: false,
@@ -271,7 +271,7 @@ describe('Core helper tests', function() {
it('should filter an array', function() {
var data = [-10, 0, 6, 0, 7];
var callback = function(item) {
- return item > 2
+ return item > 2;
};
expect(helpers.where(data, callback)).toEqual([6, 7]);
expect(helpers.findNextWhere(data, callback)).toEqual(6);
@@ -400,19 +400,19 @@ describe('Core helper tests', function() {
it('should spline curves with monotone cubic interpolation', function() {
var dataPoints = [
- { _model: { x: 0, y: 0, skip: false } },
- { _model: { x: 3, y: 6, skip: false } },
- { _model: { x: 9, y: 6, skip: false } },
- { _model: { x: 12, y: 60, skip: false } },
- { _model: { x: 15, y: 60, skip: false } },
- { _model: { x: 18, y: 120, skip: false } },
- { _model: { x: null, y: null, skip: true } },
- { _model: { x: 21, y: 180, skip: false } },
- { _model: { x: 24, y: 120, skip: false } },
- { _model: { x: 27, y: 125, skip: false } },
- { _model: { x: 30, y: 105, skip: false } },
- { _model: { x: 33, y: 110, skip: false } },
- { _model: { x: 36, y: 170, skip: false } }
+ {_model: {x: 0, y: 0, skip: false}},
+ {_model: {x: 3, y: 6, skip: false}},
+ {_model: {x: 9, y: 6, skip: false}},
+ {_model: {x: 12, y: 60, skip: false}},
+ {_model: {x: 15, y: 60, skip: false}},
+ {_model: {x: 18, y: 120, skip: false}},
+ {_model: {x: null, y: null, skip: true}},
+ {_model: {x: 21, y: 180, skip: false}},
+ {_model: {x: 24, y: 120, skip: false}},
+ {_model: {x: 27, y: 125, skip: false}},
+ {_model: {x: 30, y: 105, skip: false}},
+ {_model: {x: 33, y: 110, skip: false}},
+ {_model: {x: 36, y: 170, skip: false}}
];
helpers.splineCurveMonotone(dataPoints);
expect(dataPoints).toEqual([{
@@ -580,13 +580,13 @@ describe('Core helper tests', function() {
it('should return the width of the longest text in an Array and 2D Array', function() {
var context = window.createMockContext();
var font = "normal 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
- var arrayOfThings_1D = ['FooBar','Bar'];
- var arrayOfThings_2D = [['FooBar_1','Bar_2'],'Foo_1'];
-
+ var arrayOfThings1D = ['FooBar', 'Bar'];
+ var arrayOfThings2D = [['FooBar_1', 'Bar_2'], 'Foo_1'];
+
// Regardless 'FooBar' is the longest label it should return (charcters * 10)
- expect(helpers.longestText(context, font, arrayOfThings_1D, {})).toEqual(60);
- expect(helpers.longestText(context, font, arrayOfThings_2D, {})).toEqual(80);
+ expect(helpers.longestText(context, font, arrayOfThings1D, {})).toEqual(60);
+ expect(helpers.longestText(context, font, arrayOfThings2D, {})).toEqual(80);
// We check to make sure we made the right calls to the canvas.
expect(context.getCalls()).toEqual([{
name: 'measureText',
@@ -629,14 +629,14 @@ describe('Core helper tests', function() {
});
it('count look at all the labels and return maximum number of lines', function() {
- var context = window.createMockContext();
- var arrayOfThings_1 = ['Foo','Bar'];
- var arrayOfThings_2 = [['Foo','Bar'],'Foo'];
- var arrayOfThings_3 = [['Foo','Bar','Boo'],['Foo','Bar'],'Foo'];
+ window.createMockContext();
+ var arrayOfThings1 = ['Foo', 'Bar'];
+ var arrayOfThings2 = [['Foo', 'Bar'], 'Foo'];
+ var arrayOfThings3 = [['Foo', 'Bar', 'Boo'], ['Foo', 'Bar'], 'Foo'];
- expect(helpers.numberOfLabelLines(arrayOfThings_1)).toEqual(1);
- expect(helpers.numberOfLabelLines(arrayOfThings_2)).toEqual(2);
- expect(helpers.numberOfLabelLines(arrayOfThings_3)).toEqual(3);
+ expect(helpers.numberOfLabelLines(arrayOfThings1)).toEqual(1);
+ expect(helpers.numberOfLabelLines(arrayOfThings2)).toEqual(2);
+ expect(helpers.numberOfLabelLines(arrayOfThings3)).toEqual(3);
});
it('should draw a rounded rectangle', function() {
@@ -676,14 +676,14 @@ describe('Core helper tests', function() {
}, {
name: 'closePath',
args: []
- }])
+ }]);
});
it ('should get the maximum width and height for a node', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
- div.style.width = "200px";
- div.style.height = "300px";
+ div.style.width = '200px';
+ div.style.height = '300px';
document.body.appendChild(div);
@@ -700,14 +700,14 @@ describe('Core helper tests', function() {
it ('should get the maximum width of a node that has a max-width style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
- div.style.width = "200px";
- div.style.height = "300px";
+ div.style.width = '200px';
+ div.style.height = '300px';
document.body.appendChild(div);
// Create the div we want to get the max size for and set a max-width style
var innerDiv = document.createElement('div');
- innerDiv.style.maxWidth = "150px";
+ innerDiv.style.maxWidth = '150px';
div.appendChild(innerDiv);
expect(helpers.getMaximumWidth(innerDiv)).toBe(150);
@@ -718,14 +718,14 @@ describe('Core helper tests', function() {
it ('should get the maximum height of a node that has a max-height style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
- div.style.width = "200px";
- div.style.height = "300px";
+ div.style.width = '200px';
+ div.style.height = '300px';
document.body.appendChild(div);
// Create the div we want to get the max size for and set a max-height style
var innerDiv = document.createElement('div');
- innerDiv.style.maxHeight = "150px";
+ innerDiv.style.maxHeight = '150px';
div.appendChild(innerDiv);
expect(helpers.getMaximumHeight(innerDiv)).toBe(150);
@@ -736,14 +736,14 @@ describe('Core helper tests', function() {
it ('should get the maximum width of a node when the parent has a max-width style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
- div.style.width = "200px";
- div.style.height = "300px";
+ div.style.width = '200px';
+ div.style.height = '300px';
document.body.appendChild(div);
// Create an inner wrapper around our div we want to size and give that a max-width style
var parentDiv = document.createElement('div');
- parentDiv.style.maxWidth = "150px";
+ parentDiv.style.maxWidth = '150px';
div.appendChild(parentDiv);
// Create the div we want to get the max size for
@@ -758,19 +758,19 @@ describe('Core helper tests', function() {
it ('should get the maximum height of a node when the parent has a max-height style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
- div.style.width = "200px";
- div.style.height = "300px";
+ div.style.width = '200px';
+ div.style.height = '300px';
document.body.appendChild(div);
// Create an inner wrapper around our div we want to size and give that a max-height style
var parentDiv = document.createElement('div');
- parentDiv.style.maxHeight = "150px";
+ parentDiv.style.maxHeight = '150px';
div.appendChild(parentDiv);
// Create the div we want to get the max size for
var innerDiv = document.createElement('div');
- innerDiv.style.height = "300px"; // make it large
+ innerDiv.style.height = '300px'; // make it large
parentDiv.appendChild(innerDiv);
expect(helpers.getMaximumHeight(innerDiv)).toBe(150);
@@ -781,14 +781,14 @@ describe('Core helper tests', function() {
it ('should get the maximum width of a node that has a percentage max-width style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
- div.style.width = "200px";
- div.style.height = "300px";
+ div.style.width = '200px';
+ div.style.height = '300px';
document.body.appendChild(div);
// Create the div we want to get the max size for and set a max-width style
var innerDiv = document.createElement('div');
- innerDiv.style.maxWidth = "50%";
+ innerDiv.style.maxWidth = '50%';
div.appendChild(innerDiv);
expect(helpers.getMaximumWidth(innerDiv)).toBe(100);
@@ -799,14 +799,14 @@ describe('Core helper tests', function() {
it ('should get the maximum height of a node that has a percentage max-height style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
- div.style.width = "200px";
- div.style.height = "300px";
+ div.style.width = '200px';
+ div.style.height = '300px';
document.body.appendChild(div);
// Create the div we want to get the max size for and set a max-height style
var innerDiv = document.createElement('div');
- innerDiv.style.maxHeight = "50%";
+ innerDiv.style.maxHeight = '50%';
div.appendChild(innerDiv);
expect(helpers.getMaximumHeight(innerDiv)).toBe(150);
@@ -817,14 +817,14 @@ describe('Core helper tests', function() {
it ('should get the maximum width of a node when the parent has a percentage max-width style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
- div.style.width = "200px";
- div.style.height = "300px";
+ div.style.width = '200px';
+ div.style.height = '300px';
document.body.appendChild(div);
// Create an inner wrapper around our div we want to size and give that a max-width style
var parentDiv = document.createElement('div');
- parentDiv.style.maxWidth = "50%";
+ parentDiv.style.maxWidth = '50%';
div.appendChild(parentDiv);
// Create the div we want to get the max size for
@@ -839,18 +839,18 @@ describe('Core helper tests', function() {
it ('should get the maximum height of a node when the parent has a percentage max-height style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
- div.style.width = "200px";
- div.style.height = "300px";
+ div.style.width = '200px';
+ div.style.height = '300px';
document.body.appendChild(div);
// Create an inner wrapper around our div we want to size and give that a max-height style
var parentDiv = document.createElement('div');
- parentDiv.style.maxHeight = "50%";
+ parentDiv.style.maxHeight = '50%';
div.appendChild(parentDiv);
var innerDiv = document.createElement('div');
- innerDiv.style.height = "300px"; // make it large
+ innerDiv.style.height = '300px'; // make it large
parentDiv.appendChild(innerDiv);
expect(helpers.getMaximumHeight(innerDiv)).toBe(150);
@@ -891,7 +891,7 @@ describe('Core helper tests', function() {
expect(backgroundColor instanceof CanvasPattern).toBe(true);
done();
- }
+ };
});
it('should return a modified version of color when called with a color', function() { | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/core.interaction.tests.js | @@ -115,7 +115,7 @@ describe('Core.Interaction', function() {
currentTarget: node
};
- var elements = Chart.Interaction.modes.index(chartInstance, evt, { intersect: true });
+ var elements = Chart.Interaction.modes.index(chartInstance, evt, {intersect: true});
expect(elements).toEqual([point, meta1.data[1]]);
});
@@ -154,7 +154,7 @@ describe('Core.Interaction', function() {
currentTarget: node
};
- var elements = Chart.Interaction.modes.index(chartInstance, evt, { intersect: false });
+ var elements = Chart.Interaction.modes.index(chartInstance, evt, {intersect: false});
expect(elements).toEqual([meta0.data[0], meta1.data[0]]);
});
});
@@ -195,7 +195,7 @@ describe('Core.Interaction', function() {
currentTarget: node
};
- var elements = Chart.Interaction.modes.dataset(chartInstance, evt, { intersect: true });
+ var elements = Chart.Interaction.modes.dataset(chartInstance, evt, {intersect: true});
expect(elements).toEqual(meta.data);
});
@@ -230,7 +230,7 @@ describe('Core.Interaction', function() {
currentTarget: node
};
- var elements = Chart.Interaction.modes.dataset(chartInstance, evt, { intersect: false });
+ var elements = Chart.Interaction.modes.dataset(chartInstance, evt, {intersect: false});
var meta = chartInstance.getDatasetMeta(1);
expect(elements).toEqual(meta.data);
@@ -260,7 +260,6 @@ describe('Core.Interaction', function() {
// Trigger an event over top of the
var meta = chartInstance.getDatasetMeta(1);
var node = chartInstance.chart.canvas;
- var rect = node.getBoundingClientRect();
var evt = {
view: window,
bubbles: true,
@@ -271,7 +270,7 @@ describe('Core.Interaction', function() {
};
// Nearest to 0,0 (top left) will be first point of dataset 2
- var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: false });
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, {intersect: false});
expect(elements).toEqual([meta.data[0]]);
});
@@ -318,7 +317,7 @@ describe('Core.Interaction', function() {
};
// Nearest to 0,0 (top left) will be first point of dataset 2
- var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: false });
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, {intersect: false});
expect(elements).toEqual([meta0.data[1]]);
});
@@ -365,7 +364,7 @@ describe('Core.Interaction', function() {
};
// Nearest to 0,0 (top left) will be first point of dataset 2
- var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: false });
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, {intersect: false});
expect(elements).toEqual([meta0.data[1]]);
});
});
@@ -406,7 +405,7 @@ describe('Core.Interaction', function() {
};
// Nothing intersects so find nothing
- var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: true });
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, {intersect: true});
expect(elements).toEqual([]);
evt = {
@@ -417,7 +416,7 @@ describe('Core.Interaction', function() {
clientY: rect.top + point._view.y,
currentTarget: node
};
- elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: true });
+ elements = Chart.Interaction.modes.nearest(chartInstance, evt, {intersect: true});
expect(elements).toEqual([point]);
});
@@ -463,7 +462,7 @@ describe('Core.Interaction', function() {
};
// Nearest to 0,0 (top left) will be first point of dataset 2
- var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: true });
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, {intersect: true});
expect(elements).toEqual([meta0.data[1]]);
});
@@ -509,7 +508,7 @@ describe('Core.Interaction', function() {
};
// Nearest to 0,0 (top left) will be first point of dataset 2
- var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: true });
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, {intersect: true});
expect(elements).toEqual([meta0.data[1]]);
});
@@ -555,7 +554,7 @@ describe('Core.Interaction', function() {
};
// Nearest to 0,0 (top left) will be first point of dataset 2
- var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: true });
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, {intersect: true});
expect(elements).toEqual([meta0.data[1]]);
});
}); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/core.layoutService.tests.js | @@ -5,7 +5,7 @@ describe('Test the layout service', function() {
type: 'bar',
data: {
datasets: [
- { data: [10, 5, 0, 25, 78, -10] }
+ {data: [10, 5, 0, 25, 78, -10]}
],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
},
@@ -53,7 +53,7 @@ describe('Test the layout service', function() {
type: 'bar',
data: {
datasets: [
- { data: [10, 5, 0, 25, 78, -10] }
+ {data: [10, 5, 0, 25, 78, -10]}
],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
},
@@ -121,7 +121,7 @@ describe('Test the layout service', function() {
expect(chart.scale.right).toBeCloseToPixel(512);
expect(chart.scale.top).toBeCloseToPixel(32);
expect(chart.scale.width).toBeCloseToPixel(512);
- expect(chart.scale.height).toBeCloseToPixel(480)
+ expect(chart.scale.height).toBeCloseToPixel(480);
});
it('should fit multiple axes in the same position', function() { | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/core.legend.tests.js | @@ -118,20 +118,21 @@ describe('Legend block tests', function() {
expect(chart.legend.legendHitBoxes.length).toBe(3);
- [ { h: 12, l: 101, t: 10, w: 93 },
- { h: 12, l: 205, t: 10, w: 93 },
- { h: 12, l: 308, t: 10, w: 93 }
+ [
+ {h: 12, l: 101, t: 10, w: 93},
+ {h: 12, l: 205, t: 10, w: 93},
+ {h: 12, l: 308, t: 10, w: 93}
].forEach(function(expected, i) {
expect(chart.legend.legendHitBoxes[i].height).toBeCloseToPixel(expected.h);
expect(chart.legend.legendHitBoxes[i].left).toBeCloseToPixel(expected.l);
expect(chart.legend.legendHitBoxes[i].top).toBeCloseToPixel(expected.t);
expect(chart.legend.legendHitBoxes[i].width).toBeCloseToPixel(expected.w);
- })
+ });
// NOTE(SB) We should get ride of the following tests and use image diff instead.
// For now, as discussed with Evert Timberg, simply comment out.
// See http://humblesoftware.github.io/js-imagediff/test.html
- /*chart.legend.ctx = window.createMockContext();
+ /* chart.legend.ctx = window.createMockContext();
chart.update();
expect(chart.legend.ctx .getCalls()).toEqual([{ | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/core.plugin.tests.js | @@ -75,24 +75,52 @@ describe('Chart.plugins', function() {
};
Chart.plugins.register(myplugin);
- Chart.plugins.notify('trigger', [{ count: 10 }]);
+ Chart.plugins.notify('trigger', [{count: 10}]);
expect(myplugin.count).toBe(10);
});
it('should return TRUE if no plugin explicitly returns FALSE', function() {
- Chart.plugins.register({ check: function() {} });
- Chart.plugins.register({ check: function() { return; } });
- Chart.plugins.register({ check: function() { return null; } });
- Chart.plugins.register({ check: function() { return 42 } });
+ Chart.plugins.register({
+ check: function() {}
+ });
+ Chart.plugins.register({
+ check: function() {
+ return;
+ }
+ });
+ Chart.plugins.register({
+ check: function() {
+ return null;
+ }
+ });
+ Chart.plugins.register({
+ check: function() {
+ return 42;
+ }
+ });
var res = Chart.plugins.notify('check');
expect(res).toBeTruthy();
});
it('should return FALSE if no plugin explicitly returns FALSE', function() {
- Chart.plugins.register({ check: function() {} });
- Chart.plugins.register({ check: function() { return; } });
- Chart.plugins.register({ check: function() { return false; } });
- Chart.plugins.register({ check: function() { return 42 } });
+ Chart.plugins.register({
+ check: function() {}
+ });
+ Chart.plugins.register({
+ check: function() {
+ return;
+ }
+ });
+ Chart.plugins.register({
+ check: function() {
+ return false;
+ }
+ });
+ Chart.plugins.register({
+ check: function() {
+ return 42;
+ }
+ });
var res = Chart.plugins.notify('check');
expect(res).toBeFalsy();
}); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/core.scaleService.tests.js | @@ -15,7 +15,7 @@ describe('Test the scale service', function() {
expect(Chart.scaleService.getScaleDefaults(type)).toEqual(jasmine.objectContaining({
testProp: true
}));
-
+
Chart.scaleService.updateScaleDefaults(type, {
testProp: 'red',
newProp: 42 | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/core.title.tests.js | @@ -14,14 +14,14 @@ describe('Title block tests', function() {
fontStyle: 'bold',
padding: 10,
text: ''
- })
+ });
});
it('should update correctly', function() {
var chart = {};
var options = Chart.helpers.clone(Chart.defaults.global.title);
- options.text = "My title";
+ options.text = 'My title';
var title = new Chart.Title({
chart: chart,
@@ -50,7 +50,7 @@ describe('Title block tests', function() {
var chart = {};
var options = Chart.helpers.clone(Chart.defaults.global.title);
- options.text = "My title";
+ options.text = 'My title';
options.position = 'left';
var title = new Chart.Title({
@@ -81,7 +81,7 @@ describe('Title block tests', function() {
var context = window.createMockContext();
var options = Chart.helpers.clone(Chart.defaults.global.title);
- options.text = "My title";
+ options.text = 'My title';
var title = new Chart.Title({
chart: chart,
@@ -130,7 +130,7 @@ describe('Title block tests', function() {
var context = window.createMockContext();
var options = Chart.helpers.clone(Chart.defaults.global.title);
- options.text = "My title";
+ options.text = 'My title';
options.position = 'left';
var title = new Chart.Title({ | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/core.tooltip.tests.js | @@ -342,7 +342,7 @@ describe('Core.Tooltip', function() {
return 'title';
},
afterTitle: function() {
- return 'afterTitle'
+ return 'afterTitle';
},
beforeBody: function() {
return 'beforeBody';
@@ -366,7 +366,7 @@ describe('Core.Tooltip', function() {
return 'footer';
},
afterFooter: function() {
- return 'afterFooter'
+ return 'afterFooter';
}
}
}
@@ -494,9 +494,6 @@ describe('Core.Tooltip', function() {
var meta0 = chartInstance.getDatasetMeta(0);
var point0 = meta0.data[1];
- var meta1 = chartInstance.getDatasetMeta(1);
- var point1 = meta1.data[1];
-
var node = chartInstance.chart.canvas;
var rect = node.getBoundingClientRect();
| true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/defaultConfig.tests.js | @@ -1,6 +1,6 @@
// Test the bubble chart default config
-describe("Default Configs", function() {
- describe("Bubble Chart", function() {
+describe('Default Configs', function() {
+ describe('Bubble Chart', function() {
it('should return correct tooltip strings', function() {
var config = Chart.defaults.bubble;
var chart = window.acquireChart({
@@ -22,7 +22,7 @@ describe("Default Configs", function() {
chart.tooltip._active = [chart.getDatasetMeta(0).data[0]];
chart.tooltip.update();
- // Title is always blank
+ // Title is always blank
expect(chart.tooltip._model.title).toEqual([]);
expect(chart.tooltip._model.body).toEqual([{
before: [],
@@ -50,7 +50,7 @@ describe("Default Configs", function() {
chart.tooltip._active = [chart.getDatasetMeta(0).data[1]];
chart.tooltip.update();
- // Title is always blank
+ // Title is always blank
expect(chart.tooltip._model.title).toEqual([]);
expect(chart.tooltip._model.body).toEqual([{
before: [],
@@ -76,7 +76,7 @@ describe("Default Configs", function() {
chart.tooltip._active = [chart.getDatasetMeta(0).data[1]];
chart.tooltip.update();
- // Title is always blank
+ // Title is always blank
expect(chart.tooltip._model.title).toEqual([]);
expect(chart.tooltip._model.body).toEqual([{
before: [],
@@ -196,7 +196,7 @@ describe("Default Configs", function() {
chart.tooltip._active = [chart.getDatasetMeta(0).data[1]];
chart.tooltip.update();
- // Title is always blank
+ // Title is always blank
expect(chart.tooltip._model.title).toEqual([]);
expect(chart.tooltip._model.body).toEqual([{
before: [],
@@ -280,7 +280,7 @@ describe("Default Configs", function() {
options: config
});
var meta = chart.getDatasetMeta(0);
-
+
spyOn(chart, 'update').and.callThrough();
var legendItem = chart.legend.legendItems[0]; | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/element.arc.tests.js | @@ -213,4 +213,4 @@ describe('Arc element tests', function() {
args: []
}]);
});
-});
\ No newline at end of file
+}); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/element.line.tests.js | @@ -2580,4 +2580,4 @@ describe('Line element tests', function() {
args: []
}]);
});
-});
\ No newline at end of file
+}); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/element.point.tests.js | @@ -91,7 +91,7 @@ describe('Point element tests', function() {
y: 10
};
- expect(point.getCenterPoint()).toEqual({ x: 10, y: 10 });
+ expect(point.getCenterPoint()).toEqual({x: 10, y: 10});
});
it ('should draw correctly', function() {
@@ -275,7 +275,7 @@ describe('Point element tests', function() {
}, {
name: 'lineTo',
args: [12, 15],
- },{
+ }, {
name: 'closePath',
args: [],
}, {
@@ -347,7 +347,7 @@ describe('Point element tests', function() {
}, {
name: 'lineTo',
args: [12, 15],
- },{
+ }, {
name: 'moveTo',
args: [10 - Math.cos(Math.PI / 4) * 2, 15 - Math.sin(Math.PI / 4) * 2]
}, {
@@ -501,4 +501,4 @@ describe('Point element tests', function() {
expect(mockContext.getCalls()).toEqual([]);
});
-});
\ No newline at end of file
+}); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/element.rectangle.tests.js | @@ -163,7 +163,7 @@ describe('Rectangle element tests', function() {
y: 15
};
- expect(rectangle.getCenterPoint()).toEqual({ x: 10, y: 7.5 });
+ expect(rectangle.getCenterPoint()).toEqual({x: 10, y: 7.5});
});
it ('should draw correctly', function() {
@@ -276,10 +276,10 @@ describe('Rectangle element tests', function() {
}]);
});
- function testBorderSkipped (borderSkipped, expectedDrawCalls) {
+ function testBorderSkipped(borderSkipped, expectedDrawCalls) {
var mockContext = window.createMockContext();
var rectangle = new Chart.elements.Rectangle({
- _chart: { ctx: mockContext }
+ _chart: {ctx: mockContext}
});
// Attach a view object as if we were the controller
@@ -291,47 +291,47 @@ describe('Rectangle element tests', function() {
x: 10,
y: 15,
};
-
+
rectangle.draw();
- var drawCalls = rectangle._view.ctx.getCalls().splice(4, 4);
+ var drawCalls = rectangle._view.ctx.getCalls().splice(4, 4);
expect(drawCalls).toEqual(expectedDrawCalls);
}
-
+
it ('should draw correctly respecting "borderSkipped" == "bottom"', function() {
testBorderSkipped ('bottom', [
- { name: 'moveTo', args: [8, 0] },
- { name: 'lineTo', args: [8, 15] },
- { name: 'lineTo', args: [12, 15] },
- { name: 'lineTo', args: [12, 0] },
+ {name: 'moveTo', args: [8, 0]},
+ {name: 'lineTo', args: [8, 15]},
+ {name: 'lineTo', args: [12, 15]},
+ {name: 'lineTo', args: [12, 0]},
]);
});
it ('should draw correctly respecting "borderSkipped" == "left"', function() {
testBorderSkipped ('left', [
- { name: 'moveTo', args: [8, 15] },
- { name: 'lineTo', args: [12, 15] },
- { name: 'lineTo', args: [12, 0] },
- { name: 'lineTo', args: [8, 0] },
+ {name: 'moveTo', args: [8, 15]},
+ {name: 'lineTo', args: [12, 15]},
+ {name: 'lineTo', args: [12, 0]},
+ {name: 'lineTo', args: [8, 0]},
]);
});
it ('should draw correctly respecting "borderSkipped" == "top"', function() {
testBorderSkipped ('top', [
- { name: 'moveTo', args: [12, 15] },
- { name: 'lineTo', args: [12, 0] },
- { name: 'lineTo', args: [8, 0] },
- { name: 'lineTo', args: [8, 15] },
+ {name: 'moveTo', args: [12, 15]},
+ {name: 'lineTo', args: [12, 0]},
+ {name: 'lineTo', args: [8, 0]},
+ {name: 'lineTo', args: [8, 15]},
]);
});
it ('should draw correctly respecting "borderSkipped" == "right"', function() {
testBorderSkipped ('right', [
- { name: 'moveTo', args: [12, 0] },
- { name: 'lineTo', args: [8, 0] },
- { name: 'lineTo', args: [8, 15] },
- { name: 'lineTo', args: [12, 15] },
+ {name: 'moveTo', args: [12, 0]},
+ {name: 'lineTo', args: [8, 0]},
+ {name: 'lineTo', args: [8, 15]},
+ {name: 'lineTo', args: [12, 15]},
]);
});
-});
\ No newline at end of file
+}); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/mockContext.js | @@ -1,3 +1,5 @@
+/* eslint guard-for-in: 1 */
+/* eslint camelcase: 1 */
(function() {
// Code from http://stackoverflow.com/questions/4406864/html-canvas-unit-testing
var Context = function() {
@@ -13,44 +15,56 @@
// Define properties here so that we can record each time they are set
Object.defineProperties(this, {
- "fillStyle": {
- 'get': function() { return this._fillStyle; },
- 'set': function(style) {
+ fillStyle: {
+ get: function() {
+ return this._fillStyle;
+ },
+ set: function(style) {
this._fillStyle = style;
this.record('setFillStyle', [style]);
}
},
- 'lineCap': {
- 'get': function() { return this._lineCap; },
- 'set': function(cap) {
+ lineCap: {
+ get: function() {
+ return this._lineCap;
+ },
+ set: function(cap) {
this._lineCap = cap;
this.record('setLineCap', [cap]);
}
},
- 'lineDashOffset': {
- 'get': function() { return this._lineDashOffset; },
- 'set': function(offset) {
+ lineDashOffset: {
+ get: function() {
+ return this._lineDashOffset;
+ },
+ set: function(offset) {
this._lineDashOffset = offset;
this.record('setLineDashOffset', [offset]);
}
},
- 'lineJoin': {
- 'get': function() { return this._lineJoin; },
- 'set': function(join) {
+ lineJoin: {
+ get: function() {
+ return this._lineJoin;
+ },
+ set: function(join) {
this._lineJoin = join;
this.record('setLineJoin', [join]);
}
},
- 'lineWidth': {
- 'get': function() { return this._lineWidth; },
- 'set': function (width) {
+ lineWidth: {
+ get: function() {
+ return this._lineWidth;
+ },
+ set: function(width) {
this._lineWidth = width;
this.record('setLineWidth', [width]);
}
},
- 'strokeStyle': {
- 'get': function() { return this._strokeStyle; },
- 'set': function(style) {
+ strokeStyle: {
+ get: function() {
+ return this._strokeStyle;
+ },
+ set: function(style) {
this._strokeStyle = style;
this.record('setStrokeStyle', [style]);
}
@@ -70,33 +84,35 @@
fill: function() {},
fillRect: function() {},
fillText: function() {},
- lineTo: function(x, y) {},
+ lineTo: function() {},
measureText: function(text) {
// return the number of characters * fixed size
- return text ? { width: text.length * 10 } : {width: 0};
+ return text ? {width: text.length * 10} : {width: 0};
},
- moveTo: function(x, y) {},
+ moveTo: function() {},
quadraticCurveTo: function() {},
restore: function() {},
rotate: function() {},
save: function() {},
setLineDash: function() {},
stroke: function() {},
- strokeRect: function(x, y, w, h) {},
- setTransform: function(a, b, c, d, e, f) {},
- translate: function(x, y) {},
+ strokeRect: function() {},
+ setTransform: function() {},
+ translate: function() {},
};
// attach methods to the class itself
- var scope = this;
+ var me = this;
+ var methodName;
+
var addMethod = function(name, method) {
- scope[methodName] = function() {
- scope.record(name, arguments);
- return method.apply(scope, arguments);
+ me[methodName] = function() {
+ me.record(name, arguments);
+ return method.apply(me, arguments);
};
- }
+ };
- for (var methodName in methods) {
+ for (methodName in methods) {
var method = methods[methodName];
addMethod(methodName, method);
@@ -108,11 +124,11 @@
name: methodName,
args: Array.prototype.slice.call(args)
});
- },
+ };
Context.prototype.getCalls = function() {
return this._calls;
- }
+ };
Context.prototype.resetCalls = function() {
this._calls = [];
@@ -136,10 +152,10 @@
result = (diff <= (A > B ? A : B) * percentDiff) || diff < 2; // 2 pixels is fine
}
- return { pass: result };
+ return {pass: result};
}
- }
- };
+ };
+ }
function toEqualOneOf() {
return {
@@ -251,13 +267,13 @@
* @param {boolean} options.persistent - If true, the chart will not be released after the spec.
*/
function acquireChart(config, options) {
- var wrapper = document.createElement("div");
- var canvas = document.createElement("canvas");
+ var wrapper = document.createElement('div');
+ var canvas = document.createElement('canvas');
var chart, key;
options = options || {};
- options.canvas = options.canvas || { height: 512, width: 512 };
- options.wrapper = options.wrapper || { class: 'chartjs-wrapper' };
+ options.canvas = options.canvas || {height: 512, width: 512};
+ options.wrapper = options.wrapper || {class: 'chartjs-wrapper'};
for (key in options.canvas) {
if (options.canvas.hasOwnProperty(key)) {
@@ -280,7 +296,7 @@
wrapper.appendChild(canvas);
window.document.body.appendChild(wrapper);
- chart = new Chart(canvas.getContext("2d"), config);
+ chart = new Chart(canvas.getContext('2d'), config);
chart._test_persistent = options.persistent;
chart._test_wrapper = wrapper;
charts[chart.id] = chart;
@@ -329,4 +345,4 @@
'.chartjs-wrapper {' +
'position: absolute' +
'}');
-})();
+}()); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/scale.category.tests.js | @@ -13,20 +13,20 @@ describe('Category scale tests', function() {
display: true,
gridLines: {
- color: "rgba(0, 0, 0, 0.1)",
+ color: 'rgba(0, 0, 0, 0.1)',
drawBorder: true,
drawOnChartArea: true,
drawTicks: true, // draw ticks extending towards the label
tickMarkLength: 10,
lineWidth: 1,
offsetGridLines: false,
display: true,
- zeroLineColor: "rgba(0,0,0,0.25)",
+ zeroLineColor: 'rgba(0,0,0,0.25)',
zeroLineWidth: 1,
borderDash: [],
borderDashOffset: 0.0
},
- position: "bottom",
+ position: 'bottom',
scaleLabel: {
labelString: '',
display: false
@@ -287,8 +287,8 @@ describe('Category scale tests', function() {
var mockContext = window.createMockContext();
var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('category'));
config.gridLines.offsetGridLines = true;
- config.ticks.min = "tick2";
- config.ticks.max = "tick4";
+ config.ticks.min = 'tick2';
+ config.ticks.max = 'tick4';
var Constructor = Chart.scaleService.getScaleConstructor('category');
var scale = new Constructor({
@@ -349,7 +349,7 @@ describe('Category scale tests', function() {
var mockContext = window.createMockContext();
var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('category'));
config.gridLines.offsetGridLines = true;
- config.position = "left";
+ config.position = 'left';
var Constructor = Chart.scaleService.getScaleConstructor('category');
var scale = new Constructor({
ctx: mockContext,
@@ -414,9 +414,9 @@ describe('Category scale tests', function() {
var mockContext = window.createMockContext();
var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('category'));
config.gridLines.offsetGridLines = true;
- config.ticks.min = "tick2";
- config.ticks.max = "tick4";
- config.position = "left";
+ config.ticks.min = 'tick2';
+ config.ticks.max = 'tick4';
+ config.position = 'left';
var Constructor = Chart.scaleService.getScaleConstructor('category');
var scale = new Constructor({ | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/scale.linear.tests.js | @@ -11,20 +11,20 @@ describe('Linear Scale', function() {
display: true,
gridLines: {
- color: "rgba(0, 0, 0, 0.1)",
+ color: 'rgba(0, 0, 0, 0.1)',
drawBorder: true,
drawOnChartArea: true,
drawTicks: true, // draw ticks extending towards the label
tickMarkLength: 10,
lineWidth: 1,
offsetGridLines: false,
display: true,
- zeroLineColor: "rgba(0,0,0,0.25)",
+ zeroLineColor: 'rgba(0,0,0,0.25)',
zeroLineWidth: 1,
borderDash: [],
borderDashOffset: 0.0
},
- position: "left",
+ position: 'left',
scaleLabel: {
labelString: '',
display: false, | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/scale.logarithmic.tests.js | @@ -10,20 +10,20 @@ describe('Logarithmic Scale tests', function() {
expect(defaultConfig).toEqual({
display: true,
gridLines: {
- color: "rgba(0, 0, 0, 0.1)",
+ color: 'rgba(0, 0, 0, 0.1)',
drawBorder: true,
drawOnChartArea: true,
drawTicks: true,
tickMarkLength: 10,
lineWidth: 1,
offsetGridLines: false,
display: true,
- zeroLineColor: "rgba(0,0,0,0.25)",
+ zeroLineColor: 'rgba(0,0,0,0.25)',
zeroLineWidth: 1,
borderDash: [],
borderDashOffset: 0.0
},
- position: "left",
+ position: 'left',
scaleLabel: {
labelString: '',
display: false,
@@ -78,14 +78,14 @@ describe('Logarithmic Scale tests', function() {
id: 'yScale1',
type: 'logarithmic'
},
- {
- id: 'yScale2',
- type: 'logarithmic'
- },
- {
- id: 'yScale3',
- type: 'logarithmic'
- }]
+ {
+ id: 'yScale2',
+ type: 'logarithmic'
+ },
+ {
+ id: 'yScale3',
+ type: 'logarithmic'
+ }]
}
}
});
@@ -125,7 +125,7 @@ describe('Logarithmic Scale tests', function() {
data: ['20', '0', '150', '1800', '3040']
}, {
yAxisID: 'yScale3',
- data: ['67', '0.0004', '0', '820', '0.001']
+ data: ['67', '0.0004', '0', '820', '0.001']
}],
labels: ['a', 'b', 'c', 'd', 'e']
},
@@ -141,10 +141,10 @@ describe('Logarithmic Scale tests', function() {
id: 'yScale2',
type: 'logarithmic'
},
- {
- id: 'yScale3',
- type: 'logarithmic'
- }]
+ {
+ id: 'yScale3',
+ type: 'logarithmic'
+ }]
}
}
});
@@ -185,8 +185,8 @@ describe('Logarithmic Scale tests', function() {
data: [20, 0, 7400, 14, 291]
}, {
yAxisID: 'yScale2',
- data: [6, 0.0007, 9, 890, 60000],
- hidden: true
+ data: [6, 0.0007, 9, 890, 60000],
+ hidden: true
}],
labels: ['a', 'b', 'c', 'd', 'e']
},
@@ -232,7 +232,7 @@ describe('Logarithmic Scale tests', function() {
yAxisID: 'yScale1',
data: [undefined, 0, null, 800, 9, NaN, 894, 21]
}],
- labels: ['a', 'b', 'c', 'd', 'e', 'f' ,'g', 'h', 'i']
+ labels: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
},
options: {
scales: {
@@ -269,10 +269,10 @@ describe('Logarithmic Scale tests', function() {
data: {
datasets: [{
data: [
- { x: 10, y: 100 },
- { x: 2, y: 6 },
- { x: 65, y: 121 },
- { x: 99, y: 7 }
+ {x: 10, y: 100},
+ {x: 2, y: 6},
+ {x: 65, y: 121},
+ {x: 99, y: 7}
]
}]
},
@@ -304,10 +304,10 @@ describe('Logarithmic Scale tests', function() {
data: {
datasets: [{
data: [
- { x: 7, y: 950 },
- { x: 289, y: 0 },
- { x: 0, y: 8 },
- { x: 23, y: 0.04 }
+ {x: 7, y: 950},
+ {x: 289, y: 0},
+ {x: 0, y: 8},
+ {x: 23, y: 0.04}
]
}]
},
@@ -718,19 +718,19 @@ describe('Logarithmic Scale tests', function() {
var xScale = chart.scales.xScale;
expect(xScale.getPixelForValue(80, 0, 0)).toBeCloseToPixel(495); // right - paddingRight
- expect(xScale.getPixelForValue( 1, 0, 0)).toBeCloseToPixel(48); // left + paddingLeft
+ expect(xScale.getPixelForValue(1, 0, 0)).toBeCloseToPixel(48); // left + paddingLeft
expect(xScale.getPixelForValue(10, 0, 0)).toBeCloseToPixel(283); // halfway
- expect(xScale.getPixelForValue( 0, 0, 0)).toBeCloseToPixel(48); // 0 is invalid, put it on the left.
+ expect(xScale.getPixelForValue(0, 0, 0)).toBeCloseToPixel(48); // 0 is invalid, put it on the left.
expect(xScale.getValueForPixel(495)).toBeCloseTo(80, 1e-4);
expect(xScale.getValueForPixel(48)).toBeCloseTo(1, 1e-4);
expect(xScale.getValueForPixel(283)).toBeCloseTo(10, 1e-4);
var yScale = chart.scales.yScale;
expect(yScale.getPixelForValue(80, 0, 0)).toBeCloseToPixel(32); // top + paddingTop
- expect(yScale.getPixelForValue( 1, 0, 0)).toBeCloseToPixel(456); // bottom - paddingBottom
+ expect(yScale.getPixelForValue(1, 0, 0)).toBeCloseToPixel(456); // bottom - paddingBottom
expect(yScale.getPixelForValue(10, 0, 0)).toBeCloseToPixel(234); // halfway
- expect(yScale.getPixelForValue( 0, 0, 0)).toBeCloseToPixel(32); // 0 is invalid. force it on top
+ expect(yScale.getPixelForValue(0, 0, 0)).toBeCloseToPixel(32); // 0 is invalid. force it on top
expect(yScale.getValueForPixel(32)).toBeCloseTo(80, 1e-4);
expect(yScale.getValueForPixel(456)).toBeCloseTo(1, 1e-4); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/scale.radialLinear.tests.js | @@ -11,21 +11,21 @@ describe('Test the radial linear scale', function() {
expect(defaultConfig).toEqual({
angleLines: {
display: true,
- color: "rgba(0, 0, 0, 0.1)",
+ color: 'rgba(0, 0, 0, 0.1)',
lineWidth: 1
},
animate: true,
display: true,
gridLines: {
- color: "rgba(0, 0, 0, 0.1)",
+ color: 'rgba(0, 0, 0, 0.1)',
drawBorder: true,
drawOnChartArea: true,
drawTicks: true,
tickMarkLength: 10,
lineWidth: 1,
offsetGridLines: false,
display: true,
- zeroLineColor: "rgba(0,0,0,0.25)",
+ zeroLineColor: 'rgba(0,0,0,0.25)',
zeroLineWidth: 1,
borderDash: [],
borderDashOffset: 0.0
@@ -35,13 +35,13 @@ describe('Test the radial linear scale', function() {
fontSize: 10,
callback: defaultConfig.pointLabels.callback, // make this nicer, then check explicitly below
},
- position: "chartArea",
+ position: 'chartArea',
scaleLabel: {
labelString: '',
display: false,
},
ticks: {
- backdropColor: "rgba(255,255,255,0.75)",
+ backdropColor: 'rgba(255,255,255,0.75)',
backdropPaddingY: 2,
backdropPaddingX: 2,
beginAtZero: false,
@@ -426,19 +426,19 @@ describe('Test the radial linear scale', function() {
var radToNearestDegree = function(rad) {
return Math.round((360 * rad) / (2 * Math.PI));
- }
+ };
var slice = 72; // (360 / 5)
- for(var i = 0; i < 5; i++) {
+ for (var i = 0; i < 5; i++) {
expect(radToNearestDegree(chart.scale.getIndexAngle(i))).toBe(15 + (slice * i) - 90);
}
chart.options.startAngle = 0;
chart.update();
- for(var i = 0; i < 5; i++) {
- expect(radToNearestDegree(chart.scale.getIndexAngle(i))).toBe((slice * i) - 90);
+ for (var x = 0; x < 5; x++) {
+ expect(radToNearestDegree(chart.scale.getIndexAngle(x))).toBe((slice * x) - 90);
}
});
}); | true |
Other | chartjs | Chart.js | 766ca49cd094562f3a2e870e0c2b162ee16c8189.json | Extend eslint to test files (#3473)
* Add eslint to test files
* Fix mockContext for tests
* Make formatting look better for nested objects | test/scale.time.tests.js | @@ -15,7 +15,7 @@ describe('Time scale tests', function() {
pass: result
};
}
- }
+ };
}
});
});
@@ -35,20 +35,20 @@ describe('Time scale tests', function() {
expect(defaultConfig).toEqual({
display: true,
gridLines: {
- color: "rgba(0, 0, 0, 0.1)",
+ color: 'rgba(0, 0, 0, 0.1)',
drawBorder: true,
drawOnChartArea: true,
drawTicks: true,
tickMarkLength: 10,
lineWidth: 1,
offsetGridLines: false,
display: true,
- zeroLineColor: "rgba(0,0,0,0.25)",
+ zeroLineColor: 'rgba(0,0,0,0.25)',
zeroLineWidth: 1,
borderDash: [],
borderDashOffset: 0.0
},
- position: "bottom",
+ position: 'bottom',
scaleLabel: {
labelString: '',
display: false
@@ -75,15 +75,15 @@ describe('Time scale tests', function() {
displayFormat: false,
minUnit: 'millisecond',
displayFormats: {
- 'millisecond': 'h:mm:ss.SSS a', // 11:20:01.123 AM
- 'second': 'h:mm:ss a', // 11:20:01 AM
- 'minute': 'h:mm:ss a', // 11:20:01 AM
- 'hour': 'MMM D, hA', // Sept 4, 5PM
- 'day': 'll', // Sep 4 2015
- 'week': 'll', // Week 46, or maybe "[W]WW - YYYY" ?
- 'month': 'MMM YYYY', // Sept 2015
- 'quarter': '[Q]Q - YYYY', // Q3
- 'year': 'YYYY' // 2015
+ millisecond: 'h:mm:ss.SSS a', // 11:20:01.123 AM
+ second: 'h:mm:ss a', // 11:20:01 AM
+ minute: 'h:mm:ss a', // 11:20:01 AM
+ hour: 'MMM D, hA', // Sept 4, 5PM
+ day: 'll', // Sep 4 2015
+ week: 'll', // Week 46, or maybe "[W]WW - YYYY" ?
+ month: 'MMM YYYY', // Sept 2015
+ quarter: '[Q]Q - YYYY', // Q3
+ year: 'YYYY' // 2015
}
}
});
@@ -96,7 +96,7 @@ describe('Time scale tests', function() {
var scaleID = 'myScale';
var mockData = {
- labels: ["2015-01-01T20:00:00", "2015-01-02T21:00:00", "2015-01-03T22:00:00", "2015-01-05T23:00:00", "2015-01-07T03:00", "2015-01-08T10:00", "2015-01-10T12:00"], // days
+ labels: ['2015-01-01T20:00:00', '2015-01-02T21:00:00', '2015-01-03T22:00:00', '2015-01-05T23:00:00', '2015-01-07T03:00', '2015-01-08T10:00', '2015-01-10T12:00'], // days
};
var mockContext = window.createMockContext();
@@ -110,11 +110,11 @@ describe('Time scale tests', function() {
id: scaleID
});
- //scale.buildTicks();
+ // scale.buildTicks();
scale.update(400, 50);
// Counts down because the lines are drawn top to bottom
- expect(scale.ticks).toEqual([ 'Dec 28, 2014', 'Jan 4, 2015', 'Jan 11, 2015' ]);
+ expect(scale.ticks).toEqual(['Dec 28, 2014', 'Jan 4, 2015', 'Jan 11, 2015']);
});
it('should build ticks using date objects', function() {
@@ -142,7 +142,7 @@ describe('Time scale tests', function() {
scale.update(400, 50);
// Counts down because the lines are drawn top to bottom
- expect(scale.ticks).toEqual([ 'Dec 28, 2014', 'Jan 4, 2015', 'Jan 11, 2015' ]);
+ expect(scale.ticks).toEqual(['Dec 28, 2014', 'Jan 4, 2015', 'Jan 11, 2015']);
});
it('should build ticks when the data is xy points', function() {
@@ -198,7 +198,7 @@ describe('Time scale tests', function() {
// Counts down because the lines are drawn top to bottom
var xScale = chart.scales.xScale0;
- expect(xScale.ticks).toEqual([ 'Jan 1, 2015', 'Jan 3, 2015', 'Jan 5, 2015', 'Jan 7, 2015', 'Jan 9, 2015', 'Jan 11, 2015' ]);
+ expect(xScale.ticks).toEqual(['Jan 1, 2015', 'Jan 3, 2015', 'Jan 5, 2015', 'Jan 7, 2015', 'Jan 9, 2015', 'Jan 11, 2015']);
});
it('should allow custom time parsers', function() {
@@ -223,7 +223,7 @@ describe('Time scale tests', function() {
time: {
unit: 'day',
round: true,
- parser: function customTimeParser(label) {
+ parser: function(label) {
return moment.unix(label);
}
}
@@ -248,7 +248,7 @@ describe('Time scale tests', function() {
var scaleID = 'myScale';
var mockData = {
- labels: ["2015-01-01T20:00:00", "2015-01-02T21:00:00"], // days
+ labels: ['2015-01-01T20:00:00', '2015-01-02T21:00:00'], // days
};
var mockContext = window.createMockContext();
@@ -264,7 +264,7 @@ describe('Time scale tests', function() {
id: scaleID
});
- //scale.buildTicks();
+ // scale.buildTicks();
scale.update(400, 50);
expect(scale.ticks).toEqual(['Jan 1, 8PM', 'Jan 1, 9PM', 'Jan 1, 10PM', 'Jan 1, 11PM', 'Jan 2, 12AM', 'Jan 2, 1AM', 'Jan 2, 2AM', 'Jan 2, 3AM', 'Jan 2, 4AM', 'Jan 2, 5AM', 'Jan 2, 6AM', 'Jan 2, 7AM', 'Jan 2, 8AM', 'Jan 2, 9AM', 'Jan 2, 10AM', 'Jan 2, 11AM', 'Jan 2, 12PM', 'Jan 2, 1PM', 'Jan 2, 2PM', 'Jan 2, 3PM', 'Jan 2, 4PM', 'Jan 2, 5PM', 'Jan 2, 6PM', 'Jan 2, 7PM', 'Jan 2, 8PM', 'Jan 2, 9PM']);
});
@@ -273,7 +273,7 @@ describe('Time scale tests', function() {
var scaleID = 'myScale';
var mockData = {
- labels: ["2015-01-01T20:00:00", "2015-01-02T21:00:00"], // days
+ labels: ['2015-01-01T20:00:00', '2015-01-02T21:00:00'], // days
};
var mockContext = window.createMockContext();
@@ -289,7 +289,7 @@ describe('Time scale tests', function() {
id: scaleID
});
- //scale.buildTicks();
+ // scale.buildTicks();
scale.update(400, 50);
expect(scale.ticks).toEqual(['Jan 1, 2015', 'Jan 2, 2015', 'Jan 3, 2015']);
});
@@ -298,7 +298,7 @@ describe('Time scale tests', function() {
var scaleID = 'myScale';
var mockData = {
- labels: ["2015-01-01T20:00:00", "2015-02-02T21:00:00", "2015-02-21T01:00:00"], // days
+ labels: ['2015-01-01T20:00:00', '2015-02-02T21:00:00', '2015-02-21T01:00:00'], // days
};
var mockContext = window.createMockContext();
@@ -315,7 +315,7 @@ describe('Time scale tests', function() {
id: scaleID
});
- //scale.buildTicks();
+ // scale.buildTicks();
scale.update(400, 50);
// last date is feb 15 because we round to start of week
@@ -326,13 +326,13 @@ describe('Time scale tests', function() {
var scaleID = 'myScale';
var mockData = {
- labels: ["2015-01-01T20:00:00", "2015-01-02T20:00:00", "2015-01-03T20:00:00"], // days
+ labels: ['2015-01-01T20:00:00', '2015-01-02T20:00:00', '2015-01-03T20:00:00'], // days
};
var mockContext = window.createMockContext();
var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('time'));
- config.time.min = "2015-01-01T04:00:00";
- config.time.max = "2015-01-05T06:00:00"
+ config.time.min = '2015-01-01T04:00:00';
+ config.time.max = '2015-01-05T06:00:00';
var Constructor = Chart.scaleService.getScaleConstructor('time');
var scale = new Constructor({
ctx: mockContext,
@@ -344,17 +344,17 @@ describe('Time scale tests', function() {
});
scale.update(400, 50);
- expect(scale.ticks).toEqual([ 'Jan 1, 2015', 'Jan 5, 2015' ]);
+ expect(scale.ticks).toEqual(['Jan 1, 2015', 'Jan 5, 2015']);
});
it('Should use the isoWeekday option', function() {
var scaleID = 'myScale';
var mockData = {
labels: [
- "2015-01-01T20:00:00", // Thursday
- "2015-01-02T20:00:00", // Friday
- "2015-01-03T20:00:00" // Saturday
+ '2015-01-01T20:00:00', // Thursday
+ '2015-01-02T20:00:00', // Friday
+ '2015-01-03T20:00:00' // Saturday
]
};
@@ -374,7 +374,7 @@ describe('Time scale tests', function() {
});
scale.update(400, 50);
- expect(scale.ticks).toEqual([ 'Dec 31, 2014', 'Jan 7, 2015' ]);
+ expect(scale.ticks).toEqual(['Dec 31, 2014', 'Jan 7, 2015']);
});
it('should get the correct pixel for a value', function() {
@@ -386,7 +386,7 @@ describe('Time scale tests', function() {
yAxisID: 'yScale0',
data: []
}],
- labels: ["2015-01-01T20:00:00", "2015-01-02T21:00:00", "2015-01-03T22:00:00", "2015-01-05T23:00:00", "2015-01-07T03:00", "2015-01-08T10:00", "2015-01-10T12:00"], // days
+ labels: ['2015-01-01T20:00:00', '2015-01-02T21:00:00', '2015-01-03T22:00:00', '2015-01-05T23:00:00', '2015-01-07T03:00', '2015-01-08T10:00', '2015-01-10T12:00'], // days
},
options: {
scales: {
@@ -430,7 +430,7 @@ describe('Time scale tests', function() {
yAxisID: 'yScale0',
data: []
}],
- labels: ["2015-01-01T20:00:00", "2015-01-02T21:00:00", "2015-01-03T22:00:00", "2015-01-05T23:00:00", "2015-01-07T03:00", "2015-01-08T10:00", "2015-01-10T12:00"], // days
+ labels: ['2015-01-01T20:00:00', '2015-01-02T21:00:00', '2015-01-03T22:00:00', '2015-01-05T23:00:00', '2015-01-07T03:00', '2015-01-08T10:00', '2015-01-10T12:00'], // days
},
options: {
scales: {
@@ -457,7 +457,7 @@ describe('Time scale tests', function() {
var chart = window.acquireChart({
type: 'line',
data: {
- labels: ["2016-05-27"],
+ labels: ['2016-05-27'],
datasets: [{
xAxisID: 'xScale0',
data: [5]
@@ -468,7 +468,7 @@ describe('Time scale tests', function() {
xAxes: [{
id: 'xScale0',
display: true,
- type: "time"
+ type: 'time'
}]
}
}
@@ -485,11 +485,11 @@ describe('Time scale tests', function() {
});
});
- it("should not throw an error if the datasetIndex is out of bounds", function() {
+ it('should not throw an error if the datasetIndex is out of bounds', function() {
var chart = window.acquireChart({
type: 'line',
data: {
- labels: ["2016-06-26"],
+ labels: ['2016-06-26'],
datasets: [{
xAxisID: 'xScale0',
data: [5]
@@ -500,7 +500,7 @@ describe('Time scale tests', function() {
xAxes: [{
id: 'xScale0',
display: true,
- type: "time",
+ type: 'time',
}]
}
}
@@ -514,11 +514,11 @@ describe('Time scale tests', function() {
expect(getOutOfBoundLabelMoment).not.toThrow();
});
- it("should not throw an error if the datasetIndex or index are null", function() {
+ it('should not throw an error if the datasetIndex or index are null', function() {
var chart = window.acquireChart({
type: 'line',
data: {
- labels: ["2016-06-26"],
+ labels: ['2016-06-26'],
datasets: [{
xAxisID: 'xScale0',
data: [5]
@@ -529,7 +529,7 @@ describe('Time scale tests', function() {
xAxes: [{
id: 'xScale0',
display: true,
- type: "time",
+ type: 'time',
}]
}
} | true |
Other | chartjs | Chart.js | 4a5b5a0e7eba85ca44f658375cb0c78e6af93e5c.json | Enhance context acquisition on chart creation
Add support for creating a chart from the canvas id and prevent exceptions, at construction time, when the given item doesn't provide a valid CanvasRenderingContext2D or when the getContext API is not accessible (e.g. undefined by add-ons to prevent fingerprinting). New jasmine matcher to verify chart validity. | .gitignore | @@ -6,4 +6,5 @@
.DS_Store
.idea
+.vscode
bower.json | true |
Other | chartjs | Chart.js | 4a5b5a0e7eba85ca44f658375cb0c78e6af93e5c.json | Enhance context acquisition on chart creation
Add support for creating a chart from the canvas id and prevent exceptions, at construction time, when the given item doesn't provide a valid CanvasRenderingContext2D or when the getContext API is not accessible (e.g. undefined by add-ons to prevent fingerprinting). New jasmine matcher to verify chart validity. | docs/00-Getting-Started.md | @@ -71,6 +71,7 @@ To create a chart, we need to instantiate the `Chart` class. To do this, we need
var ctx = document.getElementById("myChart");
var ctx = document.getElementById("myChart").getContext("2d");
var ctx = $("#myChart");
+var ctx = "myChart";
```
Once you have the element or context, you're ready to instantiate a pre-defined chart-type or create your own! | true |
Other | chartjs | Chart.js | 4a5b5a0e7eba85ca44f658375cb0c78e6af93e5c.json | Enhance context acquisition on chart creation
Add support for creating a chart from the canvas id and prevent exceptions, at construction time, when the given item doesn't provide a valid CanvasRenderingContext2D or when the getContext API is not accessible (e.g. undefined by add-ons to prevent fingerprinting). New jasmine matcher to verify chart validity. | src/core/core.controller.js | @@ -112,6 +112,36 @@ module.exports = function(Chart) {
delete canvas._chartjs;
}
+ /**
+ * TODO(SB) Move this method in the upcoming core.platform class.
+ */
+ function acquireContext(item, config) {
+ if (typeof item === 'string') {
+ item = document.getElementById(item);
+ } else if (item.length) {
+ // Support for array based queries (such as jQuery)
+ item = item[0];
+ }
+
+ if (item && item.canvas) {
+ // Support for any object associated to a canvas (including a context2d)
+ item = item.canvas;
+ }
+
+ if (item instanceof HTMLCanvasElement) {
+ // To prevent canvas fingerprinting, some add-ons undefine the getContext
+ // method, for example: https://github.com/kkapsner/CanvasBlocker
+ // https://github.com/chartjs/Chart.js/issues/2807
+ var context = item.getContext && item.getContext('2d');
+ if (context instanceof CanvasRenderingContext2D) {
+ initCanvas(item, config);
+ return context;
+ }
+ }
+
+ return null;
+ }
+
/**
* Initializes the given config with global and chart default values.
*/
@@ -136,21 +166,22 @@ module.exports = function(Chart) {
* @class Chart.Controller
* The main controller of a chart.
*/
- Chart.Controller = function(context, config, instance) {
+ Chart.Controller = function(item, config, instance) {
var me = this;
- var canvas;
config = initConfig(config);
- canvas = initCanvas(context.canvas, config);
+
+ var context = acquireContext(item, config);
+ var canvas = context && context.canvas;
+ var height = canvas && canvas.height;
+ var width = canvas && canvas.width;
instance.ctx = context;
instance.canvas = canvas;
instance.config = config;
- instance.width = canvas.width;
- instance.height = canvas.height;
- instance.aspectRatio = canvas.width / canvas.height;
-
- helpers.retinaScale(instance);
+ instance.width = width;
+ instance.height = height;
+ instance.aspectRatio = height? width / height : null;
me.id = helpers.uid();
me.chart = instance;
@@ -167,6 +198,17 @@ module.exports = function(Chart) {
}
});
+ if (!context || !canvas) {
+ // The given item is not a compatible context2d element, let's return before finalizing
+ // the chart initialization but after setting basic chart / controller properties that
+ // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
+ // https://github.com/chartjs/Chart.js/issues/2807
+ console.error("Failed to create chart: can't acquire context from the given item");
+ return me;
+ }
+
+ helpers.retinaScale(instance);
+
// Responsiveness is currently based on the use of an iframe, however this method causes
// performance issues and could be troublesome when used with ad blockers. So make sure
// that the user is still able to create a chart without iframe when responsive is false.
@@ -593,7 +635,6 @@ module.exports = function(Chart) {
var meta, i, ilen;
me.stop();
- me.clear();
// dataset controllers need to cleanup associated data
for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
@@ -607,8 +648,10 @@ module.exports = function(Chart) {
if (canvas) {
helpers.unbindEvents(me, me.events);
helpers.removeResizeListener(canvas.parentNode);
+ helpers.clear(me.chart);
releaseCanvas(canvas);
me.chart.canvas = null;
+ me.chart.ctx = null;
}
// if we scaled the canvas in response to a devicePixelRatio !== 1, we need to undo that transform here | true |
Other | chartjs | Chart.js | 4a5b5a0e7eba85ca44f658375cb0c78e6af93e5c.json | Enhance context acquisition on chart creation
Add support for creating a chart from the canvas id and prevent exceptions, at construction time, when the given item doesn't provide a valid CanvasRenderingContext2D or when the getContext API is not accessible (e.g. undefined by add-ons to prevent fingerprinting). New jasmine matcher to verify chart validity. | src/core/core.js | @@ -3,22 +3,9 @@
module.exports = function() {
// Occupy the global variable of Chart, and create a simple base class
- var Chart = function(context, config) {
- var me = this;
-
- // Support a jQuery'd canvas element
- if (context.length && context[0].getContext) {
- context = context[0];
- }
-
- // Support a canvas domnode
- if (context.getContext) {
- context = context.getContext('2d');
- }
-
- me.controller = new Chart.Controller(context, config, me);
-
- return me.controller;
+ var Chart = function(item, config) {
+ this.controller = new Chart.Controller(item, config, this);
+ return this.controller;
};
// Globally expose the defaults to allow for user updating/changing | true |
Other | chartjs | Chart.js | 4a5b5a0e7eba85ca44f658375cb0c78e6af93e5c.json | Enhance context acquisition on chart creation
Add support for creating a chart from the canvas id and prevent exceptions, at construction time, when the given item doesn't provide a valid CanvasRenderingContext2D or when the getContext API is not accessible (e.g. undefined by add-ons to prevent fingerprinting). New jasmine matcher to verify chart validity. | test/core.controller.tests.js | @@ -4,7 +4,75 @@ describe('Chart.Controller', function() {
setTimeout(callback, 100);
}
- describe('config', function() {
+ describe('context acquisition', function() {
+ var canvasId = 'chartjs-canvas';
+
+ beforeEach(function() {
+ var canvas = document.createElement('canvas');
+ canvas.setAttribute('id', canvasId);
+ window.document.body.appendChild(canvas);
+ });
+
+ afterEach(function() {
+ document.getElementById(canvasId).remove();
+ });
+
+ // see https://github.com/chartjs/Chart.js/issues/2807
+ it('should gracefully handle invalid item', function() {
+ var chart = new Chart('foobar');
+
+ expect(chart).not.toBeValidChart();
+
+ chart.destroy();
+ });
+
+ it('should accept a DOM element id', function() {
+ var canvas = document.getElementById(canvasId);
+ var chart = new Chart(canvasId);
+
+ expect(chart).toBeValidChart();
+ expect(chart.chart.canvas).toBe(canvas);
+ expect(chart.chart.ctx).toBe(canvas.getContext('2d'));
+
+ chart.destroy();
+ });
+
+ it('should accept a canvas element', function() {
+ var canvas = document.getElementById(canvasId);
+ var chart = new Chart(canvas);
+
+ expect(chart).toBeValidChart();
+ expect(chart.chart.canvas).toBe(canvas);
+ expect(chart.chart.ctx).toBe(canvas.getContext('2d'));
+
+ chart.destroy();
+ });
+
+ it('should accept a canvas context2D', function() {
+ var canvas = document.getElementById(canvasId);
+ var context = canvas.getContext('2d');
+ var chart = new Chart(context);
+
+ expect(chart).toBeValidChart();
+ expect(chart.chart.canvas).toBe(canvas);
+ expect(chart.chart.ctx).toBe(context);
+
+ chart.destroy();
+ });
+
+ it('should accept an array containing canvas', function() {
+ var canvas = document.getElementById(canvasId);
+ var chart = new Chart([canvas]);
+
+ expect(chart).toBeValidChart();
+ expect(chart.chart.canvas).toBe(canvas);
+ expect(chart.chart.ctx).toBe(canvas.getContext('2d'));
+
+ chart.destroy();
+ });
+ });
+
+ describe('config initialization', function() {
it('should create missing config.data properties', function() {
var chart = acquireChart({});
var data = chart.data; | true |
Other | chartjs | Chart.js | 4a5b5a0e7eba85ca44f658375cb0c78e6af93e5c.json | Enhance context acquisition on chart creation
Add support for creating a chart from the canvas id and prevent exceptions, at construction time, when the given item doesn't provide a valid CanvasRenderingContext2D or when the getContext API is not accessible (e.g. undefined by add-ons to prevent fingerprinting). New jasmine matcher to verify chart validity. | test/mockContext.js | @@ -158,54 +158,82 @@
};
}
+ function toBeValidChart() {
+ return {
+ compare: function(actual) {
+ var chart = actual && actual.chart;
+ var message = null;
+
+ if (!(actual instanceof Chart.Controller)) {
+ message = 'Expected ' + actual + ' to be an instance of Chart.Controller';
+ } else if (!(chart instanceof Chart)) {
+ message = 'Expected chart to be an instance of Chart';
+ } else if (!(chart.canvas instanceof HTMLCanvasElement)) {
+ message = 'Expected canvas to be an instance of HTMLCanvasElement';
+ } else if (!(chart.ctx instanceof CanvasRenderingContext2D)) {
+ message = 'Expected context to be an instance of CanvasRenderingContext2D';
+ } else if (typeof chart.height !== 'number' || !isFinite(chart.height)) {
+ message = 'Expected height to be a strict finite number';
+ } else if (typeof chart.width !== 'number' || !isFinite(chart.width)) {
+ message = 'Expected width to be a strict finite number';
+ }
+
+ return {
+ message: message? message : 'Expected ' + actual + ' to be valid chart',
+ pass: !message
+ };
+ }
+ };
+ }
+
function toBeChartOfSize() {
return {
compare: function(actual, expected) {
+ var res = toBeValidChart().compare(actual);
+ if (!res.pass) {
+ return res;
+ }
+
var message = null;
- var chart, canvas, style, dh, dw, rh, rw;
-
- if (!actual || !(actual instanceof Chart.Controller)) {
- message = 'Expected ' + actual + ' to be an instance of Chart.Controller.';
- } else {
- chart = actual.chart;
- canvas = chart.ctx.canvas;
- style = getComputedStyle(canvas);
- dh = parseInt(style.height);
- dw = parseInt(style.width);
- rh = canvas.height;
- rw = canvas.width;
-
- // sanity checks
- if (chart.height !== rh) {
- message = 'Expected chart height ' + chart.height + ' to be equal to render height ' + rh;
- } else if (chart.width !== rw) {
- message = 'Expected chart width ' + chart.width + ' to be equal to render width ' + rw;
- }
+ var chart = actual.chart;
+ var canvas = chart.ctx.canvas;
+ var style = getComputedStyle(canvas);
+ var dh = parseInt(style.height, 10);
+ var dw = parseInt(style.width, 10);
+ var rh = canvas.height;
+ var rw = canvas.width;
+
+ // sanity checks
+ if (chart.height !== rh) {
+ message = 'Expected chart height ' + chart.height + ' to be equal to render height ' + rh;
+ } else if (chart.width !== rw) {
+ message = 'Expected chart width ' + chart.width + ' to be equal to render width ' + rw;
+ }
- // validity checks
- if (dh !== expected.dh) {
- message = 'Expected display height ' + dh + ' to be equal to ' + expected.dh;
- } else if (dw !== expected.dw) {
- message = 'Expected display width ' + dw + ' to be equal to ' + expected.dw;
- } else if (rh !== expected.rh) {
- message = 'Expected render height ' + rh + ' to be equal to ' + expected.rh;
- } else if (rw !== expected.rw) {
- message = 'Expected render width ' + rw + ' to be equal to ' + expected.rw;
- }
+ // validity checks
+ if (dh !== expected.dh) {
+ message = 'Expected display height ' + dh + ' to be equal to ' + expected.dh;
+ } else if (dw !== expected.dw) {
+ message = 'Expected display width ' + dw + ' to be equal to ' + expected.dw;
+ } else if (rh !== expected.rh) {
+ message = 'Expected render height ' + rh + ' to be equal to ' + expected.rh;
+ } else if (rw !== expected.rw) {
+ message = 'Expected render width ' + rw + ' to be equal to ' + expected.rw;
}
return {
message: message? message : 'Expected ' + actual + ' to be a chart of size ' + expected,
pass: !message
- }
+ };
}
- }
+ };
}
beforeEach(function() {
jasmine.addMatchers({
toBeCloseToPixel: toBeCloseToPixel,
toEqualOneOf: toEqualOneOf,
+ toBeValidChart: toBeValidChart,
toBeChartOfSize: toBeChartOfSize
});
}); | true |
Other | chartjs | Chart.js | f481746fe1e56a1b0b88eae150863471d3550478.json | Update the GitHub issue template | .github/ISSUE_TEMPLATE.md | @@ -1,9 +1,40 @@
+<!--
Please consider the following before submitting an issue:
-Guidelines for contributing: https://github.com/chartjs/Chart.js/blob/master/CONTRIBUTING.md
+- Issues are reserved for BUG reports and FEATURE requests, DO NOT create issues for questions or support requests.
+- Most features should start as plugins outside of Chart.js (http://www.chartjs.org/docs/#advanced-usage-creating-plugins).
+- Bug reports MUST be submitted with an interactive example (http://codepen.io/pen?template=JXVYzq).
+- Chart.js 1.x is NOT supported anymore, new issues will be disregarded.
+-->
-Example of issue on an interactive website such as the following:
-- http://jsbin.com/
-- http://jsfiddle.net/
-- http://codepen.io/pen/
-- Premade template: http://codepen.io/pen?template=JXVYzq
\ No newline at end of file
+<!--- Provide a general summary of the issue in the Title above prefixed by [BUG] or [FEATURE] -->
+
+## Expected Behavior
+<!--- If you're describing a bug, tell us what should happen -->
+<!--- If you're suggesting a change/improvement, tell us how it should work -->
+
+## Current Behavior
+<!--- If describing a bug, tell us what happens instead of the expected behavior -->
+<!--- If suggesting a change/improvement, explain the difference from current behavior -->
+
+## Possible Solution
+<!--- Not obligatory, but suggest a fix/reason for the bug, -->
+<!--- or ideas how to implement the addition or change -->
+
+## Steps to Reproduce (for bugs)
+<!--- Provide a link to a live example, or an unambiguous set of steps to -->
+<!--- reproduce this bug. Include code to reproduce, if relevant -->
+1.
+2.
+3.
+4.
+
+## Context
+<!--- How has this issue affected you? What are you trying to accomplish? -->
+<!--- Providing context helps us come up with a solution that is most useful in the real world -->
+
+## Environment
+<!--- Include as many relevant details about the environment you experienced the bug in -->
+* Chart.js version:
+* Browser name and version:
+* Link to your project: | false |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | docs/01-Chart-Configuration.md | @@ -36,13 +36,13 @@ This concept was introduced in Chart.js 1.0 to keep configuration [DRY](https://
Chart.js merges the options object passed to the chart with the global configuration using chart type defaults and scales defaults appropriately. This way you can be as specific as you would like in your individual chart configuration, while still changing the defaults for all chart types where applicable. The global general options are defined in `Chart.defaults.global`. The defaults for each chart type are discussed in the documentation for that chart type.
-The following example would set the hover mode to 'single' for all charts where this was not overridden by the chart type defaults or the options passed to the constructor on creation.
+The following example would set the hover mode to 'nearest' for all charts where this was not overridden by the chart type defaults or the options passed to the constructor on creation.
```javascript
-Chart.defaults.global.hover.mode = 'single';
+Chart.defaults.global.hover.mode = 'nearest';
-// Hover mode is set to single because it was not overridden here
-var chartInstanceHoverModeSingle = new Chart(ctx, {
+// Hover mode is set to nearest because it was not overridden here
+var chartInstanceHoverModeNearest = new Chart(ctx, {
type: 'line',
data: data,
});
@@ -54,7 +54,7 @@ var chartInstanceDifferentHoverMode = new Chart(ctx, {
options: {
hover: {
// Overrides the global setting
- mode: 'label'
+ mode: 'index'
}
}
})
@@ -200,7 +200,7 @@ var chartInstance = new Chart(ctx, {
fontColor: 'rgb(255, 99, 132)'
}
}
- }
+}
});
```
@@ -212,7 +212,8 @@ Name | Type | Default | Description
--- | --- | --- | ---
enabled | Boolean | true | Are tooltips enabled
custom | Function | null | See [section](#advanced-usage-external-tooltips) below
-mode | String | 'single' | Sets which elements appear in the tooltip. Acceptable options are `'single'`, `'label'` or `'x-axis'`. <br> <br>`single` highlights the closest element. <br> <br>`label` highlights elements in all datasets at the same `X` value. <br> <br>`'x-axis'` also highlights elements in all datasets at the same `X` value, but activates when hovering anywhere within the vertical slice of the x-axis representing that `X` value.
+mode | String | 'nearest' | Sets which elements appear in the tooltip. See [Interaction Modes](#interaction-modes) for details
+intersect | Boolean | true | if true, the tooltip mode applies only when the mouse position intersects with an element. If false, the mode will be applied at all times.
itemSort | Function | undefined | Allows sorting of [tooltip items](#chart-configuration-tooltip-item-interface). Must implement at minimum a function that can be passed to [Array.prototype.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). This function can also accept a third parameter that is the data object passed to the chart.
backgroundColor | Color | 'rgba(0,0,0,0.8)' | Background color of the tooltip
titleFontFamily | String | "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" | Font family for tooltip title inherited from global font family
@@ -286,10 +287,28 @@ The hover configuration is passed into the `options.hover` namespace. The global
Name | Type | Default | Description
--- | --- | --- | ---
-mode | String | 'single' | Sets which elements hover. Acceptable options are `'single'`, `'label'`, `'x-axis'`, or `'dataset'`. <br> <br>`single` highlights the closest element. <br> <br>`label` highlights elements in all datasets at the same `X` value. <br> <br>`'x-axis'` also highlights elements in all datasets at the same `X` value, but activates when hovering anywhere within the vertical slice of the x-axis representing that `X` value. <br> <br>`dataset` highlights the closest dataset.
+mode | String | 'naerest' | Sets which elements appear in the tooltip. See [Interaction Modes](#interaction-modes) for details
+intersect | Boolean | true | if true, the hover mode only applies when the mouse position intersects an item on the chart
animationDuration | Number | 400 | Duration in milliseconds it takes to animate hover style changes
onHover | Function | null | Called when any of the events fire. Called in the context of the chart and passed an array of active elements (bars, points, etc)
+### Interaction Modes
+When configuring interaction with the graph via hover or tooltips, a number of different modes are available.
+
+The following table details the modes and how they behave in conjunction with the `intersect` setting
+
+Mode | Behaviour
+--- | ---
+point | Finds all of the items that intersect the point
+nearest | Gets the item that is nearest to the point. The nearest item is determined based on the distance to the center of the chart item (point, bar). If 2 or more items are at the same distance, the one with the smallest area is used. If `intersect` is true, this is only triggered when the mouse position intersects an item in the graph. This is very useful for combo charts where points are hidden behind bars.
+single (deprecated) | Finds the first item that intersects the point and returns it. Behaves like 'nearest' mode with intersect = true.
+label (deprecated) | See `'index'` mode
+index | Finds item at the same index. If the `intersect` setting is true, the first intersecting item is used to determine the index in the data. If `intersect` false the nearest item is used to determine the index.
+x-axis (deprecated) | Behaves like `'index'` mode with `intersect = true`
+dataset | Finds items in the same dataset. If the `intersect` setting is true, the first intersecting item is used to determine the index in the data. If `intersect` false the nearest item is used to determine the index.
+x | Returns all items that would intersect based on the `X` coordinate of the position only. Would be useful for a vertical cursor implementation. Note that this only applies to cartesian charts
+y | Returns all items that would intersect based on the `Y` coordinate of the position. This would be useful for a horizontal cursor implementation. Note that this only applies to cartesian charts.
+
### Animation Configuration
The following animation options are available. The global options for are defined in `Chart.defaults.global.animation`. | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/AnimationCallbacks/progress-bar.html | @@ -75,7 +75,7 @@
}
},
tooltips: {
- mode: 'label',
+ mode: 'index',
},
scales: {
xAxes: [{ | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/bar-multi-axis.html | @@ -56,7 +56,7 @@
data: barChartData,
options: {
responsive: true,
- hoverMode: 'label',
+ hoverMode: 'index',
hoverAnimationDuration: 400,
stacked: false,
title:{ | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/bar-stacked.html | @@ -55,7 +55,7 @@
text:"Chart.js Bar Chart - Stacked"
},
tooltips: {
- mode: 'label'
+ mode: 'index'
},
responsive: true,
scales: { | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/different-point-sizes.html | @@ -70,7 +70,7 @@
position: 'bottom',
},
hover: {
- mode: 'label'
+ mode: 'index'
},
scales: {
xAxes: [{ | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/line-cubicInterpolationMode.html | @@ -68,7 +68,7 @@
text:'Chart.js Line Chart - Cubic interpolation mode'
},
tooltips: {
- mode: 'label'
+ mode: 'index'
},
hover: {
mode: 'dataset' | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/line-legend.html | @@ -68,7 +68,7 @@
position: 'bottom',
},
hover: {
- mode: 'label'
+ mode: 'index'
},
scales: {
xAxes: [{ | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/line-multi-axis.html | @@ -54,7 +54,7 @@
data: lineChartData,
options: {
responsive: true,
- hoverMode: 'label',
+ hoverMode: 'index',
stacked: false,
title:{
display:true, | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/line-multiline-labels.html | @@ -65,7 +65,7 @@
text:'Chart.js Line Chart'
},
tooltips: {
- mode: 'label',
+ mode: 'index',
callbacks: {
// beforeTitle: function() {
// return '...beforeTitle'; | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/line-skip-points.html | @@ -64,10 +64,10 @@
text:'Chart.js Line Chart - Skip Points'
},
tooltips: {
- mode: 'label',
+ mode: 'index',
},
hover: {
- mode: 'label'
+ mode: 'index'
},
scales: {
xAxes: [{ | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/line-stacked-area.html | @@ -63,10 +63,10 @@
text:"Chart.js Line Chart - Stacked Area"
},
tooltips: {
- mode: 'label',
+ mode: 'index',
},
hover: {
- mode: 'label'
+ mode: 'index'
},
scales: {
xAxes: [{ | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/line-stepped.html | @@ -68,7 +68,7 @@
text:'Chart.js Line Chart'
},
tooltips: {
- mode: 'label',
+ mode: 'index',
callbacks: {
// beforeTitle: function() {
// return '...beforeTitle'; | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/line.html | @@ -65,7 +65,8 @@
text:'Chart.js Line Chart'
},
tooltips: {
- mode: 'label',
+ mode: 'index',
+ intersect: false,
callbacks: {
// beforeTitle: function() {
// return '...beforeTitle';
@@ -91,7 +92,8 @@
}
},
hover: {
- mode: 'dataset'
+ mode: 'nearest',
+ intersect: true
},
scales: {
xAxes: [{ | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/scatter-multi-axis.html | @@ -99,7 +99,8 @@
data: scatterChartData,
options: {
responsive: true,
- hoverMode: 'single',
+ hoverMode: 'nearest',
+ intersect: true,
title: {
display: true,
text: 'Chart.js Scatter Chart - Multi Axis' | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | samples/tooltip-hooks.html | @@ -59,7 +59,7 @@
text:"Chart.js Line Chart - Tooltip Hooks"
},
tooltips: {
- mode: 'label',
+ mode: 'index',
callbacks: {
beforeTitle: function() {
return '...beforeTitle';
@@ -91,7 +91,7 @@
}
},
hover: {
- mode: 'label'
+ mode: 'index'
},
scales: {
xAxes: [{ | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | src/chart.js | @@ -16,6 +16,7 @@ require('./core/core.ticks.js')(Chart);
require('./core/core.scale')(Chart);
require('./core/core.title')(Chart);
require('./core/core.legend')(Chart);
+require('./core/core.interaction')(Chart);
require('./core/core.tooltip')(Chart);
require('./elements/element.arc')(Chart); | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | src/controllers/controller.bar.js | @@ -422,21 +422,6 @@ module.exports = function(Chart) {
if (vm.borderWidth) {
ctx.stroke();
}
- },
-
- inRange: function(mouseX, mouseY) {
- var vm = this._view;
- var inRange = false;
-
- if (vm) {
- if (vm.x < vm.base) {
- inRange = (mouseY >= vm.y - vm.height / 2 && mouseY <= vm.y + vm.height / 2) && (mouseX >= vm.x && mouseX <= vm.base);
- } else {
- inRange = (mouseY >= vm.y - vm.height / 2 && mouseY <= vm.y + vm.height / 2) && (mouseX >= vm.base && mouseX <= vm.x);
- }
- }
-
- return inRange;
}
});
| true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | src/core/core.controller.js | @@ -515,125 +515,28 @@ module.exports = function(Chart) {
// 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) {
- var me = this;
- var eventPosition = helpers.getRelativePosition(e, me.chart);
- var elementsArray = [];
-
- helpers.each(me.data.datasets, function(dataset, datasetIndex) {
- if (me.isDatasetVisible(datasetIndex)) {
- var meta = me.getDatasetMeta(datasetIndex);
- helpers.each(meta.data, function(element) {
- if (element.inRange(eventPosition.x, eventPosition.y)) {
- elementsArray.push(element);
- return elementsArray;
- }
- });
- }
- });
-
- return elementsArray.slice(0, 1);
+ return Chart.Interaction.modes.single(this, e);
},
getElementsAtEvent: function(e) {
- var me = this;
- var eventPosition = helpers.getRelativePosition(e, me.chart);
- var elementsArray = [];
-
- var found = function() {
- if (me.data.datasets) {
- for (var i = 0; i < me.data.datasets.length; i++) {
- var meta = me.getDatasetMeta(i);
- if (me.isDatasetVisible(i)) {
- for (var j = 0; j < meta.data.length; j++) {
- if (meta.data[j].inRange(eventPosition.x, eventPosition.y)) {
- return meta.data[j];
- }
- }
- }
- }
- }
- }.call(me);
-
- if (!found) {
- return elementsArray;
- }
-
- helpers.each(me.data.datasets, function(dataset, datasetIndex) {
- if (me.isDatasetVisible(datasetIndex)) {
- var meta = me.getDatasetMeta(datasetIndex),
- element = meta.data[found._index];
- if (element && !element._view.skip) {
- elementsArray.push(element);
- }
- }
- }, me);
-
- return elementsArray;
+ return Chart.Interaction.modes.label(this, e, {intersect: true});
},
getElementsAtXAxis: function(e) {
- var me = this;
- var eventPosition = helpers.getRelativePosition(e, me.chart);
- var elementsArray = [];
-
- var found = function() {
- if (me.data.datasets) {
- for (var i = 0; i < me.data.datasets.length; i++) {
- var meta = me.getDatasetMeta(i);
- if (me.isDatasetVisible(i)) {
- for (var j = 0; j < meta.data.length; j++) {
- if (meta.data[j].inLabelRange(eventPosition.x, eventPosition.y)) {
- return meta.data[j];
- }
- }
- }
- }
- }
- }.call(me);
-
- if (!found) {
- return elementsArray;
- }
-
- helpers.each(me.data.datasets, function(dataset, datasetIndex) {
- if (me.isDatasetVisible(datasetIndex)) {
- var meta = me.getDatasetMeta(datasetIndex);
- var index = helpers.findIndex(meta.data, function(it) {
- return found._model.x === it._model.x;
- });
- if (index !== -1 && !meta.data[index]._view.skip) {
- elementsArray.push(meta.data[index]);
- }
- }
- }, me);
-
- return elementsArray;
+ return Chart.Interaction.modes['x-axis'](this, e, {intersect: true});
},
- getElementsAtEventForMode: function(e, mode) {
- var me = this;
- switch (mode) {
- case 'single':
- return me.getElementAtEvent(e);
- case 'label':
- return me.getElementsAtEvent(e);
- case 'dataset':
- return me.getDatasetAtEvent(e);
- case 'x-axis':
- return me.getElementsAtXAxis(e);
- default:
- return e;
+ getElementsAtEventForMode: function(e, mode, options) {
+ var method = Chart.Interaction.modes[mode];
+ if (typeof method === 'function') {
+ return method(this, e, options);
}
+
+ return [];
},
getDatasetAtEvent: function(e) {
- var elementsArray = this.getElementAtEvent(e);
-
- if (elementsArray.length > 0) {
- elementsArray = this.getDatasetMeta(elementsArray[0]._datasetIndex).data;
- }
-
- return elementsArray;
+ return Chart.Interaction.modes.dataset(this, e);
},
getDatasetMeta: function(datasetIndex) {
@@ -777,8 +680,8 @@ module.exports = function(Chart) {
me.active = [];
me.tooltipActive = [];
} else {
- me.active = me.getElementsAtEventForMode(e, hoverOptions.mode);
- me.tooltipActive = me.getElementsAtEventForMode(e, tooltipsOptions.mode);
+ me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
+ me.tooltipActive = me.getElementsAtEventForMode(e, tooltipsOptions.mode, tooltipsOptions);
}
// On Hover hook | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | src/core/core.helpers.js | @@ -308,6 +308,9 @@ module.exports = function(Chart) {
distance: radialDistanceFromCenter
};
};
+ helpers.distanceBetweenPoints = function(pt1, pt2) {
+ return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
+ };
helpers.aliasPixel = function(pixelWidth) {
return (pixelWidth % 2 === 0) ? 0 : 0.5;
}; | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | src/core/core.interaction.js | @@ -0,0 +1,263 @@
+'use strict';
+
+module.exports = function(Chart) {
+ var helpers = Chart.helpers;
+
+ /**
+ * 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
+ */
+ function parseVisibleItems(chart, handler) {
+ var datasets = chart.data.datasets;
+ var meta, i, j, ilen, jlen;
+
+ for (i = 0, ilen = datasets.length; i < ilen; ++i) {
+ if (!chart.isDatasetVisible(i)) {
+ continue;
+ }
+
+ meta = chart.getDatasetMeta(i);
+ for (j = 0, jlen = meta.data.length; j < jlen; ++j) {
+ var element = meta.data[j];
+ if (!element._view.skip) {
+ handler(element);
+ }
+ }
+ }
+ }
+
+ /**
+ * 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
+ * @return {ChartElement[]} the nearest items
+ */
+ function getIntersectItems(chart, position) {
+ var elements = [];
+
+ parseVisibleItems(chart, function(element) {
+ if (element.inRange(position.x, position.y)) {
+ elements.push(element);
+ }
+ });
+
+ return elements;
+ }
+
+ /**
+ * 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
+ * @return {ChartElement[]} the nearest items
+ */
+ function getNearestItems(chart, position, intersect) {
+ var minDistance = Number.POSITIVE_INFINITY;
+ var nearestItems = [];
+
+ parseVisibleItems(chart, function(element) {
+ if (intersect && !element.inRange(position.x, position.y)) {
+ return;
+ }
+
+ var center = element.getCenterPoint();
+ var distance = Math.round(helpers.distanceBetweenPoints(position, center));
+
+ if (distance < minDistance) {
+ nearestItems = [element];
+ minDistance = distance;
+ } else if (distance === minDistance) {
+ // Can have multiple items at the same distance in which case we sort by size
+ nearestItems.push(element);
+ }
+ });
+
+ return nearestItems;
+ }
+
+ function indexMode(chart, e, options) {
+ var position = helpers.getRelativePosition(e, chart.chart);
+ var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false);
+ var elements = [];
+
+ if (!items.length) {
+ return [];
+ }
+
+ chart.data.datasets.forEach(function(dataset, datasetIndex) {
+ if (chart.isDatasetVisible(datasetIndex)) {
+ var meta = chart.getDatasetMeta(datasetIndex),
+ element = meta.data[items[0]._index];
+
+ // don't count items that are skipped (null data)
+ if (element && !element._view.skip) {
+ elements.push(element);
+ }
+ }
+ });
+
+ return elements;
+ }
+
+ /**
+ * @interface IInteractionOptions
+ */
+ /**
+ * If true, only consider items that intersect the point
+ * @name IInterfaceOptions#boolean
+ * @type Boolean
+ */
+
+ /**
+ * @namespace Chart.Interaction
+ * Contains interaction related functions
+ */
+ Chart.Interaction = {
+ // Helper function for different modes
+ modes: {
+ single: function(chart, e) {
+ var position = helpers.getRelativePosition(e, chart.chart);
+ var elements = [];
+
+ parseVisibleItems(chart, function(element) {
+ if (element.inRange(position.x, position.y)) {
+ elements.push(element);
+ return elements;
+ }
+ });
+
+ return elements.slice(0, 1);
+ },
+
+ /**
+ * @function Chart.Interaction.modes.label
+ * @deprecated since version 2.4.0
+ */
+ label: indexMode,
+
+ /**
+ * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
+ * 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
+ * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
+ */
+ index: indexMode,
+
+ /**
+ * 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
+ * @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) {
+ var position = helpers.getRelativePosition(e, chart.chart);
+ var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false);
+
+ if (items.length > 0) {
+ items = chart.getDatasetMeta(items[0]._datasetIndex).data;
+ }
+
+ return items;
+ },
+
+ /**
+ * @function Chart.Interaction.modes.x-axis
+ * @deprecated since version 2.4.0. Use index mode and intersect == true
+ */
+ 'x-axis': function(chart, e) {
+ return indexMode(chart, e, true);
+ },
+
+ /**
+ * 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
+ * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
+ */
+ point: function(chart, e) {
+ var position = helpers.getRelativePosition(e, chart.chart);
+ return getIntersectItems(chart, position);
+ },
+
+ /**
+ * 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
+ * @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) {
+ var position = helpers.getRelativePosition(e, chart.chart);
+ var nearestItems = getNearestItems(chart, position, options.intersect);
+
+ // We have multiple items at the same distance from the event. Now sort by smallest
+ if (nearestItems.length > 1) {
+ nearestItems.sort(function(a, b) {
+ var sizeA = a.getArea();
+ var sizeB = b.getArea();
+ var ret = sizeA - sizeB;
+
+ if (ret === 0) {
+ // if equal sort by dataset index
+ ret = a._datasetIndex - b._datasetIndex;
+ }
+
+ return ret;
+ });
+ }
+
+ // Return only 1 item
+ return nearestItems.slice(0, 1);
+ },
+
+ /**
+ * 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
+ * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
+ */
+ x: function(chart, e) {
+ var position = helpers.getRelativePosition(e, chart.chart);
+ var items = [];
+ parseVisibleItems(chart, function(element) {
+ if (element.inXRange(position.x)) {
+ items.push(element);
+ }
+ });
+ return items;
+ },
+
+ /**
+ * 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
+ * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
+ */
+ y: function(chart, e) {
+ var position = helpers.getRelativePosition(e, chart.chart);
+ var items = [];
+ parseVisibleItems(chart, function(element) {
+ if (element.inYRange(position.x)) {
+ items.push(element);
+ }
+ });
+ return items;
+ }
+ }
+ };
+}; | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | src/core/core.js | @@ -30,7 +30,8 @@ module.exports = function() {
events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
hover: {
onHover: null,
- mode: 'single',
+ mode: 'nearest',
+ intersect: true,
animationDuration: 400
},
onClick: null, | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | src/core/core.tooltip.js | @@ -7,7 +7,8 @@ module.exports = function(Chart) {
Chart.defaults.global.tooltips = {
enabled: true,
custom: null,
- mode: 'single',
+ mode: 'nearest',
+ intersect: true,
backgroundColor: 'rgba(0,0,0,0.8)',
titleFontStyle: 'bold',
titleSpacing: 2, | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | src/elements/element.arc.js | @@ -52,6 +52,19 @@ module.exports = function(Chart) {
}
return false;
},
+ getCenterPoint: function() {
+ var vm = this._view;
+ var halfAngle = (vm.startAngle + vm.endAngle) / 2;
+ var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
+ return {
+ x: vm.x + Math.cos(halfAngle) * halfRadius,
+ y: vm.y + Math.sin(halfAngle) * halfRadius
+ };
+ },
+ getArea: function() {
+ var vm = this._view;
+ return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
+ },
tooltipPosition: function() {
var vm = this._view;
| true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | src/elements/element.point.js | @@ -18,14 +18,35 @@ module.exports = function(Chart) {
hoverBorderWidth: 1
};
+ function xRange(mouseX) {
+ var vm = this._view;
+ return vm ? (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hitRadius, 2)) : false;
+ }
+
+ function yRange(mouseY) {
+ var vm = this._view;
+ return vm ? (Math.pow(mouseY - vm.y, 2) < Math.pow(vm.radius + vm.hitRadius, 2)) : false;
+ }
+
Chart.elements.Point = Chart.Element.extend({
inRange: function(mouseX, mouseY) {
var vm = this._view;
return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
},
- inLabelRange: function(mouseX) {
+
+ inLabelRange: xRange,
+ inXRange: xRange,
+ inYRange: yRange,
+
+ getCenterPoint: function() {
var vm = this._view;
- return vm ? (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hitRadius, 2)) : false;
+ return {
+ x: vm.x,
+ y: vm.y
+ };
+ },
+ getArea: function() {
+ return Math.PI * Math.pow(this._view.radius, 2);
},
tooltipPosition: function() {
var vm = this._view; | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | src/elements/element.rectangle.js | @@ -11,6 +11,44 @@ module.exports = function(Chart) {
borderSkipped: 'bottom'
};
+ function isVertical(bar) {
+ return bar._view.width !== undefined;
+ }
+
+ /**
+ * Helper function to get the bounds of the bar regardless of the orientation
+ * @private
+ * @param bar {Chart.Element.Rectangle} the bar
+ * @return {Bounds} bounds of the bar
+ */
+ function getBarBounds(bar) {
+ var vm = bar._view;
+ var x1, x2, y1, y2;
+
+ if (isVertical(bar)) {
+ // vertical
+ var halfWidth = vm.width / 2;
+ x1 = vm.x - halfWidth;
+ x2 = vm.x + halfWidth;
+ y1 = Math.min(vm.y, vm.base);
+ y2 = Math.max(vm.y, vm.base);
+ } else {
+ // horizontal bar
+ var halfHeight = vm.height / 2;
+ x1 = Math.min(vm.x, vm.base);
+ x2 = Math.max(vm.x, vm.base);
+ y1 = vm.y - halfHeight;
+ y2 = vm.y + halfHeight;
+ }
+
+ return {
+ left: x1,
+ top: y1,
+ right: x2,
+ bottom: y2
+ };
+ }
+
Chart.elements.Rectangle = Chart.Element.extend({
draw: function() {
var ctx = this._chart.ctx;
@@ -72,16 +110,56 @@ module.exports = function(Chart) {
return vm.base - vm.y;
},
inRange: function(mouseX, mouseY) {
+ var inRange = false;
+
+ if (this._view) {
+ var bounds = getBarBounds(this);
+ inRange = mouseX >= bounds.left && mouseX <= bounds.right && mouseY >= bounds.top && mouseY <= bounds.bottom;
+ }
+
+ return inRange;
+ },
+ inLabelRange: function(mouseX, mouseY) {
+ var me = this;
+ if (!me._view) {
+ return false;
+ }
+
+ var inRange = false;
+ var bounds = getBarBounds(me);
+
+ if (isVertical(me)) {
+ inRange = mouseX >= bounds.left && mouseX <= bounds.right;
+ } else {
+ inRange = mouseY >= bounds.top && mouseY <= bounds.bottom;
+ }
+
+ return inRange;
+ },
+ inXRange: function(mouseX) {
+ var bounds = getBarBounds(this);
+ return mouseX >= bounds.left && mouseX <= bounds.right;
+ },
+ inYRange: function(mouseY) {
+ var bounds = getBarBounds(this);
+ return mouseY >= bounds.top && mouseY <= bounds.bottom;
+ },
+ getCenterPoint: function() {
var vm = this._view;
- return vm ?
- (vm.y < vm.base ?
- (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.y && mouseY <= vm.base) :
- (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.base && mouseY <= vm.y)) :
- false;
+ var x, y;
+ if (isVertical(this)) {
+ x = vm.x;
+ y = (vm.y + vm.base) / 2;
+ } else {
+ x = (vm.x + vm.base) / 2;
+ y = vm.y;
+ }
+
+ return {x: x, y: y};
},
- inLabelRange: function(mouseX) {
+ getArea: function() {
var vm = this._view;
- return vm ? (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) : false;
+ return vm.width * Math.abs(vm.y - vm.base);
},
tooltipPosition: function() {
var vm = this._view; | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | test/core.interaction.tests.js | @@ -0,0 +1,562 @@
+// Tests of the interaction handlers in Core.Interaction
+
+// Test the rectangle element
+describe('Core.Interaction', function() {
+ describe('point mode', function() {
+ it ('should return all items under the point', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 20, 30],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 20, 40],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ // Trigger an event over top of the
+ var meta0 = chartInstance.getDatasetMeta(0);
+ var meta1 = chartInstance.getDatasetMeta(1);
+ var point = meta0.data[1];
+
+ var node = chartInstance.chart.canvas;
+ var rect = node.getBoundingClientRect();
+
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + point._model.x,
+ clientY: rect.top + point._model.y,
+ currentTarget: node
+ };
+
+ var elements = Chart.Interaction.modes.point(chartInstance, evt);
+ expect(elements).toEqual([point, meta1.data[1]]);
+ });
+
+ it ('should return an empty array when no items are found', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 20, 30],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 20, 40],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ // Trigger an event at (0, 0)
+ var node = chartInstance.chart.canvas;
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: 0,
+ clientY: 0,
+ currentTarget: node
+ };
+
+ var elements = Chart.Interaction.modes.point(chartInstance, evt);
+ expect(elements).toEqual([]);
+ });
+ });
+
+ describe('index mode', function() {
+ it ('should return all items at the same index', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 20, 30],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ // Trigger an event over top of the
+ var meta0 = chartInstance.getDatasetMeta(0);
+ var meta1 = chartInstance.getDatasetMeta(1);
+ var point = meta0.data[1];
+
+ var node = chartInstance.chart.canvas;
+ var rect = node.getBoundingClientRect();
+
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + point._model.x,
+ clientY: rect.top + point._model.y,
+ currentTarget: node
+ };
+
+ var elements = Chart.Interaction.modes.index(chartInstance, evt, { intersect: true });
+ expect(elements).toEqual([point, meta1.data[1]]);
+ });
+
+ it ('should return all items at the same index when intersect is false', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 20, 30],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ // Trigger an event over top of the
+ var meta0 = chartInstance.getDatasetMeta(0);
+ var meta1 = chartInstance.getDatasetMeta(1);
+
+ var node = chartInstance.chart.canvas;
+ var rect = node.getBoundingClientRect();
+
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left,
+ clientY: rect.top,
+ currentTarget: node
+ };
+
+ var elements = Chart.Interaction.modes.index(chartInstance, evt, { intersect: false });
+ expect(elements).toEqual([meta0.data[0], meta1.data[0]]);
+ });
+ });
+
+ describe('dataset mode', function() {
+ it ('should return all items in the dataset of the first item found', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 20, 30],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ // Trigger an event over top of the
+ var meta = chartInstance.getDatasetMeta(0);
+ var point = meta.data[1];
+
+ var node = chartInstance.chart.canvas;
+ var rect = node.getBoundingClientRect();
+
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + point._model.x,
+ clientY: rect.top + point._model.y,
+ currentTarget: node
+ };
+
+ var elements = Chart.Interaction.modes.dataset(chartInstance, evt, { intersect: true });
+ expect(elements).toEqual(meta.data);
+ });
+
+ it ('should return all items in the dataset of the first item found when intersect is false', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 20, 30],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ var node = chartInstance.chart.canvas;
+ var rect = node.getBoundingClientRect();
+
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left,
+ clientY: rect.top,
+ currentTarget: node
+ };
+
+ var elements = Chart.Interaction.modes.dataset(chartInstance, evt, { intersect: false });
+
+ var meta = chartInstance.getDatasetMeta(1);
+ expect(elements).toEqual(meta.data);
+ });
+ });
+
+ describe('nearest mode', function() {
+ it ('should return the nearest item', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 20, 30],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ // Trigger an event over top of the
+ var meta = chartInstance.getDatasetMeta(1);
+ var node = chartInstance.chart.canvas;
+ var rect = node.getBoundingClientRect();
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: 0,
+ clientY: 0,
+ currentTarget: node
+ };
+
+ // Nearest to 0,0 (top left) will be first point of dataset 2
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: false });
+ expect(elements).toEqual([meta.data[0]]);
+ });
+
+ it ('should return the smallest item if more than 1 are at the same distance', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 40, 30],
+ pointRadius: [5, 5, 5],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointRadius: [10, 10, 10],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ // Trigger an event over top of the
+ var meta0 = chartInstance.getDatasetMeta(0);
+ var meta1 = chartInstance.getDatasetMeta(1);
+
+ // Halfway between 2 mid points
+ var pt = {
+ x: meta0.data[1]._view.x,
+ y: (meta0.data[1]._view.y + meta1.data[1]._view.y) / 2
+ };
+
+ var node = chartInstance.chart.canvas;
+ var rect = node.getBoundingClientRect();
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + pt.x,
+ clientY: rect.top + pt.y,
+ currentTarget: node
+ };
+
+ // Nearest to 0,0 (top left) will be first point of dataset 2
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: false });
+ expect(elements).toEqual([meta0.data[1]]);
+ });
+
+ it ('should return the lowest dataset index if size and area are the same', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 40, 30],
+ pointRadius: [5, 10, 5],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointRadius: [10, 10, 10],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ // Trigger an event over top of the
+ var meta0 = chartInstance.getDatasetMeta(0);
+ var meta1 = chartInstance.getDatasetMeta(1);
+
+ // Halfway between 2 mid points
+ var pt = {
+ x: meta0.data[1]._view.x,
+ y: (meta0.data[1]._view.y + meta1.data[1]._view.y) / 2
+ };
+
+ var node = chartInstance.chart.canvas;
+ var rect = node.getBoundingClientRect();
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + pt.x,
+ clientY: rect.top + pt.y,
+ currentTarget: node
+ };
+
+ // Nearest to 0,0 (top left) will be first point of dataset 2
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: false });
+ expect(elements).toEqual([meta0.data[1]]);
+ });
+ });
+
+ describe('nearest intersect mode', function() {
+ it ('should return the nearest item', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 20, 30],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ // Trigger an event over top of the
+ var meta = chartInstance.getDatasetMeta(1);
+ var point = meta.data[1];
+
+ var node = chartInstance.chart.canvas;
+ var rect = node.getBoundingClientRect();
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + point._view.x + 15,
+ clientY: rect.top + point._view.y,
+ currentTarget: node
+ };
+
+ // Nothing intersects so find nothing
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: true });
+ expect(elements).toEqual([]);
+
+ evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + point._view.x,
+ clientY: rect.top + point._view.y,
+ currentTarget: node
+ };
+ elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: true });
+ expect(elements).toEqual([point]);
+ });
+
+ it ('should return the nearest item even if 2 intersect', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 39, 30],
+ pointRadius: [5, 30, 5],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointRadius: [10, 10, 10],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ // Trigger an event over top of the
+ var meta0 = chartInstance.getDatasetMeta(0);
+
+ // Halfway between 2 mid points
+ var pt = {
+ x: meta0.data[1]._view.x,
+ y: meta0.data[1]._view.y
+ };
+
+ var node = chartInstance.chart.canvas;
+ var rect = node.getBoundingClientRect();
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + pt.x,
+ clientY: rect.top + pt.y,
+ currentTarget: node
+ };
+
+ // Nearest to 0,0 (top left) will be first point of dataset 2
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: true });
+ expect(elements).toEqual([meta0.data[1]]);
+ });
+
+ it ('should return the smallest item if more than 1 are at the same distance', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 40, 30],
+ pointRadius: [5, 5, 5],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointRadius: [10, 10, 10],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ // Trigger an event over top of the
+ var meta0 = chartInstance.getDatasetMeta(0);
+
+ // Halfway between 2 mid points
+ var pt = {
+ x: meta0.data[1]._view.x,
+ y: meta0.data[1]._view.y
+ };
+
+ var node = chartInstance.chart.canvas;
+ var rect = node.getBoundingClientRect();
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + pt.x,
+ clientY: rect.top + pt.y,
+ currentTarget: node
+ };
+
+ // Nearest to 0,0 (top left) will be first point of dataset 2
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: true });
+ expect(elements).toEqual([meta0.data[1]]);
+ });
+
+ it ('should return the item at the lowest dataset index if distance and area are the same', function() {
+ var chartInstance = window.acquireChart({
+ type: 'line',
+ data: {
+ datasets: [{
+ label: 'Dataset 1',
+ data: [10, 40, 30],
+ pointRadius: [5, 10, 5],
+ pointHoverBorderColor: 'rgb(255, 0, 0)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 0)'
+ }, {
+ label: 'Dataset 2',
+ data: [40, 40, 40],
+ pointRadius: [10, 10, 10],
+ pointHoverBorderColor: 'rgb(0, 0, 255)',
+ pointHoverBackgroundColor: 'rgb(0, 255, 255)'
+ }],
+ labels: ['Point 1', 'Point 2', 'Point 3']
+ }
+ });
+
+ // Trigger an event over top of the
+ var meta0 = chartInstance.getDatasetMeta(0);
+
+ // Halfway between 2 mid points
+ var pt = {
+ x: meta0.data[1]._view.x,
+ y: meta0.data[1]._view.y
+ };
+
+ var node = chartInstance.chart.canvas;
+ var rect = node.getBoundingClientRect();
+ var evt = {
+ view: window,
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + pt.x,
+ clientY: rect.top + pt.y,
+ currentTarget: node
+ };
+
+ // Nearest to 0,0 (top left) will be first point of dataset 2
+ var elements = Chart.Interaction.modes.nearest(chartInstance, evt, { intersect: true });
+ expect(elements).toEqual([meta0.data[1]]);
+ });
+ });
+}); | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | test/element.arc.tests.js | @@ -60,6 +60,46 @@ describe('Arc element tests', function() {
expect(pos.y).toBeCloseTo(0.5);
});
+ it ('should get the area', function() {
+ var arc = new Chart.elements.Arc({
+ _datasetIndex: 2,
+ _index: 1
+ });
+
+ // Mock out the view as if the controller put it there
+ arc._view = {
+ startAngle: 0,
+ endAngle: Math.PI / 2,
+ x: 0,
+ y: 0,
+ innerRadius: 0,
+ outerRadius: Math.sqrt(2),
+ };
+
+ expect(arc.getArea()).toBeCloseTo(0.5 * Math.PI, 6);
+ });
+
+ it ('should get the center', function() {
+ var arc = new Chart.elements.Arc({
+ _datasetIndex: 2,
+ _index: 1
+ });
+
+ // Mock out the view as if the controller put it there
+ arc._view = {
+ startAngle: 0,
+ endAngle: Math.PI / 2,
+ x: 0,
+ y: 0,
+ innerRadius: 0,
+ outerRadius: Math.sqrt(2),
+ };
+
+ var center = arc.getCenterPoint();
+ expect(center.x).toBeCloseTo(0.5, 6);
+ expect(center.y).toBeCloseTo(0.5, 6);
+ });
+
it ('should draw correctly with no border', function() {
var mockContext = window.createMockContext();
var arc = new Chart.elements.Arc({ | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | test/element.point.tests.js | @@ -64,6 +64,36 @@ describe('Point element tests', function() {
});
});
+ it('should get the correct area', function() {
+ var point = new Chart.elements.Point({
+ _datasetIndex: 2,
+ _index: 1
+ });
+
+ // Attach a view object as if we were the controller
+ point._view = {
+ radius: 2,
+ };
+
+ expect(point.getArea()).toEqual(Math.PI * 4);
+ });
+
+ it('should get the correct center point', function() {
+ var point = new Chart.elements.Point({
+ _datasetIndex: 2,
+ _index: 1
+ });
+
+ // Attach a view object as if we were the controller
+ point._view = {
+ radius: 2,
+ x: 10,
+ y: 10
+ };
+
+ expect(point.getCenterPoint()).toEqual({ x: 10, y: 10 });
+ });
+
it ('should draw correctly', function() {
var mockContext = window.createMockContext();
var point = new Chart.elements.Point({ | true |
Other | chartjs | Chart.js | 03735563f44e1ae108f83b9c7ee946f8818c92c3.json | Improve Tooltip and Hover Interaction (#3400)
Refactored interaction modes to use lookup functions in Chart.Interaction.modes and added new modes for 'point', 'index', 'nearest', 'x', and 'y' | test/element.rectangle.tests.js | @@ -132,6 +132,40 @@ describe('Rectangle element tests', function() {
});
});
+ it ('should get the correct area', function() {
+ var rectangle = new Chart.elements.Rectangle({
+ _datasetIndex: 2,
+ _index: 1
+ });
+
+ // Attach a view object as if we were the controller
+ rectangle._view = {
+ base: 0,
+ width: 4,
+ x: 10,
+ y: 15
+ };
+
+ expect(rectangle.getArea()).toEqual(60);
+ });
+
+ it ('should get the center', function() {
+ var rectangle = new Chart.elements.Rectangle({
+ _datasetIndex: 2,
+ _index: 1
+ });
+
+ // Attach a view object as if we were the controller
+ rectangle._view = {
+ base: 0,
+ width: 4,
+ x: 10,
+ y: 15
+ };
+
+ expect(rectangle.getCenterPoint()).toEqual({ x: 10, y: 7.5 });
+ });
+
it ('should draw correctly', function() {
var mockContext = window.createMockContext();
var rectangle = new Chart.elements.Rectangle({ | true |
Other | chartjs | Chart.js | 9deebf837188164078b092a19bf3b7add660406f.json | Fix config initialization and add unit tests | src/core/core.controller.js | @@ -117,16 +117,19 @@ module.exports = function(Chart) {
*/
function initConfig(config) {
config = config || {};
- return helpers.configMerge({
- options: helpers.configMerge(
- Chart.defaults.global,
- Chart.defaults[config.type],
- config.options || {}),
- data: {
- datasets: [],
- labels: []
- }
- }, config);
+
+ // Do NOT use configMerge() for the data object because this method merges arrays
+ // and so would change references to labels and datasets, preventing data updates.
+ var data = config.data = config.data || {};
+ data.datasets = data.datasets || [];
+ data.labels = data.labels || [];
+
+ config.options = helpers.configMerge(
+ Chart.defaults.global,
+ Chart.defaults[config.type],
+ config.options || {});
+
+ return config;
}
/** | true |
Other | chartjs | Chart.js | 9deebf837188164078b092a19bf3b7add660406f.json | Fix config initialization and add unit tests | test/core.controller.tests.js | @@ -4,6 +4,89 @@ describe('Chart.Controller', function() {
setTimeout(callback, 100);
}
+ describe('config', function() {
+ it('should create missing config.data properties', function() {
+ var chart = acquireChart({});
+ var data = chart.data;
+
+ expect(data instanceof Object).toBeTruthy();
+ expect(data.labels instanceof Array).toBeTruthy();
+ expect(data.labels.length).toBe(0);
+ expect(data.datasets instanceof Array).toBeTruthy();
+ expect(data.datasets.length).toBe(0);
+ });
+
+ it('should NOT alter config.data references', function() {
+ var ds0 = {data: [10, 11, 12, 13]};
+ var ds1 = {data: [20, 21, 22, 23]};
+ var datasets = [ds0, ds1];
+ var labels = [0, 1, 2, 3];
+ var data = {labels: labels, datasets: datasets};
+
+ var chart = acquireChart({
+ type: 'line',
+ data: data
+ });
+
+ expect(chart.data).toBe(data);
+ expect(chart.data.labels).toBe(labels);
+ expect(chart.data.datasets).toBe(datasets);
+ expect(chart.data.datasets[0]).toBe(ds0);
+ expect(chart.data.datasets[1]).toBe(ds1);
+ expect(chart.data.datasets[0].data).toBe(ds0.data);
+ expect(chart.data.datasets[1].data).toBe(ds1.data);
+ });
+
+ it('should initialize config with default options', function() {
+ var callback = function() {};
+
+ var defaults = Chart.defaults;
+ defaults.global.responsiveAnimationDuration = 42;
+ defaults.global.hover.onHover = callback;
+ defaults.line.hover.mode = 'x-axis';
+ defaults.line.spanGaps = true;
+
+ var chart = acquireChart({
+ type: 'line'
+ });
+
+ var options = chart.options;
+ expect(options.defaultFontSize).toBe(defaults.global.defaultFontSize);
+ expect(options.showLines).toBe(defaults.line.showLines);
+ expect(options.spanGaps).toBe(true);
+ expect(options.responsiveAnimationDuration).toBe(42);
+ expect(options.hover.onHover).toBe(callback);
+ expect(options.hover.mode).toBe('x-axis');
+ });
+
+ it('should override default options', function() {
+ var defaults = Chart.defaults;
+ defaults.global.responsiveAnimationDuration = 42;
+ defaults.line.hover.mode = 'x-axis';
+ defaults.line.spanGaps = true;
+
+ var chart = acquireChart({
+ type: 'line',
+ options: {
+ responsiveAnimationDuration: 4242,
+ spanGaps: false,
+ hover: {
+ mode: 'dataset',
+ },
+ title: {
+ position: 'bottom'
+ }
+ }
+ });
+
+ var options = chart.options;
+ expect(options.responsiveAnimationDuration).toBe(4242);
+ expect(options.spanGaps).toBe(false);
+ expect(options.hover.mode).toBe('dataset');
+ expect(options.title.position).toBe('bottom');
+ });
+ });
+
describe('config.options.aspectRatio', function() {
it('should use default "global" aspect ratio for render and display sizes', function() {
var chart = acquireChart({ | true |
Other | chartjs | Chart.js | 4f668c3ed94c57bc5176bd8c89c2bb743139087c.json | Adjust expected values in core.title.tests.js | test/core.title.tests.js | @@ -118,7 +118,7 @@ describe('Title block tests', function() {
args: [0]
}, {
name: 'fillText',
- args: ['My title', 0, 0]
+ args: ['My title', 0, 0, 400]
}, {
name: 'restore',
args: []
@@ -168,7 +168,7 @@ describe('Title block tests', function() {
args: [-0.5 * Math.PI]
}, {
name: 'fillText',
- args: ['My title', 0, 0]
+ args: ['My title', 0, 0, 400]
}, {
name: 'restore',
args: []
@@ -201,10 +201,10 @@ describe('Title block tests', function() {
args: [0.5 * Math.PI]
}, {
name: 'fillText',
- args: ['My title', 0, 0]
+ args: ['My title', 0, 0, 400]
}, {
name: 'restore',
args: []
}]);
});
-});
\ No newline at end of file
+}); | false |
Other | chartjs | Chart.js | fb302d5f0074b5d367386319e696d5718b78a88d.json | Set maxWidth during title draw to avoid overflow
CanvasRenderingContext2D.fillText() accepts a fourth parameter called maxWidth that sets the maximum width of the drawn text, enforced by scaling the entire line.
This commit uses the title element's layout dimensions to set maxWidth and avoid overflow outside of the canvas. | src/core/core.title.js | @@ -158,7 +158,8 @@ module.exports = function(Chart) {
top = me.top,
left = me.left,
bottom = me.bottom,
- right = me.right;
+ right = me.right,
+ maxWidth;
ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour
ctx.font = titleFont;
@@ -167,9 +168,11 @@ module.exports = function(Chart) {
if (me.isHorizontal()) {
titleX = left + ((right - left) / 2); // midpoint of the width
titleY = top + ((bottom - top) / 2); // midpoint of the height
+ maxWidth = right - left;
} else {
titleX = opts.position === 'left' ? left + (fontSize / 2) : right - (fontSize / 2);
titleY = top + ((bottom - top) / 2);
+ maxWidth = bottom - top;
rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
}
@@ -178,7 +181,7 @@ module.exports = function(Chart) {
ctx.rotate(rotation);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
- ctx.fillText(opts.text, 0, 0);
+ ctx.fillText(opts.text, 0, 0, maxWidth);
ctx.restore();
}
} | false |
Other | chartjs | Chart.js | 16bcd6adc579cb3deae16ea915680bc219924cdc.json | Fix initial aspect ratio when not responsive
When responsive is false and no canvas height explicitly set, the aspectRatio option wasn't applied because of the canvas default height. Prevent the retinaScale method to change the canvas display size since this method is called for none responsive charts, but instead make the resize() responsible of these changes. Also, as discussed some time ago, moved most of the core.js logic into core.controller.js. Clean up the destroy process and make sure that initial canvas values are properly saved and restored. | src/core/core.controller.js | @@ -3,6 +3,7 @@
module.exports = function(Chart) {
var helpers = Chart.helpers;
+
// Create a dictionary of chart types, to allow for extension of existing types
Chart.types = {};
@@ -13,40 +14,176 @@ module.exports = function(Chart) {
// Controllers available for dataset visualization eg. bar, line, slice, etc.
Chart.controllers = {};
+ /**
+ * The "used" size is the final value of a dimension property after all calculations have
+ * been performed. This method uses the computed style of `element` but returns undefined
+ * if the computed style is not expressed in pixels. That can happen in some cases where
+ * `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.
+ * TODO(SB) Move this method in the upcoming core.platform class.
+ * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
+ * @returns {Number} Size in pixels or undefined if unknown.
+ */
+ function readUsedSize(element, property) {
+ var value = helpers.getStyle(element, property);
+ var matches = value && value.match(/(\d+)px/);
+ return matches? Number(matches[1]) : undefined;
+ }
+
+ /**
+ * Initializes the canvas style and render size without modifying the canvas display size,
+ * since responsiveness is handled by the controller.resize() method. The config is used
+ * to determine the aspect ratio to apply in case no explicit height has been specified.
+ * TODO(SB) Move this method in the upcoming core.platform class.
+ */
+ function initCanvas(canvas, config) {
+ var style = canvas.style;
+
+ // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
+ // returns null or '' if no explicit value has been set to the canvas attribute.
+ var renderHeight = canvas.getAttribute('height');
+ var renderWidth = canvas.getAttribute('width');
+
+ // Chart.js modifies some canvas values that we want to restore on destroy
+ canvas._chartjs = {
+ initial: {
+ height: renderHeight,
+ width: renderWidth,
+ style: {
+ display: style.display,
+ height: style.height,
+ width: style.width
+ }
+ }
+ };
+
+ // Force canvas to display as block to avoid extra space caused by inline
+ // elements, which would interfere with the responsive resize process.
+ // https://github.com/chartjs/Chart.js/issues/2538
+ style.display = style.display || 'block';
+
+ if (renderWidth === null || renderWidth === '') {
+ var displayWidth = readUsedSize(canvas, 'width');
+ if (displayWidth !== undefined) {
+ canvas.width = displayWidth;
+ }
+ }
+
+ if (renderHeight === null || renderHeight === '') {
+ if (canvas.style.height === '') {
+ // If no explicit render height and style height, let's apply the aspect ratio,
+ // which one can be specified by the user but also by charts as default option
+ // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
+ canvas.height = canvas.width / (config.options.aspectRatio || 2);
+ } else {
+ var displayHeight = readUsedSize(canvas, 'height');
+ if (displayWidth !== undefined) {
+ canvas.height = displayHeight;
+ }
+ }
+ }
+
+ return canvas;
+ }
+
+ /**
+ * Restores the canvas initial state, such as render/display sizes and style.
+ * TODO(SB) Move this method in the upcoming core.platform class.
+ */
+ function releaseCanvas(canvas) {
+ if (!canvas._chartjs) {
+ return;
+ }
+
+ var initial = canvas._chartjs.initial;
+ ['height', 'width'].forEach(function(prop) {
+ var value = initial[prop];
+ if (value === undefined || value === null) {
+ canvas.removeAttribute(prop);
+ } else {
+ canvas.setAttribute(prop, value);
+ }
+ });
+
+ helpers.each(initial.style || {}, function(value, key) {
+ canvas.style[key] = value;
+ });
+
+ delete canvas._chartjs;
+ }
+
+ /**
+ * Initializes the given config with global and chart default values.
+ */
+ function initConfig(config) {
+ config = config || {};
+ return helpers.configMerge({
+ options: helpers.configMerge(
+ Chart.defaults.global,
+ Chart.defaults[config.type],
+ config.options || {}),
+ data: {
+ datasets: [],
+ labels: []
+ }
+ }, config);
+ }
+
/**
* @class Chart.Controller
* The main controller of a chart.
*/
- Chart.Controller = function(instance) {
+ Chart.Controller = function(context, config, instance) {
+ var me = this;
+ var canvas;
- this.chart = instance;
- this.config = instance.config;
- this.options = this.config.options = helpers.configMerge(Chart.defaults.global, Chart.defaults[this.config.type], this.config.options || {});
- this.id = helpers.uid();
+ config = initConfig(config);
+ canvas = initCanvas(context.canvas, config);
- Object.defineProperty(this, 'data', {
+ instance.ctx = context;
+ instance.canvas = canvas;
+ instance.config = config;
+ instance.width = canvas.width;
+ instance.height = canvas.height;
+ instance.aspectRatio = canvas.width / canvas.height;
+
+ helpers.retinaScale(instance);
+
+ me.id = helpers.uid();
+ me.chart = instance;
+ me.config = instance.config;
+ me.options = me.config.options;
+
+ Object.defineProperty(me, 'data', {
get: function() {
- return this.config.data;
+ return me.config.data;
+ }
+ });
+
+ // Always bind this so that if the responsive state changes we still work
+ helpers.addResizeListener(canvas.parentNode, function() {
+ if (me.config.options.responsive) {
+ me.resize();
}
});
// Add the chart instance to the global namespace
- Chart.instances[this.id] = this;
+ Chart.instances[me.id] = me;
- if (this.options.responsive) {
+ if (me.options.responsive) {
// Silent resize before chart draws
- this.resize(true);
+ me.resize(true);
}
- this.initialize();
+ me.initialize();
- return this;
+ return me;
};
helpers.extend(Chart.Controller.prototype, /** @lends Chart.Controller */ {
-
initialize: function() {
var me = this;
+
// Before init plugin notification
Chart.plugins.notify('beforeInit', [me]);
@@ -82,22 +219,27 @@ module.exports = function(Chart) {
resize: function(silent) {
var me = this;
var chart = me.chart;
+ var options = me.options;
var canvas = chart.canvas;
- var newWidth = helpers.getMaximumWidth(canvas);
- var aspectRatio = chart.aspectRatio;
- var newHeight = (me.options.maintainAspectRatio && isNaN(aspectRatio) === false && isFinite(aspectRatio) && aspectRatio !== 0) ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas);
+ var aspectRatio = (options.maintainAspectRatio && chart.aspectRatio) || null;
- var sizeChanged = chart.width !== newWidth || chart.height !== newHeight;
+ // the canvas render width and height will be casted to integers so make sure that
+ // the canvas display style uses the same integer values to avoid blurring effect.
+ var newWidth = Math.floor(helpers.getMaximumWidth(canvas));
+ var newHeight = Math.floor(aspectRatio? newWidth / aspectRatio : helpers.getMaximumHeight(canvas));
- if (!sizeChanged) {
- return me;
+ if (chart.width === newWidth && chart.height === newHeight) {
+ return;
}
canvas.width = chart.width = newWidth;
canvas.height = chart.height = newHeight;
helpers.retinaScale(chart);
+ canvas.style.width = newWidth + 'px';
+ canvas.style.height = newHeight + 'px';
+
// Notify any plugins about the resize
var newSize = {width: newWidth, height: newHeight};
Chart.plugins.notify('resize', [me, newSize]);
@@ -111,8 +253,6 @@ module.exports = function(Chart) {
me.stop();
me.update(me.options.responsiveAnimationDuration);
}
-
- return me;
},
ensureScalesHaveIDs: function() {
@@ -539,25 +679,23 @@ module.exports = function(Chart) {
destroy: function() {
var me = this;
+ var canvas = me.chart.canvas;
+
me.stop();
me.clear();
+
helpers.unbindEvents(me, me.events);
- helpers.removeResizeListener(me.chart.canvas.parentNode);
- // Reset canvas height/width attributes
- var canvas = me.chart.canvas;
- canvas.width = me.chart.width;
- canvas.height = me.chart.height;
+ if (canvas) {
+ helpers.removeResizeListener(canvas.parentNode);
+ releaseCanvas(canvas);
+ }
// if we scaled the canvas in response to a devicePixelRatio !== 1, we need to undo that transform here
if (me.chart.originalDevicePixelRatio !== undefined) {
me.chart.ctx.scale(1 / me.chart.originalDevicePixelRatio, 1 / me.chart.originalDevicePixelRatio);
}
- // Reset to the old style since it may have been changed by the device pixel ratio changes
- canvas.style.width = me.chart.originalCanvasStyleWidth;
- canvas.style.height = me.chart.originalCanvasStyleHeight;
-
Chart.plugins.notify('destroy', [me]);
delete Chart.instances[me.id]; | true |
Other | chartjs | Chart.js | 16bcd6adc579cb3deae16ea915680bc219924cdc.json | Fix initial aspect ratio when not responsive
When responsive is false and no canvas height explicitly set, the aspectRatio option wasn't applied because of the canvas default height. Prevent the retinaScale method to change the canvas display size since this method is called for none responsive charts, but instead make the resize() responsible of these changes. Also, as discussed some time ago, moved most of the core.js logic into core.controller.js. Clean up the destroy process and make sure that initial canvas values are properly saved and restored. | src/core/core.helpers.js | @@ -859,9 +859,6 @@ module.exports = function(Chart) {
// when destroy is called
chart.originalDevicePixelRatio = chart.originalDevicePixelRatio || pixelRatio;
}
-
- canvas.style.width = width + 'px';
- canvas.style.height = height + 'px';
};
// -- Canvas methods
helpers.clear = function(chart) { | true |
Other | chartjs | Chart.js | 16bcd6adc579cb3deae16ea915680bc219924cdc.json | Fix initial aspect ratio when not responsive
When responsive is false and no canvas height explicitly set, the aspectRatio option wasn't applied because of the canvas default height. Prevent the retinaScale method to change the canvas display size since this method is called for none responsive charts, but instead make the resize() responsible of these changes. Also, as discussed some time ago, moved most of the core.js logic into core.controller.js. Clean up the destroy process and make sure that initial canvas values are properly saved and restored. | src/core/core.js | @@ -5,12 +5,6 @@ module.exports = function() {
// Occupy the global variable of Chart, and create a simple base class
var Chart = function(context, config) {
var me = this;
- var helpers = Chart.helpers;
- me.config = config || {
- data: {
- datasets: []
- }
- };
// Support a jQuery'd canvas element
if (context.length && context[0].getContext) {
@@ -22,44 +16,9 @@ module.exports = function() {
context = context.getContext('2d');
}
- me.ctx = context;
- me.canvas = context.canvas;
-
- context.canvas.style.display = context.canvas.style.display || 'block';
-
- // Figure out what the size of the chart will be.
- // If the canvas has a specified width and height, we use those else
- // we look to see if the canvas node has a CSS width and height.
- // If there is still no height, fill the parent container
- me.width = context.canvas.width || parseInt(helpers.getStyle(context.canvas, 'width'), 10) || helpers.getMaximumWidth(context.canvas);
- me.height = context.canvas.height || parseInt(helpers.getStyle(context.canvas, 'height'), 10) || helpers.getMaximumHeight(context.canvas);
-
- me.aspectRatio = me.width / me.height;
-
- if (isNaN(me.aspectRatio) || isFinite(me.aspectRatio) === false) {
- // If the canvas has no size, try and figure out what the aspect ratio will be.
- // Some charts prefer square canvases (pie, radar, etc). If that is specified, use that
- // else use the canvas default ratio of 2
- me.aspectRatio = config.aspectRatio !== undefined ? config.aspectRatio : 2;
- }
-
- // Store the original style of the element so we can set it back
- me.originalCanvasStyleWidth = context.canvas.style.width;
- me.originalCanvasStyleHeight = context.canvas.style.height;
-
- // High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
- helpers.retinaScale(me);
- me.controller = new Chart.Controller(me);
-
- // Always bind this so that if the responsive state changes we still work
- helpers.addResizeListener(context.canvas.parentNode, function() {
- if (me.controller && me.controller.config.options.responsive) {
- me.controller.resize();
- }
- });
-
- return me.controller ? me.controller : me;
+ me.controller = new Chart.Controller(context, config, me);
+ return me.controller;
};
// Globally expose the defaults to allow for user updating/changing
@@ -106,5 +65,4 @@ module.exports = function() {
Chart.Chart = Chart;
return Chart;
-
}; | true |
Other | chartjs | Chart.js | 97e23737210bbfb5612b41e2573430350f1aeee6.json | Change `ticks.mode` to `scale.distribution` (#4582)
Fix `ticks.mode` behavior when `ticks.source` is `auto`: the lookup table is now built from the data and not from the ticks, so data (and ticks) are correctly distributed along the scale. Rename the option to `distribution` (more explicit than `mode`) and since this option applies from now on the data, it seems better to have it under `scale` instead `scale.ticks`. | src/scales/scale.time.js | @@ -64,6 +64,22 @@ function sorter(a, b) {
return a - b;
}
+function arrayUnique(items) {
+ var hash = {};
+ var out = [];
+ var i, ilen, item;
+
+ for (i = 0, ilen = items.length; i < ilen; ++i) {
+ item = items[i];
+ if (!hash[item]) {
+ hash[item] = true;
+ out.push(item);
+ }
+ }
+
+ return out;
+}
+
/**
* Returns an array of {time, pos} objects used to interpolate a specific `time` or position
* (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
@@ -73,31 +89,33 @@ function sorter(a, b) {
* 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 {Boolean} linear - If true, timestamps will be spread linearly along the min/max
- * range, so basically, the table will contains only two items: {min, 0} and {max, 1}. If
- * false, 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 best
- * case, all timestamps are linear, the table contains only min and max.
+ * @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
+ * best case, all timestamps are linear, the table contains only min and max.
*/
-function buildLookupTable(timestamps, min, max, linear) {
- if (linear || !timestamps.length) {
+function buildLookupTable(timestamps, min, max, distribution) {
+ if (distribution === 'linear' || !timestamps.length) {
return [
{time: min, pos: 0},
{time: max, pos: 1}
];
}
var table = [];
- var items = timestamps.slice(0);
+ var items = [min];
var i, ilen, prev, curr, next;
- if (min < timestamps[0]) {
- items.unshift(min);
- }
- if (max > timestamps[timestamps.length - 1]) {
- items.push(max);
+ for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
+ curr = timestamps[i];
+ if (curr > min && curr < max) {
+ items.push(curr);
+ }
}
+ items.push(max);
+
for (i = 0, ilen = items.length; i < ilen; ++i) {
next = items[i + 1];
prev = items[i - 1];
@@ -334,6 +352,15 @@ module.exports = function(Chart) {
var defaultConfig = {
position: 'bottom',
+ /**
+ * Data distribution along the scale:
+ * - 'linear': data are spread according to their time (distances can vary),
+ * - 'series': data are spread at the same distance from each other.
+ * @see https://github.com/chartjs/Chart.js/pull/4507
+ * @since 2.7.0
+ */
+ distribution: 'linear',
+
time: {
parser: false, // false == a pattern string from http://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 http://momentjs.com/docs/#/parsing/string-format/
@@ -359,15 +386,6 @@ module.exports = function(Chart) {
ticks: {
autoSkip: false,
- /**
- * Ticks distribution along the scale:
- * - 'linear': ticks and data are spread according to their time (distances can vary),
- * - 'series': ticks and data are spread at the same distance from each other.
- * @see https://github.com/chartjs/Chart.js/pull/4507
- * @since 2.7.0
- */
- mode: 'linear',
-
/**
* Ticks generation input values:
* - 'auto': generates "optimal" ticks based on scale size and time options.
@@ -430,44 +448,54 @@ module.exports = function(Chart) {
var me = this;
var chart = me.chart;
var options = me.options;
- var datasets = chart.data.datasets || [];
var min = parse(options.time.min, me) || MAX_INTEGER;
var max = parse(options.time.max, me) || MIN_INTEGER;
var timestamps = [];
+ var datasets = [];
var labels = [];
var i, j, ilen, jlen, data, timestamp;
// Convert labels to timestamps
for (i = 0, ilen = chart.data.labels.length; i < ilen; ++i) {
- timestamp = parse(chart.data.labels[i], me);
- min = Math.min(min, timestamp);
- max = Math.max(max, timestamp);
- labels.push(timestamp);
+ labels.push(parse(chart.data.labels[i], me));
}
// Convert data to timestamps
- for (i = 0, ilen = datasets.length; i < ilen; ++i) {
+ for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
if (chart.isDatasetVisible(i)) {
- data = datasets[i].data;
+ data = chart.data.datasets[i].data;
// Let's consider that all data have the same format.
if (helpers.isObject(data[0])) {
- timestamps[i] = [];
+ datasets[i] = [];
for (j = 0, jlen = data.length; j < jlen; ++j) {
timestamp = parse(data[j], me);
- min = Math.min(min, timestamp);
- max = Math.max(max, timestamp);
- timestamps[i][j] = timestamp;
+ timestamps.push(timestamp);
+ datasets[i][j] = timestamp;
}
} else {
- timestamps[i] = labels.slice(0);
+ timestamps.push.apply(timestamps, labels);
+ datasets[i] = labels.slice(0);
}
} else {
- timestamps[i] = [];
+ datasets[i] = [];
}
}
+ if (labels.length) {
+ // Sort labels **after** data have been converted
+ labels = arrayUnique(labels).sort(sorter);
+ min = Math.min(min, labels[0]);
+ max = Math.max(max, labels[labels.length - 1]);
+ }
+
+ if (timestamps.length) {
+ timestamps = arrayUnique(timestamps).sort(sorter);
+ min = Math.min(min, timestamps[0]);
+ max = Math.max(max, timestamps[timestamps.length - 1]);
+ }
+
// In case there is no valid min/max, let's use today limits
min = min === MAX_INTEGER ? +moment().startOf('day') : min;
max = max === MIN_INTEGER ? +moment().endOf('day') + 1 : max;
@@ -477,36 +505,36 @@ module.exports = function(Chart) {
me.max = Math.max(min + 1, max);
// PRIVATE
- me._datasets = timestamps;
me._horizontal = me.isHorizontal();
- me._labels = labels.sort(sorter); // Sort labels **after** data have been converted
me._table = [];
+ me._timestamps = {
+ data: timestamps,
+ datasets: datasets,
+ labels: labels
+ };
},
buildTicks: function() {
var me = this;
var min = me.min;
var max = me.max;
- var timeOpts = me.options.time;
- var ticksOpts = me.options.ticks;
+ var options = me.options;
+ var timeOpts = options.time;
+ var ticksOpts = options.ticks;
var formats = timeOpts.displayFormats;
var capacity = me.getLabelCapacity(min);
var unit = timeOpts.unit || determineUnit(timeOpts.minUnit, min, max, capacity);
var majorUnit = determineMajorUnit(unit);
var timestamps = [];
var ticks = [];
- var hash = {};
var i, ilen, timestamp;
switch (ticksOpts.source) {
case 'data':
- for (i = 0, ilen = me._datasets.length; i < ilen; ++i) {
- timestamps.push.apply(timestamps, me._datasets[i]);
- }
- timestamps.sort(sorter);
+ timestamps = me._timestamps.data;
break;
case 'labels':
- timestamps = me._labels;
+ timestamps = me._timestamps.labels;
break;
case 'auto':
default:
@@ -522,12 +550,10 @@ module.exports = function(Chart) {
min = parse(timeOpts.min, me) || min;
max = parse(timeOpts.max, me) || max;
- // Remove ticks outside the min/max range and duplicated entries
+ // Remove ticks outside the min/max range
for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
timestamp = timestamps[i];
- if (timestamp >= min && timestamp <= max && !hash[timestamp]) {
- // hash is used to efficiently detect timestamp duplicates
- hash[timestamp] = true;
+ if (timestamp >= min && timestamp <= max) {
ticks.push(timestamp);
}
}
@@ -540,7 +566,7 @@ module.exports = function(Chart) {
me._majorUnit = majorUnit;
me._minorFormat = formats[unit];
me._majorFormat = formats[majorUnit];
- me._table = buildLookupTable(ticks, min, max, ticksOpts.mode === 'linear');
+ me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
return ticksFromTimestamps(ticks, majorUnit);
},
@@ -609,7 +635,7 @@ module.exports = function(Chart) {
var time = null;
if (index !== undefined && datasetIndex !== undefined) {
- time = me._datasets[datasetIndex][index];
+ time = me._timestamps.datasets[datasetIndex][index];
}
if (time === null) { | true |
Other | chartjs | Chart.js | 97e23737210bbfb5612b41e2573430350f1aeee6.json | Change `ticks.mode` to `scale.distribution` (#4582)
Fix `ticks.mode` behavior when `ticks.source` is `auto`: the lookup table is now built from the data and not from the ticks, so data (and ticks) are correctly distributed along the scale. Rename the option to `distribution` (more explicit than `mode`) and since this option applies from now on the data, it seems better to have it under `scale` instead `scale.ticks`. | test/specs/scale.time.tests.js | @@ -21,12 +21,6 @@ describe('Time scale tests', function() {
return scale.ticks;
}
- function fetchTickPositions(scale) {
- return scale.ticks.map(function(tick, index) {
- return scale.getPixelForTick(index);
- });
- }
-
beforeEach(function() {
// Need a time matcher for getValueFromPixel
jasmine.addMatchers({
@@ -83,12 +77,12 @@ describe('Time scale tests', function() {
labelString: '',
lineHeight: 1.2
},
+ distribution: 'linear',
ticks: {
beginAtZero: false,
minRotation: 0,
maxRotation: 50,
mirror: false,
- mode: 'linear',
source: 'auto',
bounds: 'data',
padding: 0,
@@ -803,7 +797,7 @@ describe('Time scale tests', function() {
});
});
- describe('when ticks.mode', function() {
+ describe('when distribution', function() {
describe('is "series"', function() {
beforeEach(function() {
this.chart = window.acquireChart({
@@ -820,8 +814,8 @@ describe('Time scale tests', function() {
time: {
parser: 'YYYY'
},
+ distribution: 'series',
ticks: {
- mode: 'series',
source: 'labels'
}
}],
@@ -833,19 +827,18 @@ describe('Time scale tests', function() {
});
});
- it ('should space ticks out with the same gap, whatever their time values', function() {
+ it ('should space data out with the same gap, whatever their time values', function() {
var scale = this.chart.scales.x;
var start = scale.left;
var slice = scale.width / 4;
- var pixels = fetchTickPositions(scale);
- expect(pixels[0]).toBeCloseToPixel(start);
- expect(pixels[1]).toBeCloseToPixel(start + slice);
- expect(pixels[2]).toBeCloseToPixel(start + slice * 2);
- expect(pixels[3]).toBeCloseToPixel(start + slice * 3);
- expect(pixels[4]).toBeCloseToPixel(start + slice * 4);
+ expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start);
+ expect(scale.getPixelForValue('2019')).toBeCloseToPixel(start + slice);
+ expect(scale.getPixelForValue('2020')).toBeCloseToPixel(start + slice * 2);
+ expect(scale.getPixelForValue('2025')).toBeCloseToPixel(start + slice * 3);
+ expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * 4);
});
- it ('should add a step before if scale.min is before the first tick', function() {
+ it ('should add a step before if scale.min is before the first data', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.xAxes[0];
@@ -855,12 +848,11 @@ describe('Time scale tests', function() {
var start = scale.left;
var slice = scale.width / 5;
- var pixels = fetchTickPositions(scale);
- expect(pixels[0]).toBeCloseToPixel(start + slice);
- expect(pixels[4]).toBeCloseToPixel(start + slice * 5);
+ expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start + slice);
+ expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * 5);
});
- it ('should add a step after if scale.max is after the last tick', function() {
+ it ('should add a step after if scale.max is after the last data', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.xAxes[0];
@@ -870,12 +862,11 @@ describe('Time scale tests', function() {
var start = scale.left;
var slice = scale.width / 5;
- var pixels = fetchTickPositions(scale);
- expect(pixels[0]).toBeCloseToPixel(start);
- expect(pixels[4]).toBeCloseToPixel(start + slice * 4);
+ expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start);
+ expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * 4);
});
- it ('should add steps before and after if scale.min/max are outside the labels range', function() {
+ it ('should add steps before and after if scale.min/max are outside the data range', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.xAxes[0];
@@ -886,10 +877,9 @@ describe('Time scale tests', function() {
var start = scale.left;
var slice = scale.width / 6;
- var pixels = fetchTickPositions(scale);
- expect(pixels[0]).toBeCloseToPixel(start + slice);
- expect(pixels[4]).toBeCloseToPixel(start + slice * 5);
+ expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start + slice);
+ expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * 5);
});
});
describe('is "linear"', function() {
@@ -908,8 +898,8 @@ describe('Time scale tests', function() {
time: {
parser: 'YYYY'
},
+ distribution: 'linear',
ticks: {
- mode: 'linear',
source: 'labels'
}
}],
@@ -921,17 +911,16 @@ describe('Time scale tests', function() {
});
});
- it ('should space ticks out with a gap relative to their time values', function() {
+ it ('should space data out with a gap relative to their time values', function() {
var scale = this.chart.scales.x;
var start = scale.left;
var slice = scale.width / (2042 - 2017);
- var pixels = fetchTickPositions(scale);
- expect(pixels[0]).toBeCloseToPixel(start);
- expect(pixels[1]).toBeCloseToPixel(start + slice * (2019 - 2017));
- expect(pixels[2]).toBeCloseToPixel(start + slice * (2020 - 2017));
- expect(pixels[3]).toBeCloseToPixel(start + slice * (2025 - 2017));
- expect(pixels[4]).toBeCloseToPixel(start + slice * (2042 - 2017));
+ expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start);
+ expect(scale.getPixelForValue('2019')).toBeCloseToPixel(start + slice * (2019 - 2017));
+ expect(scale.getPixelForValue('2020')).toBeCloseToPixel(start + slice * (2020 - 2017));
+ expect(scale.getPixelForValue('2025')).toBeCloseToPixel(start + slice * (2025 - 2017));
+ expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * (2042 - 2017));
});
it ('should take in account scale min and max if outside the ticks range', function() {
var chart = this.chart;
@@ -944,13 +933,12 @@ describe('Time scale tests', function() {
var start = scale.left;
var slice = scale.width / (2050 - 2012);
- var pixels = fetchTickPositions(scale);
- expect(pixels[0]).toBeCloseToPixel(start + slice * (2017 - 2012));
- expect(pixels[1]).toBeCloseToPixel(start + slice * (2019 - 2012));
- expect(pixels[2]).toBeCloseToPixel(start + slice * (2020 - 2012));
- expect(pixels[3]).toBeCloseToPixel(start + slice * (2025 - 2012));
- expect(pixels[4]).toBeCloseToPixel(start + slice * (2042 - 2012));
+ expect(scale.getPixelForValue('2017')).toBeCloseToPixel(start + slice * (2017 - 2012));
+ expect(scale.getPixelForValue('2019')).toBeCloseToPixel(start + slice * (2019 - 2012));
+ expect(scale.getPixelForValue('2020')).toBeCloseToPixel(start + slice * (2020 - 2012));
+ expect(scale.getPixelForValue('2025')).toBeCloseToPixel(start + slice * (2025 - 2012));
+ expect(scale.getPixelForValue('2042')).toBeCloseToPixel(start + slice * (2042 - 2012));
});
});
}); | true |
Other | chartjs | Chart.js | 56fdd7ebc10c91834361a6228f2ebdb09530d690.json | Allow specifying bar chart via {x, y} data points (#4565) | docs/charts/bar.md | @@ -152,6 +152,12 @@ The `data` property of a dataset for a bar chart is specified as a an array of n
data: [20, 10]
```
+You can also specify the dataset as x/y coordinates.
+
+```javascript
+data: [{x:'2016-12-25', y:20}, {'2016-12-26', y:10}]
+```
+
# Stacked Bar Chart
Bar charts can be configured into stacked bar charts by changing the settings on the X and Y axes to enable stacking. Stacked bar charts can be used to show how one data series is made up of a number of smaller pieces. | true |
Other | chartjs | Chart.js | 56fdd7ebc10c91834361a6228f2ebdb09530d690.json | Allow specifying bar chart via {x, y} data points (#4565) | src/controllers/controller.bar.js | @@ -268,7 +268,7 @@ module.exports = function(Chart) {
var meta = me.getMeta();
var scale = me.getValueScale();
var datasets = chart.data.datasets;
- var value = Number(datasets[datasetIndex].data[index]);
+ var value = scale.getRightValue(datasets[datasetIndex].data[index]);
var stacked = scale.options.stacked;
var stack = meta.stack;
var start = 0;
@@ -283,7 +283,7 @@ module.exports = function(Chart) {
imeta.controller.getValueScaleId() === scale.id &&
chart.isDatasetVisible(i)) {
- ivalue = Number(datasets[i].data[index]);
+ ivalue = scale.getRightValue(datasets[i].data[index]);
if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) {
start += ivalue;
}
@@ -330,17 +330,16 @@ module.exports = function(Chart) {
draw: function() {
var me = this;
var chart = me.chart;
+ var scale = me.getIndexScale();
var rects = me.getMeta().data;
var dataset = me.getDataset();
var ilen = rects.length;
var i = 0;
- var d;
helpers.canvas.clipArea(chart.ctx, chart.chartArea);
for (; i < ilen; ++i) {
- d = dataset.data[i];
- if (d !== null && d !== undefined && !isNaN(d)) {
+ if (!isNaN(scale.getRightValue(dataset.data[i]))) {
rects[i].draw();
}
} | true |
Other | chartjs | Chart.js | 56fdd7ebc10c91834361a6228f2ebdb09530d690.json | Allow specifying bar chart via {x, y} data points (#4565) | src/scales/scale.linearbase.js | @@ -8,6 +8,13 @@ module.exports = function(Chart) {
var noop = helpers.noop;
Chart.LinearScaleBase = Chart.Scale.extend({
+ getRightValue: function(value) {
+ if (typeof value === 'string') {
+ return +value;
+ }
+ return Chart.Scale.prototype.getRightValue.call(this, value);
+ },
+
handleTickRangeOptions: function() {
var me = this;
var opts = me.options; | true |
Other | chartjs | Chart.js | d07fb284628076518ee15e2240b3eea1456e56ca.json | Add a note about breaking changes (#4555) | docs/developers/contributing.md | @@ -8,6 +8,7 @@ New contributions to the library are welcome, but we ask that you please follow
- Check that your code will pass tests, `gulp test` will run tests for you.
- Keep pull requests concise, and document new functionality in the relevant `.md` file.
- Consider whether your changes are useful for all users, or if creating a Chart.js [plugin](plugins.md) would be more appropriate.
+- Avoid breaking changes unless there is an upcoming major release, which are infrequent. We encourage people to write plugins for most new advanced features, so care a lot about backwards compatibility.
# Joining the project
| false |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | .eslintrc | @@ -197,8 +197,8 @@ rules:
space-before-blocks: [2, always]
space-before-function-paren: [2, never]
space-in-parens: [2, never]
- space-infix-ops: 0
- space-unary-ops: 0
+ space-infix-ops: 2
+ space-unary-ops: [2, {words: true, nonwords: false}]
spaced-comment: [2, always]
unicode-bom: 0
wrap-regex: 2 | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | gulpfile.js | @@ -23,7 +23,6 @@ var package = require('./package.json');
var srcDir = './src/';
var outDir = './dist/';
-var testDir = './test/';
var header = "/*!\n" +
" * Chart.js\n" +
@@ -128,8 +127,9 @@ function packageTask() {
function lintTask() {
var files = [
- srcDir + '**/*.js',
- testDir + '**/*.js'
+ 'samples/**/*.js',
+ 'src/**/*.js',
+ 'test/**/*.js'
];
// NOTE(SB) codeclimate has 'complexity' and 'max-statements' eslint rules way too strict
@@ -174,8 +174,8 @@ function startTest() {
'./test/jasmine.index.js',
'./src/**/*.js',
].concat(
- argv.inputs?
- argv.inputs.split(';'):
+ argv.inputs ?
+ argv.inputs.split(';') :
['./test/specs/**/*.js']
);
} | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | samples/charts/area/analyser.js | @@ -20,7 +20,7 @@
return;
}
- for (i=0, ilen=datasets.length; i<ilen; ++i) {
+ for (i = 0, ilen = datasets.length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i).$filler;
if (meta) {
dataset = datasets[i]; | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | samples/utils.js | @@ -41,8 +41,8 @@ window.randomScalingFactor = function() {
rand: function(min, max) {
var seed = this._seed;
- min = min === undefined? 0 : min;
- max = max === undefined? 1 : max;
+ min = min === undefined ? 0 : min;
+ max = max === undefined ? 1 : max;
this._seed = (seed * 9301 + 49297) % 233280;
return min + (this._seed / 233280) * (max - min);
},
@@ -59,7 +59,7 @@ window.randomScalingFactor = function() {
var data = [];
var i, value;
- for (i=0; i<count; ++i) {
+ for (i = 0; i < count; ++i) {
value = (from[i] || 0) + this.rand(min, max);
if (this.rand() <= continuity) {
data.push(Math.round(dfactor * value) / dfactor);
@@ -76,14 +76,14 @@ window.randomScalingFactor = function() {
var min = cfg.min || 0;
var max = cfg.max || 100;
var count = cfg.count || 8;
- var step = (max-min) / count;
+ var step = (max - min) / count;
var decimals = cfg.decimals || 8;
var dfactor = Math.pow(10, decimals) || 0;
var prefix = cfg.prefix || '';
var values = [];
var i;
- for (i=min; i<max; i+=step) {
+ for (i = min; i < max; i += step) {
values.push(prefix + Math.round(dfactor * i) / dfactor);
}
@@ -97,16 +97,16 @@ window.randomScalingFactor = function() {
var values = [];
var i, value;
- for (i=0; i<count; ++i) {
- value = Months[Math.ceil(i)%12];
+ for (i = 0; i < count; ++i) {
+ value = Months[Math.ceil(i) % 12];
values.push(value.substring(0, section));
}
return values;
},
transparentize: function(color, opacity) {
- var alpha = opacity === undefined? 0.5 : 1 - opacity;
+ var alpha = opacity === undefined ? 0.5 : 1 - opacity;
return Chart.helpers.color(color).alpha(alpha).rgbString();
},
| true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/controllers/controller.bar.js | @@ -156,11 +156,11 @@ module.exports = function(Chart) {
var ipixels = me.calculateBarIndexPixels(me.index, index, ruler);
model.horizontal = horizontal;
- model.base = reset? base : vpixels.base;
- model.x = horizontal? reset? base : vpixels.head : ipixels.center;
- model.y = horizontal? ipixels.center : reset? base : vpixels.head;
- model.height = horizontal? ipixels.size : undefined;
- model.width = horizontal? undefined : ipixels.size;
+ model.base = reset ? base : vpixels.base;
+ model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
+ model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
+ model.height = horizontal ? ipixels.size : undefined;
+ model.width = horizontal ? undefined : ipixels.size;
},
/**
@@ -200,7 +200,7 @@ module.exports = function(Chart) {
var chart = me.chart;
var scale = me.getIndexScale();
var stacked = scale.options.stacked;
- var ilen = last === undefined? chart.data.datasets.length : last + 1;
+ var ilen = last === undefined ? chart.data.datasets.length : last + 1;
var stacks = [];
var i, meta;
@@ -233,7 +233,7 @@ module.exports = function(Chart) {
var scale = me.getIndexScale();
var options = scale.options;
var stackCount = me.getStackCount();
- var fullSize = scale.isHorizontal()? scale.width : scale.height;
+ var fullSize = scale.isHorizontal() ? scale.width : scale.height;
var tickSize = fullSize / scale.ticks.length;
var categorySize = tickSize * options.categoryPercentage;
var fullBarSize = categorySize / stackCount;
@@ -311,7 +311,7 @@ module.exports = function(Chart) {
var base = scale.getPixelForValue(null, index, datasetIndex, isCombo);
var size = ruler.barSize;
- base -= isCombo? ruler.tickSize / 2 : 0;
+ base -= isCombo ? ruler.tickSize / 2 : 0;
base += ruler.fullBarSize * stackIndex;
base += ruler.categorySpacing / 2;
base += ruler.barSpacing / 2;
@@ -335,7 +335,7 @@ module.exports = function(Chart) {
helpers.canvas.clipArea(chart.ctx, chart.chartArea);
- for (; i<ilen; ++i) {
+ for (; i < ilen; ++i) {
d = dataset.data[i];
if (d !== null && d !== undefined && !isNaN(d)) {
rects[i].draw(); | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/controllers/controller.line.js | @@ -86,7 +86,7 @@ module.exports = function(Chart) {
}
// Update Points
- for (i=0, ilen=points.length; i<ilen; ++i) {
+ for (i = 0, ilen = points.length; i < ilen; ++i) {
me.updateElement(points[i], i, reset);
}
@@ -95,7 +95,7 @@ module.exports = function(Chart) {
}
// Now pivot the point for animation
- for (i=0, ilen=points.length; i<ilen; ++i) {
+ for (i = 0, ilen = points.length; i < ilen; ++i) {
points[i].pivot();
}
},
@@ -296,7 +296,7 @@ module.exports = function(Chart) {
helpers.canvas.unclipArea(chart.ctx);
// Draw the points
- for (; i<ilen; ++i) {
+ for (; i < ilen; ++i) {
points[i].draw(area);
}
}, | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/core/core.animation.js | @@ -49,7 +49,7 @@ module.exports = function(Chart) {
chart.animating = true;
}
- for (i=0, ilen=animations.length; i < ilen; ++i) {
+ for (i = 0, ilen = animations.length; i < ilen; ++i) {
if (animations[i].chart === chart) {
animations[i] = animation;
return; | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/core/core.controller.js | @@ -82,7 +82,7 @@ module.exports = function(Chart) {
me.config = config;
me.width = width;
me.height = height;
- me.aspectRatio = height? width / height : null;
+ me.aspectRatio = height ? width / height : null;
me.options = config.options;
me._bufferedRender = false;
@@ -546,7 +546,7 @@ module.exports = function(Chart) {
transition: function(easingValue) {
var me = this;
- for (var i=0, ilen=(me.data.datasets || []).length; i<ilen; ++i) {
+ for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
if (me.isDatasetVisible(i)) {
me.getDatasetMeta(i).controller.transition(easingValue);
}
@@ -568,7 +568,7 @@ module.exports = function(Chart) {
}
// Draw datasets reversed to support proper line stacking
- for (var i=(me.data.datasets || []).length - 1; i >= 0; --i) {
+ for (var i = (me.data.datasets || []).length - 1; i >= 0; --i) {
if (me.isDatasetVisible(i)) {
me.drawDataset(i, easingValue);
}
@@ -652,7 +652,7 @@ module.exports = function(Chart) {
getVisibleDatasetCount: function() {
var count = 0;
- for (var i = 0, ilen = this.data.datasets.length; i<ilen; ++i) {
+ for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
if (this.isDatasetVisible(i)) {
count++;
}
@@ -665,7 +665,7 @@ module.exports = function(Chart) {
// meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
// the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
- return typeof meta.hidden === 'boolean'? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
+ return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
},
generateLegend: function() {
@@ -762,10 +762,10 @@ module.exports = function(Chart) {
},
updateHoverStyle: function(elements, mode, enabled) {
- var method = enabled? 'setHoverStyle' : 'removeHoverStyle';
+ var method = enabled ? 'setHoverStyle' : 'removeHoverStyle';
var element, i, ilen;
- for (i=0, ilen=elements.length; i<ilen; ++i) {
+ for (i = 0, ilen = elements.length; i < ilen; ++i) {
element = elements[i];
if (element) {
this.getDatasetMeta(element._datasetIndex).controller[method](element); | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/core/core.datasetController.js | @@ -170,7 +170,7 @@ module.exports = function(Chart) {
var metaData = meta.data;
var i, ilen;
- for (i=0, ilen=data.length; i<ilen; ++i) {
+ for (i = 0, ilen = data.length; i < ilen; ++i) {
metaData[i] = metaData[i] || me.createMetaData(i);
}
@@ -214,7 +214,7 @@ module.exports = function(Chart) {
var ilen = elements.length;
var i = 0;
- for (; i<ilen; ++i) {
+ for (; i < ilen; ++i) {
elements[i].transition(easingValue);
}
@@ -233,7 +233,7 @@ module.exports = function(Chart) {
meta.dataset.draw();
}
- for (; i<ilen; ++i) {
+ for (; i < ilen; ++i) {
elements[i].draw();
}
},
@@ -284,7 +284,7 @@ module.exports = function(Chart) {
* @private
*/
insertElements: function(start, count) {
- for (var i=0; i<count; ++i) {
+ for (var i = 0; i < count; ++i) {
this.addElementAndReset(start + i);
}
},
@@ -293,7 +293,7 @@ module.exports = function(Chart) {
* @private
*/
onDataPush: function() {
- this.insertElements(this.getDataset().data.length-1, arguments.length);
+ this.insertElements(this.getDataset().data.length - 1, arguments.length);
},
/** | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/core/core.element.js | @@ -7,7 +7,7 @@ function interpolate(start, view, model, ease) {
var keys = Object.keys(model);
var i, ilen, key, actual, origin, target, type, c0, c1;
- for (i=0, ilen=keys.length; i<ilen; ++i) {
+ for (i = 0, ilen = keys.length; i < ilen; ++i) {
key = keys[i];
target = model[key];
@@ -30,9 +30,9 @@ function interpolate(start, view, model, ease) {
origin = start[key];
- type = typeof(target);
+ type = typeof target;
- if (type === typeof(origin)) {
+ if (type === typeof origin) {
if (type === 'string') {
c0 = color(origin);
if (c0.valid) { | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/core/core.helpers.js | @@ -52,7 +52,7 @@ module.exports = function(Chart) {
for (i = 0; i < slen; ++i) {
scale = source[key][i];
- type = helpers.valueOrDefault(scale.type, key === 'xAxes'? 'category' : 'linear');
+ type = helpers.valueOrDefault(scale.type, key === 'xAxes' ? 'category' : 'linear');
if (i >= target[key].length) {
target[key].push({});
@@ -88,12 +88,12 @@ module.exports = function(Chart) {
return filtered;
};
- helpers.findIndex = Array.prototype.findIndex?
+ helpers.findIndex = Array.prototype.findIndex ?
function(array, callback, scope) {
return array.findIndex(callback, scope);
} :
function(array, callback, scope) {
- scope = scope === undefined? array : scope;
+ scope = scope === undefined ? array : scope;
for (var i = 0, ilen = array.length; i < ilen; ++i) {
if (callback.call(scope, array[i], i, array)) {
return i;
@@ -175,7 +175,7 @@ module.exports = function(Chart) {
return min;
}, Number.POSITIVE_INFINITY);
};
- helpers.sign = Math.sign?
+ helpers.sign = Math.sign ?
function(x) {
return Math.sign(x);
} :
@@ -186,7 +186,7 @@ module.exports = function(Chart) {
}
return x > 0 ? 1 : -1;
};
- helpers.log10 = Math.log10?
+ helpers.log10 = Math.log10 ?
function(x) {
return Math.log10(x);
} :
@@ -446,7 +446,7 @@ module.exports = function(Chart) {
// Private helper function to convert max-width/max-height values that may be percentages into a number
function parseMaxStyle(styleValue, node, parentProperty) {
var valueInPixels;
- if (typeof(styleValue) === 'string') {
+ if (typeof styleValue === 'string') {
valueInPixels = parseInt(styleValue, 10);
if (styleValue.indexOf('%') !== -1) {
@@ -484,8 +484,8 @@ module.exports = function(Chart) {
if (hasCNode || hasCContainer) {
return Math.min(
- hasCNode? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
- hasCContainer? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
+ hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
+ hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
}
return 'none';
@@ -504,15 +504,15 @@ module.exports = function(Chart) {
var paddingRight = parseInt(helpers.getStyle(container, 'padding-right'), 10);
var w = container.clientWidth - paddingLeft - paddingRight;
var cw = helpers.getConstraintWidth(domNode);
- return isNaN(cw)? w : Math.min(w, cw);
+ return isNaN(cw) ? w : Math.min(w, cw);
};
helpers.getMaximumHeight = function(domNode) {
var container = domNode.parentNode;
var paddingTop = parseInt(helpers.getStyle(container, 'padding-top'), 10);
var paddingBottom = parseInt(helpers.getStyle(container, 'padding-bottom'), 10);
var h = container.clientHeight - paddingTop - paddingBottom;
var ch = helpers.getConstraintHeight(domNode);
- return isNaN(ch)? h : Math.min(h, ch);
+ return isNaN(ch) ? h : Math.min(h, ch);
};
helpers.getStyle = function(el, property) {
return el.currentStyle ?
@@ -604,7 +604,7 @@ module.exports = function(Chart) {
return numberOfLines;
};
- helpers.color = !color?
+ helpers.color = !color ?
function(value) {
console.error('Color.js not found!');
return value; | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/core/core.layoutService.js | @@ -75,7 +75,7 @@ module.exports = function(Chart) {
* @param {Object} layoutItem - the item to remove from the layout
*/
removeBox: function(chart, layoutItem) {
- var index = chart.boxes? chart.boxes.indexOf(layoutItem) : -1;
+ var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
if (index !== -1) {
chart.boxes.splice(index, 1);
}
@@ -93,7 +93,7 @@ module.exports = function(Chart) {
var i = 0;
var prop;
- for (; i<ilen; ++i) {
+ for (; i < ilen; ++i) {
prop = props[i];
if (options.hasOwnProperty(prop)) {
item[prop] = options[prop]; | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/core/core.plugin.js | @@ -102,7 +102,7 @@ module.exports = function(Chart) {
var ilen = descriptors.length;
var i, descriptor, plugin, params, method;
- for (i=0; i<ilen; ++i) {
+ for (i = 0; i < ilen; ++i) {
descriptor = descriptors[i];
plugin = descriptor.plugin;
method = plugin[hook]; | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/core/core.scale.js | @@ -378,8 +378,8 @@ module.exports = function(Chart) {
// Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned which means that the right padding is dominated
// by the font height
if (me.labelRotation !== 0) {
- me.paddingLeft = opts.position === 'bottom'? (cosRotation * firstLabelWidth) + 3: (cosRotation * lineSpace) + 3; // add 3 px to move away from canvas edges
- me.paddingRight = opts.position === 'bottom'? (cosRotation * lineSpace) + 3: (cosRotation * lastLabelWidth) + 3;
+ me.paddingLeft = opts.position === 'bottom' ? (cosRotation * firstLabelWidth) + 3 : (cosRotation * lineSpace) + 3; // add 3 px to move away from canvas edges
+ me.paddingRight = opts.position === 'bottom' ? (cosRotation * lineSpace) + 3 : (cosRotation * lastLabelWidth) + 3;
} else {
me.paddingLeft = firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges
me.paddingRight = lastLabelWidth / 2 + 3;
@@ -438,7 +438,7 @@ module.exports = function(Chart) {
return NaN;
}
// isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
- if (typeof(rawValue) === 'number' && !isFinite(rawValue)) {
+ if (typeof rawValue === 'number' && !isFinite(rawValue)) {
return NaN;
}
// If it is in fact an object, dive in one more level
@@ -627,13 +627,13 @@ module.exports = function(Chart) {
if (options.position === 'bottom') {
// bottom
- textBaseline = !isRotated? 'top':'middle';
- textAlign = !isRotated? 'center': 'right';
+ textBaseline = !isRotated ? 'top' : 'middle';
+ textAlign = !isRotated ? 'center' : 'right';
labelY = me.top + labelYOffset;
} else {
// top
- textBaseline = !isRotated? 'bottom':'middle';
- textAlign = !isRotated? 'center': 'left';
+ textBaseline = !isRotated ? 'bottom' : 'middle';
+ textAlign = !isRotated ? 'center' : 'left';
labelY = me.bottom - labelYOffset;
}
| true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/elements/element.point.js | @@ -85,18 +85,18 @@ module.exports = Element.extend({
// Cliping for Points.
// going out from inner charArea?
- if ((chartArea !== undefined) && ((model.x < chartArea.left) || (chartArea.right*errMargin < model.x) || (model.y < chartArea.top) || (chartArea.bottom*errMargin < model.y))) {
+ if ((chartArea !== undefined) && ((model.x < chartArea.left) || (chartArea.right * errMargin < model.x) || (model.y < chartArea.top) || (chartArea.bottom * errMargin < model.y))) {
// Point fade out
if (model.x < chartArea.left) {
ratio = (x - model.x) / (chartArea.left - model.x);
- } else if (chartArea.right*errMargin < model.x) {
+ } else if (chartArea.right * errMargin < model.x) {
ratio = (model.x - x) / (model.x - chartArea.right);
} else if (model.y < chartArea.top) {
ratio = (y - model.y) / (chartArea.top - model.y);
- } else if (chartArea.bottom*errMargin < model.y) {
+ } else if (chartArea.bottom * errMargin < model.y) {
ratio = (model.y - y) / (model.y - chartArea.bottom);
}
- ratio = Math.round(ratio*100) / 100;
+ ratio = Math.round(ratio * 100) / 100;
ctx.strokeStyle = color(ctx.strokeStyle).alpha(ratio).rgbString();
ctx.fillStyle = color(ctx.fillStyle).alpha(ratio).rgbString();
} | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/elements/element.rectangle.js | @@ -66,15 +66,15 @@ module.exports = Element.extend({
top = vm.y;
bottom = vm.base;
signX = 1;
- signY = bottom > top? 1: -1;
+ signY = bottom > top ? 1 : -1;
borderSkipped = vm.borderSkipped || 'bottom';
} else {
// horizontal bar
left = vm.base;
right = vm.x;
top = vm.y - vm.height / 2;
bottom = vm.y + vm.height / 2;
- signX = right > left? 1: -1;
+ signX = right > left ? 1 : -1;
signY = 1;
borderSkipped = vm.borderSkipped || 'left';
}
@@ -84,13 +84,13 @@ module.exports = Element.extend({
if (borderWidth) {
// borderWidth shold be less than bar width and bar height.
var barSize = Math.min(Math.abs(left - right), Math.abs(top - bottom));
- borderWidth = borderWidth > barSize? barSize: borderWidth;
+ borderWidth = borderWidth > barSize ? barSize : borderWidth;
var halfStroke = borderWidth / 2;
// Adjust borderWidth when bar top position is near vm.base(zero).
- var borderLeft = left + (borderSkipped !== 'left'? halfStroke * signX: 0);
- var borderRight = right + (borderSkipped !== 'right'? -halfStroke * signX: 0);
- var borderTop = top + (borderSkipped !== 'top'? halfStroke * signY: 0);
- var borderBottom = bottom + (borderSkipped !== 'bottom'? -halfStroke * signY: 0);
+ var borderLeft = left + (borderSkipped !== 'left' ? halfStroke * signX : 0);
+ var borderRight = right + (borderSkipped !== 'right' ? -halfStroke * signX : 0);
+ var borderTop = top + (borderSkipped !== 'top' ? halfStroke * signY : 0);
+ var borderBottom = bottom + (borderSkipped !== 'bottom' ? -halfStroke * signY : 0);
// not become a vertical line?
if (borderLeft !== borderRight) {
top = borderTop; | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/helpers/helpers.canvas.js | @@ -27,8 +27,8 @@ var exports = module.exports = {
*/
roundedRect: function(ctx, x, y, width, height, radius) {
if (radius) {
- var rx = Math.min(radius, width/2);
- var ry = Math.min(radius, height/2);
+ var rx = Math.min(radius, width / 2);
+ var ry = Math.min(radius, height / 2);
ctx.moveTo(x + rx, y);
ctx.lineTo(x + width - rx, y);
@@ -180,10 +180,10 @@ var exports = module.exports = {
}
ctx.bezierCurveTo(
- flip? previous.controlPointPreviousX : previous.controlPointNextX,
- flip? previous.controlPointPreviousY : previous.controlPointNextY,
- flip? target.controlPointNextX : target.controlPointPreviousX,
- flip? target.controlPointNextY : target.controlPointPreviousY,
+ flip ? previous.controlPointPreviousX : previous.controlPointNextX,
+ flip ? previous.controlPointPreviousY : previous.controlPointNextY,
+ flip ? target.controlPointNextX : target.controlPointPreviousX,
+ flip ? target.controlPointNextY : target.controlPointPreviousY,
target.x,
target.y);
} | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/helpers/helpers.core.js | @@ -37,7 +37,7 @@ var helpers = {
* @returns {Boolean}
* @function
*/
- isArray: Array.isArray? Array.isArray : function(value) {
+ isArray: Array.isArray ? Array.isArray : function(value) {
return Object.prototype.toString.call(value) === '[object Array]';
},
@@ -58,7 +58,7 @@ var helpers = {
* @returns {*}
*/
valueOrDefault: function(value, defaultValue) {
- return typeof value === 'undefined'? defaultValue : value;
+ return typeof value === 'undefined' ? defaultValue : value;
},
/**
@@ -69,7 +69,7 @@ var helpers = {
* @returns {*}
*/
valueAtIndexOrDefault: function(value, index, defaultValue) {
- return helpers.valueOrDefault(helpers.isArray(value)? value[index] : value, defaultValue);
+ return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
},
/**
@@ -131,7 +131,7 @@ var helpers = {
return false;
}
- for (i = 0, ilen=a0.length; i < ilen; ++i) {
+ for (i = 0, ilen = a0.length; i < ilen; ++i) {
v0 = a0[i];
v1 = a1[i];
@@ -164,7 +164,7 @@ var helpers = {
var klen = keys.length;
var k = 0;
- for (; k<klen; ++k) {
+ for (; k < klen; ++k) {
target[keys[k]] = helpers.clone(source[keys[k]]);
}
@@ -215,7 +215,7 @@ var helpers = {
* @returns {Object} The `target` object.
*/
merge: function(target, source, options) {
- var sources = helpers.isArray(source)? source : [source];
+ var sources = helpers.isArray(source) ? source : [source];
var ilen = sources.length;
var merge, i, keys, klen, k;
@@ -226,14 +226,14 @@ var helpers = {
options = options || {};
merge = options.merger || helpers._merger;
- for (i=0; i<ilen; ++i) {
+ for (i = 0; i < ilen; ++i) {
source = sources[i];
if (!helpers.isObject(source)) {
continue;
}
keys = Object.keys(source);
- for (k=0, klen = keys.length; k<klen; ++k) {
+ for (k = 0, klen = keys.length; k < klen; ++k) {
merge(keys[k], target, source, options);
}
} | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/helpers/helpers.options.js | @@ -15,7 +15,7 @@ module.exports = {
* @since 2.7.0
*/
toLineHeight: function(value, size) {
- var matches = (''+value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
+ var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
if (!matches || matches[1] === 'normal') {
return size * 1.2;
} | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/helpers/helpers.time.js | @@ -1,7 +1,7 @@
'use strict';
var moment = require('moment');
-moment = typeof(moment) === 'function' ? moment : window.moment;
+moment = typeof moment === 'function' ? moment : window.moment;
var helpers = require('./helpers.core');
@@ -55,7 +55,7 @@ function generateTicksNiceRange(options, dataRange, niceRange) {
var ticks = [];
if (options.maxTicks) {
var stepSize = options.stepSize;
- var startTick = helpers.isNullOrUndef(options.min)? niceRange.min : options.min;
+ var startTick = helpers.isNullOrUndef(options.min) ? niceRange.min : options.min;
var majorUnit = options.majorUnit;
var majorUnitStart = majorUnit ? moment(startTick).add(1, majorUnit).startOf(majorUnit) : startTick;
var startRange = majorUnitStart.valueOf() - startTick; | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/platforms/platform.dom.js | @@ -39,7 +39,7 @@ var eventTypeMap = {
function readUsedSize(element, property) {
var value = helpers.getStyle(element, property);
var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
- return matches? Number(matches[1]) : undefined;
+ return matches ? Number(matches[1]) : undefined;
}
/**
@@ -119,7 +119,7 @@ var supportsEventListenerOptions = (function() {
// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
// https://github.com/chartjs/Chart.js/issues/4287
-var eventListenerOptions = supportsEventListenerOptions? {passive: true} : false;
+var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
function addEventListener(node, type, listener) {
node.addEventListener(type, listener, eventListenerOptions);
@@ -134,8 +134,8 @@ function createEvent(type, chart, x, y, nativeEvent) {
type: type,
chart: chart,
native: nativeEvent || null,
- x: x !== undefined? x : null,
- y: y !== undefined? y : null,
+ x: x !== undefined ? x : null,
+ y: y !== undefined ? y : null,
};
}
@@ -149,18 +149,18 @@ function createResizer(handler) {
var iframe = document.createElement('iframe');
iframe.className = 'chartjs-hidden-iframe';
iframe.style.cssText =
- 'display:block;'+
- 'overflow:hidden;'+
- 'border:0;'+
- 'margin:0;'+
- 'top:0;'+
- 'left:0;'+
- 'bottom:0;'+
- 'right:0;'+
- 'height:100%;'+
- 'width:100%;'+
- 'position:absolute;'+
- 'pointer-events:none;'+
+ 'display:block;' +
+ 'overflow:hidden;' +
+ 'border:0;' +
+ 'margin:0;' +
+ 'top:0;' +
+ 'left:0;' +
+ 'bottom:0;' +
+ 'right:0;' +
+ 'height:100%;' +
+ 'width:100%;' +
+ 'position:absolute;' +
+ 'pointer-events:none;' +
'z-index:-1;';
// Prevent the iframe to gain focus on tab. | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/plugins/plugin.filler.js | @@ -29,20 +29,20 @@ module.exports = function() {
var points = (visible && meta.dataset._children) || [];
var length = points.length || 0;
- return !length? null : function(point, i) {
+ return !length ? null : function(point, i) {
return (i < length && points[i]._view) || null;
};
},
boundary: function(source) {
var boundary = source.boundary;
- var x = boundary? boundary.x : null;
- var y = boundary? boundary.y : null;
+ var x = boundary ? boundary.x : null;
+ var y = boundary ? boundary.y : null;
return function(point) {
return {
- x: x === null? point.x : x,
- y: y === null? point.y : y,
+ x: x === null ? point.x : x,
+ y: y === null ? point.y : y,
};
};
}
@@ -114,9 +114,9 @@ module.exports = function() {
// controllers might still use it (e.g. the Smith chart).
if (fill === 'start') {
- target = model.scaleBottom === undefined? scale.bottom : model.scaleBottom;
+ target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
} else if (fill === 'end') {
- target = model.scaleTop === undefined? scale.top : model.scaleTop;
+ target = model.scaleTop === undefined ? scale.top : model.scaleTop;
} else if (model.scaleZero !== undefined) {
target = model.scaleZero;
} else if (scale.getBasePosition) {
@@ -133,8 +133,8 @@ module.exports = function() {
if (typeof target === 'number' && isFinite(target)) {
horizontal = scale.isHorizontal();
return {
- x: horizontal? target : null,
- y: horizontal? null : target
+ x: horizontal ? target : null,
+ y: horizontal ? null : target
};
}
}
@@ -201,16 +201,16 @@ module.exports = function() {
// building first area curve (normal)
ctx.moveTo(curve0[0].x, curve0[0].y);
- for (i=1; i<len0; ++i) {
- helpers.canvas.lineTo(ctx, curve0[i-1], curve0[i]);
+ for (i = 1; i < len0; ++i) {
+ helpers.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
}
// joining the two area curves
- ctx.lineTo(curve1[len1-1].x, curve1[len1-1].y);
+ ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
// building opposite area curve (reverse)
- for (i=len1-1; i>0; --i) {
- helpers.canvas.lineTo(ctx, curve1[i], curve1[i-1], true);
+ for (i = len1 - 1; i > 0; --i) {
+ helpers.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
}
}
@@ -226,7 +226,7 @@ module.exports = function() {
ctx.beginPath();
for (i = 0, ilen = (count + !!loop); i < ilen; ++i) {
- index = i%count;
+ index = i % count;
p0 = points[index]._view;
p1 = mapper(p0, index, view);
d0 = isDrawable(p0);
@@ -286,7 +286,7 @@ module.exports = function() {
sources.push(source);
}
- for (i=0; i<count; ++i) {
+ for (i = 0; i < count; ++i) {
source = sources[i];
if (!source) {
continue; | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/plugins/plugin.legend.js | @@ -19,7 +19,7 @@ defaults._set('global', {
var meta = ci.getDatasetMeta(index);
// See controller.isDatasetVisible comment
- meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;
+ meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
// We hid a dataset ... rerender the chart
ci.update(); | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/plugins/plugin.title.js | @@ -153,7 +153,7 @@ module.exports = function(Chart) {
fontFamily = valueOrDefault(opts.fontFamily, globalDefaults.defaultFontFamily),
titleFont = helpers.fontString(fontSize, fontStyle, fontFamily),
lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize),
- offset = lineHeight/2 + opts.padding,
+ offset = lineHeight / 2 + opts.padding,
rotation = 0,
titleX,
titleY, | true |
Other | chartjs | Chart.js | 4c763bff44345ff5bbf2acc97cbce8918fa5b055.json | Enforce spaces around infix/unary words operators (#4547)
Enable ESLint `space-infix-ops` and `space-unary-ops` (for words only) rules. Also added `samples` to the linting task to match Code Climate expectations.
http://eslint.org/docs/rules/space-infix-ops
http://eslint.org/docs/rules/space-unary-ops | src/scales/scale.logarithmic.js | @@ -206,7 +206,7 @@ module.exports = function(Chart) {
} else if (newVal === me.minNotZero) {
pixel = me.bottom - innerDimension * 0.02;
} else {
- pixel = me.bottom - innerDimension * 0.02 - (innerDimension * 0.98/ range * (helpers.log10(newVal)-helpers.log10(me.minNotZero)));
+ pixel = me.bottom - innerDimension * 0.02 - (innerDimension * 0.98 / range * (helpers.log10(newVal) - helpers.log10(me.minNotZero)));
}
} else if (me.end === 0 && tickOpts.reverse) {
range = helpers.log10(me.start) - helpers.log10(me.minNotZero);
@@ -215,7 +215,7 @@ module.exports = function(Chart) {
} else if (newVal === me.minNotZero) {
pixel = me.top + innerDimension * 0.02;
} else {
- pixel = me.top + innerDimension * 0.02 + (innerDimension * 0.98/ range * (helpers.log10(newVal)-helpers.log10(me.minNotZero)));
+ pixel = me.top + innerDimension * 0.02 + (innerDimension * 0.98 / range * (helpers.log10(newVal) - helpers.log10(me.minNotZero)));
}
} else if (newVal === 0) {
pixel = tickOpts.reverse ? me.top : me.bottom; | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.