@@ -18,13 +18,68 @@ export const getMinWidth = (element, maxWidth) => {
18
18
return Math . round ( Math . min ( maxWidth , contentWidth || maxWidth ) ) ;
19
19
} ;
20
20
21
- export const isInViewport = ( element ) => {
21
+ export const isElementInViewport = ( element , container = null , position ) => {
22
22
const rect = element . getBoundingClientRect ( ) ;
23
+ const viewportWidth = window . innerWidth || document . documentElement . clientWidth ;
24
+ const viewportHeight = window . innerHeight || document . documentElement . clientHeight ;
23
25
24
- return (
25
- rect . top >= 0 &&
26
- rect . left >= 0 &&
27
- rect . bottom <= ( window . innerHeight || document . documentElement . clientHeight ) &&
28
- rect . right <= ( window . innerWidth || document . documentElement . clientWidth )
26
+ let isInsideViewport = (
27
+ rect . bottom > 0 &&
28
+ rect . top < viewportHeight &&
29
+ rect . right > 0 &&
30
+ rect . left < viewportWidth
29
31
) ;
32
+
33
+ if ( container ) {
34
+ const containerRect = container . getBoundingClientRect ( ) ;
35
+
36
+ if ( position === 'top' || position === 'bottom' ) {
37
+ isInsideViewport = (
38
+ ( containerRect . bottom + containerRect . height ) < viewportHeight &&
39
+ containerRect . top < viewportHeight
40
+ ) ;
41
+ } else {
42
+ isInsideViewport = (
43
+ ( containerRect . right + containerRect . width ) < viewportWidth &&
44
+ containerRect . left < viewportWidth
45
+ ) ;
46
+ }
47
+
48
+ return isInsideViewport ;
49
+ }
50
+
51
+ return isInsideViewport ;
52
+ } ;
53
+
54
+ export const computeTooltipPosition = ( containerRef , tooltipRef , position , coords ) => {
55
+ if ( ! containerRef || ! tooltipRef ) {
56
+ return coords ;
57
+ }
58
+
59
+ const containerRect = containerRef . getBoundingClientRect ( ) ;
60
+ const tooltipRect = tooltipRef . getBoundingClientRect ( ) ;
61
+
62
+ switch ( position ) {
63
+ case 'top' :
64
+ coords . top = containerRect . top ;
65
+ coords . left = containerRect . left + ( containerRect . width / 2 ) ;
66
+ break ;
67
+ case 'bottom' :
68
+ coords . top = containerRect . top - tooltipRect . height ;
69
+ coords . left = containerRect . left + ( containerRect . width / 2 ) ;
70
+ break ;
71
+ case 'left' :
72
+ coords . left = containerRect . left ;
73
+ coords . top = containerRect . top + ( containerRect . height / 2 ) ;
74
+ break ;
75
+ case 'right' :
76
+ coords . left = containerRect . right - tooltipRect . width ;
77
+ coords . top = containerRect . top + ( containerRect . height / 2 ) ;
78
+ break ;
79
+ }
80
+
81
+ coords . top += window . scrollY ;
82
+ coords . left += window . scrollX ;
83
+
84
+ return coords ;
30
85
} ;
0 commit comments