Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Display tooltip for only one item per dataset at a time #5578

Closed
25 changes: 24 additions & 1 deletion src/core/core.interaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ module.exports = {
*/
x: function(chart, e, options) {
var position = getRelativePosition(e, chart);
var distanceMetric = getDistanceMetricForAxis('x');
var items = [];
var intersectsItem = false;

Expand All @@ -293,7 +294,29 @@ module.exports = {
if (options.intersect && !intersectsItem) {
items = [];
}
return items;

// group by dataset
var byIndex = items.reduce(function(res, element) {
if (res[element._datasetIndex] === undefined) {
res[element._datasetIndex] = [element];
} else {
res[element._datasetIndex].push(element);
}
return res;
}, {});

// sort by distance
Object.keys(byIndex).forEach(function(key) {
byIndex[key].sort(function(a, b) {
return distanceMetric(position, a.getCenterPoint()) - distanceMetric(position, b.getCenterPoint());
});
});

return Object.keys(byIndex).map(
function(key) {
return byIndex[key][0];
}
);
},

/**
Expand Down
47 changes: 39 additions & 8 deletions test/specs/core.interaction.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -556,22 +556,53 @@ describe('Core.Interaction', function() {
describe('x mode', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
type: 'scatter',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 40, 30],
pointRadius: [5, 10, 5],
data: [
{
x: 1,
y: 10
},
{
x: 2,
y: 40
},
{
x: 2,
y: 40
},
{
x: 3,
y: 30
}],
pointRadius: [10, 5, 10, 5],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointRadius: [10, 10, 10],
data: [
{
x: 1,
y: 40
},
{
x: 2,
y: 40
},
{
x: 2,
y: 40
},
{
x: 3,
y: 40
}],
pointRadius: [10, 5, 10, 5],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
}]
}
});
});
Expand Down Expand Up @@ -610,7 +641,7 @@ describe('Core.Interaction', function() {
expect(elements).toEqual([]);
});

it('should return items at the same x value when intersect is true', function() {
it('should return one item per dataset at the same x value when intersect is true', function() {
var chart = this.chart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
Expand Down