Skip to content

Commit

Permalink
feat(tooltip): improve positioning
Browse files Browse the repository at this point in the history
  • Loading branch information
Raphaël Benitte committed Sep 19, 2017
1 parent 1164883 commit 288657c
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions src/components/charts/Container.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,8 @@ const tooltipStyle = {
pointerEvents: 'none',
position: 'absolute',
zIndex: 10,
top: 0,
left: 0,
}

const Tooltip = ({ x, y, children, theme }) => (
<div style={{ ...tooltipStyle, top: y, left: x, ...theme.tooltip }}>{children}</div>
)

const noopHandlers = {
showTooltip: noop,
hideTooltip: noop,
Expand All @@ -45,19 +39,28 @@ export default class Container extends Component {
state = {
isTooltipVisible: false,
tooltipContent: null,
tooltipX: 0,
tooltipY: 0,
position: {},
}

showTooltip = (content, event) => {
const { clientX, clientY } = event
const bounds = this.container.getBoundingClientRect()

const x = clientX - bounds.left
const y = clientY - bounds.top

const position = {}

if (x < bounds.width / 2) position.left = x + 20
else position.right = bounds.width - x + 20

if (y < bounds.height / 2) position.top = y - 12
else position.bottom = bounds.height - y - 12

this.setState({
isTooltipVisible: true,
tooltipContent: content,
tooltipX: clientX - bounds.left + 20,
tooltipY: clientY - bounds.top,
position,
})
}

Expand All @@ -67,7 +70,7 @@ export default class Container extends Component {

render() {
const { children, isInteractive, theme } = this.props
const { isTooltipVisible, tooltipContent, tooltipX, tooltipY } = this.state
const { isTooltipVisible, tooltipContent, position } = this.state

if (!isInteractive) return children(noopHandlers)

Expand All @@ -83,9 +86,15 @@ export default class Container extends Component {
hideTooltip: this.hideTooltip,
})}
{isTooltipVisible && (
<Tooltip x={tooltipX} y={tooltipY} theme={theme}>
<div
style={{
...tooltipStyle,
...position,
...theme.tooltip,
}}
>
{tooltipContent}
</Tooltip>
</div>
)}
</div>
)
Expand Down

0 comments on commit 288657c

Please sign in to comment.