From b11fa310b6e214e48893023de79da01b794ea07a Mon Sep 17 00:00:00 2001 From: Irina Kuzmina Date: Mon, 26 Aug 2024 11:47:05 +0300 Subject: [PATCH] fix(D3 plugin): fix the detection of the closest point for line chart (#512) --- src/plugins/d3/__stories__/line/Split.stories.tsx | 5 +++++ src/plugins/d3/renderer/utils/get-closest-data.ts | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/src/plugins/d3/__stories__/line/Split.stories.tsx b/src/plugins/d3/__stories__/line/Split.stories.tsx index 013e75a1..7def385f 100644 --- a/src/plugins/d3/__stories__/line/Split.stories.tsx +++ b/src/plugins/d3/__stories__/line/Split.stories.tsx @@ -91,6 +91,11 @@ const ChartStory = () => { }, }, }, + chart: { + events: { + click: action('chart.events.click'), + }, + }, }; if (loading) { diff --git a/src/plugins/d3/renderer/utils/get-closest-data.ts b/src/plugins/d3/renderer/utils/get-closest-data.ts index 448edcc9..734c7343 100644 --- a/src/plugins/d3/renderer/utils/get-closest-data.ts +++ b/src/plugins/d3/renderer/utils/get-closest-data.ts @@ -54,6 +54,14 @@ function getClosestPointsByXValue(x: number, y: number, points: ShapePoint[]) { closestYIndex = closestPoints.length - 1; } else { closestYIndex = closestPoints.findIndex((p) => y > p.y0 && y < p.y1); + if (closestYIndex === -1) { + const sortedY = sort( + closestPoints.map((p, index) => ({index, y: p.y1 + (p.y0 - p.y1) / 2})), + (p) => p.y, + ); + const sortedYIndex = bisector<{y: number}, number>((p) => p.y).center(sortedY, y); + closestYIndex = sortedY[sortedYIndex]?.index ?? -1; + } } return closestPoints.map((p, i) => ({