UNPKG

@atlaskit/drawer

Version:

A drawer is a panel that slides in from the left side of the screen.

52 lines (50 loc) • 2 kB
import { useCallback, useEffect, useLayoutEffect, useState } from 'react'; import { bind } from 'bind-event-listener'; import { fg } from '@atlaskit/platform-feature-flags/fg'; /** * Returns how far the body is scrolled from the top of the viewport. * * ⚠️ This is copied from `packages/design-system/modal-dialog/src/internal/hooks/use-prevent-programmatic-scroll.tsx` * * ____ * ||____|| <-- overflow * | | <-- viewport * |____| * * Scroll distance is the height of overflow outside the viewport. */ function getScrollDistance() { var _document$documentEle, _document$body; return window.pageYOffset || ((_document$documentEle = document.documentElement) === null || _document$documentEle === void 0 ? void 0 : _document$documentEle.scrollTop) || ((_document$body = document.body) === null || _document$body === void 0 ? void 0 : _document$body.scrollTop) || 0; } /** * Prevents programmatic scrolling of the viewport with `scrollIntoView`. * Should be used in conjunction with a scroll lock to prevent a user from scrolling. * * ⚠️ This is copied from `packages/design-system/modal-dialog/src/internal/hooks/use-prevent-programmatic-scroll.tsx` * * @returns scroll top offset of the viewport */ export default function usePreventProgrammaticScroll() { const [scrollTopOffset, setScrollTopOffset] = useState(0); useLayoutEffect(() => { setScrollTopOffset(getScrollDistance()); }, []); const onWindowScroll = useCallback(() => { if (getScrollDistance() !== scrollTopOffset) { window.scrollTo(window.pageXOffset, scrollTopOffset); } }, [scrollTopOffset]); useEffect(() => { // The top-layer drawer relies on native modality + `DialogScrollLock`; the // programmatic-scroll guard is intentionally dropped under the flag. if (fg('platform-dst-top-layer')) { return; } return bind(window, { type: 'scroll', listener: onWindowScroll }); }, [onWindowScroll]); return scrollTopOffset; }