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

Fix tooltip positioning when charts are rendered inside an scaled div #2034

Merged
merged 2 commits into from
Jun 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion packages/core/src/lib/interactivity/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ export * from './detect'
export const getRelativeCursor = (el, event) => {
const { clientX, clientY } = event
const bounds = el.getBoundingClientRect()
const box = el.getBBox()

return [clientX - bounds.left, clientY - bounds.top]
// In a normal situation mouse enter / mouse leave events
// capture the position ok. But when the chart is inside a scaled
// element with a CSS transform like: `transform: scale(2);`
// tooltip are not positioned ok.
// Comparing original width `box.width` agains scaled width give us the
// scaling factor to calculate ok mouse position
const scaling = box.width === bounds.width ? 1 : box.width / bounds.width
return [(clientX - bounds.left) * scaling, (clientY - bounds.top) * scaling]
}
13 changes: 11 additions & 2 deletions packages/tooltip/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,17 @@ export const useTooltipHandlers = (container: MutableRefObject<HTMLDivElement>)
const showTooltipFromEvent: TooltipActionsContextData['showTooltipFromEvent'] = useCallback(
(content: JSX.Element, event: MouseEvent, anchor: TooltipAnchor = 'top') => {
const bounds = container.current.getBoundingClientRect()
const x = event.clientX - bounds.left
const y = event.clientY - bounds.top
const offsetWidth = container.current.offsetWidth
// In a normal situation mouse enter / mouse leave events
// capture the position ok. But when the chart is inside a scaled
// element with a CSS transform like: `transform: scale(2);`
// tooltip are not positioned ok.
// Comparing original width `offsetWidth` agains scaled
// width give us the scaling factor to calculate
// ok mouse position
const scaling = offsetWidth === bounds.width ? 1 : offsetWidth / bounds.width
const x = (event.clientX - bounds.left) * scaling
const y = (event.clientY - bounds.top) * scaling

if (anchor === 'left' || anchor === 'right') {
if (x < bounds.width / 2) anchor = 'right'
Expand Down