-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathuseDetectWrap.ts
80 lines (67 loc) · 2.34 KB
/
useDetectWrap.ts
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { RefCallback, useCallback, useEffect, useRef, useState } from 'react'
export type UseDetectWrapReturn = {
containerRef: RefCallback<HTMLElement | null>
childRef: RefCallback<HTMLElement | null>
wrapped: boolean
}
/*
* This hook detects when the child falls below the top of the container. It is
* not wrapped when the top of the child is the same as the top of the
* container. This may be used, for example, to detect when a flex item wraps to
* the next line in a flex row container. See the `Spend` action component for
* example usage.
*
* To use it, add the refs to the `ref` property of the corresponding components
* in the caller. The `wrapped` value will be updated when the child wraps
* beneath the top of the container.
*/
export const useDetectWrap = (): UseDetectWrapReturn => {
const [wrapped, setWrapped] = useState(false)
// Detect when the recipient wraps to the next page to change arrow.
const [refSet, setRefSet] = useState(0)
const _containerRef = useRef<HTMLElement | null>(null)
const containerRef: RefCallback<HTMLElement> = useCallback((node) => {
_containerRef.current = node
setRefSet((refSet) => refSet + 1)
}, [])
const _childRef = useRef<HTMLElement | null>(null)
const childRef: RefCallback<HTMLElement> = useCallback((node) => {
_childRef.current = node
setRefSet((refSet) => refSet + 1)
}, [])
useEffect(() => {
if (typeof window === 'undefined') {
return
}
const updateWrap = () => {
if (!_containerRef.current || !_childRef.current) {
return
}
const containerTop = _containerRef.current.offsetTop
const childTop = _childRef.current.offsetTop
setWrapped(childTop > containerTop)
}
// Trigger initial set.
updateWrap()
// Observe changes to the container and child elements.
const observer = new ResizeObserver(updateWrap)
if (_containerRef.current) {
observer.observe(_containerRef.current)
}
if (_childRef.current) {
observer.observe(_childRef.current)
}
// Trigger re-render when window is resized.
window.addEventListener('resize', updateWrap)
return () => {
observer.disconnect()
window.removeEventListener('resize', updateWrap)
}
// Trigger re-render when refs are set.
}, [refSet])
return {
containerRef,
childRef,
wrapped,
}
}