feat(SW-650): added sitewide alert to use sticky position hook

This commit is contained in:
Erik Tiekstra
2024-10-24 10:23:19 +02:00
parent 63dbbac014
commit fbdfeafcb5
7 changed files with 87 additions and 23 deletions

View File

@@ -6,12 +6,17 @@ import useStickyPositionStore, {
StickyElementNameEnum,
} from "@/stores/sticky-position"
import { debounce } from "@/utils/debounce"
interface UseStickyPositionProps {
ref?: React.RefObject<HTMLElement>
name?: StickyElementNameEnum
group?: string
}
// Global singleton ResizeObserver to observe the body only once
let resizeObserver: ResizeObserver | null = null
/**
* Custom hook to manage sticky positioning of elements within a page.
* This hook registers an element as sticky, calculates its top offset based on
@@ -83,6 +88,25 @@ export default function useStickyPosition({
}
}, [stickyElements, ref])
useEffect(() => {
if (!resizeObserver) {
const debouncedResizeHandler = debounce(() => {
updateHeights()
}, 100)
resizeObserver = new ResizeObserver(debouncedResizeHandler)
console.log("Initialized ResizeObserver")
}
resizeObserver.observe(document.body)
return () => {
if (resizeObserver) {
resizeObserver.unobserve(document.body)
}
}
}, [updateHeights])
return {
currentHeight: ref?.current?.offsetHeight || null,
allElements: getAllElements(),