mirror of
https://github.com/supabase/supabase.git
synced 2026-10-08 10:55:06 +03:00
Co-authored-by: Kang Ming <kang.ming1996@gmail.com> Co-authored-by: Joel Lee <lee.yi.jie.joel@gmail.com>
54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
import { useCallback, useRef } from 'react'
|
|
import { useInView } from 'react-intersection-observer'
|
|
|
|
const useSticky = <Element extends HTMLElement>({
|
|
enabled = true,
|
|
style = {} as CSSStyleDeclaration,
|
|
}: {
|
|
enabled?: boolean
|
|
style?: CSSStyleDeclaration
|
|
} = {}) => {
|
|
const stickyRef = useRef<Element>(null)
|
|
|
|
const handleSticking = useCallback(
|
|
(inView: boolean) => {
|
|
if (!stickyRef.current) return
|
|
|
|
if (inView) {
|
|
stickyRef.current.style.position = 'sticky'
|
|
stickyRef.current.style.top = '100px'
|
|
stickyRef.current.style.zIndex = '5'
|
|
|
|
for (const property in style) {
|
|
// @ts-ignore
|
|
stickyRef.current.style[property] = style[property]
|
|
}
|
|
} else {
|
|
stickyRef.current.style.position = ''
|
|
stickyRef.current.style.top = ''
|
|
stickyRef.current.style.zIndex = ''
|
|
for (const property in style) {
|
|
// @ts-ignore
|
|
stickyRef.current.style[property] = ''
|
|
}
|
|
}
|
|
},
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
[JSON.stringify(style)]
|
|
)
|
|
|
|
const { ref: observedRef, inView } = useInView({
|
|
threshold: 0.1,
|
|
onChange: handleSticking,
|
|
skip: !enabled,
|
|
})
|
|
|
|
return {
|
|
inView,
|
|
observedRef,
|
|
stickyRef,
|
|
}
|
|
}
|
|
|
|
export { useSticky }
|