-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
hooks.js
64 lines (56 loc) · 1.7 KB
/
hooks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* This file is part of the nivo project.
*
* Copyright 2016-present, Raphaël Benitte.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { useState, useContext, useCallback } from 'react'
import { tooltipContext } from './context'
export const useTooltipHandlers = container => {
const [state, setState] = useState({
isVisible: false,
content: null,
position: {},
})
const showTooltipAt = useCallback((content, [x, y], anchor) => {
setState({
isVisible: true,
position: [x, y],
anchor,
content,
})
}, [])
const showTooltipFromEvent = useCallback(
(content, event, anchor) => {
const bounds = container.current.getBoundingClientRect()
const x = event.clientX - bounds.left
const y = event.clientY - bounds.top
if (anchor === 'left' || anchor === 'right') {
if (x < bounds.width / 2) anchor = 'right'
else anchor = 'left'
}
setState({
isVisible: true,
position: [x, y],
anchor,
content,
})
},
[container]
)
const hideTooltip = useCallback(() => {
setState({ isVisible: false, content: null })
})
return {
showTooltipAt,
showTooltipFromEvent,
hideTooltip,
isTooltipVisible: state.isVisible,
tooltipPosition: state.position,
tooltipAnchor: state.anchor,
tooltipContent: state.content,
}
}
export const useTooltip = () => useContext(tooltipContext)