@redocly/theme
Version:
Shared UI components lib
41 lines (33 loc) • 1.26 kB
text/typescript
import { useEffect } from 'react';
export function useModalScrollLock(isOpen: boolean): void {
useEffect(() => {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return;
}
const { body, documentElement } = document;
const originalOverflow = body.style.overflow;
const originalPaddingRight = body.style.paddingRight;
const originalScrollbarWidth =
documentElement.style.getPropertyValue('--modal-scrollbar-width');
const restoreScrollState = () => {
body.style.overflow = originalOverflow;
body.style.paddingRight = originalPaddingRight;
if (originalScrollbarWidth) {
documentElement.style.setProperty('--modal-scrollbar-width', originalScrollbarWidth);
} else {
documentElement.style.removeProperty('--modal-scrollbar-width');
}
};
if (isOpen) {
const scrollbarWidth = window.innerWidth - documentElement.clientWidth;
body.style.overflow = 'hidden';
if (scrollbarWidth > 0) {
body.style.paddingRight = `${scrollbarWidth}px`;
documentElement.style.setProperty('--modal-scrollbar-width', `${scrollbarWidth}px`);
}
}
return () => {
restoreScrollState();
};
}, [isOpen]);
}