Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 21 additions & 10 deletions packages/documentation-framework/hooks/useIsStuck.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,44 @@
import { useState, useLayoutEffect, useRef } from 'react';
import { useState, useEffect, useLayoutEffect, useRef } from 'react';

// The prerenderer provides a partial document shim but no createElement.
const useIsomorphicLayoutEffect =
typeof document !== 'undefined' && typeof document.createElement === 'function'
? useLayoutEffect
: useEffect;

export const useIsStuck = (stickyElementId) => {
const [isStuck, setIsStuck] = useState(false);
const prevIsStuck = useRef(false);

useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
const scrollElement = document.getElementById('ws-page-main');
const stickyElement = document.getElementById(stickyElementId);

if (!scrollElement || !stickyElement) {
if (prevIsStuck.current !== false) {
setIsStuck(false);
prevIsStuck.current = false;
}
prevIsStuck.current = false;
setIsStuck(false);
return;
}

const syncFromScroll = () => {
const newIsStuck = scrollElement.scrollTop >= stickyElement.offsetTop;
// Only update state if the value actually changed
// Compare rendered positions: offsetTop may be relative to a different
// ancestor than the scrolling page container.
const scrollportTop = scrollElement.getBoundingClientRect().top + scrollElement.clientTop;
const stickyTop = stickyElement.getBoundingClientRect().top;
const newIsStuck = stickyTop <= scrollportTop + 1;
if (prevIsStuck.current !== newIsStuck) {
setIsStuck(newIsStuck);
prevIsStuck.current = newIsStuck;
setIsStuck(newIsStuck);
}
};

syncFromScroll();
scrollElement.addEventListener('scroll', syncFromScroll, { passive: true });
return () => scrollElement.removeEventListener('scroll', syncFromScroll);
window.addEventListener('resize', syncFromScroll);
return () => {
scrollElement.removeEventListener('scroll', syncFromScroll);
window.removeEventListener('resize', syncFromScroll);
};
}, [stickyElementId]);

return isStuck;
Expand Down
Loading