Skip to content

Commit

Permalink
restore scroll on clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
sirineJ committed Dec 22, 2024
1 parent a56459a commit 4440560
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
15 changes: 15 additions & 0 deletions packages/circuit-ui/hooks/useScrollLock/useScrollLock.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,19 @@ describe('useScrollLock', () => {
expect(document.body.style.top).toBe('');
expect(window.scrollTo).toHaveBeenCalledWith(0, 100);
});

it('unlocks the scroll when unmounted', () => {
window.scrollY = 100;

const { unmount } = renderHook(() => useScrollLock(true), {
initialProps: { isLocked: true },
});
expect(document.body.style.position).toBe('fixed');

unmount();

expect(document.body.style.position).toBe('');
expect(document.body.style.top).toBe('');
expect(window.scrollTo).toHaveBeenCalledWith(0, 100);
});
});
24 changes: 15 additions & 9 deletions packages/circuit-ui/hooks/useScrollLock/useScrollLock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,20 @@
* limitations under the License.
*/

import { useEffect, useRef } from 'react';
import { useCallback, useEffect, useRef } from 'react';

export const useScrollLock = (isLocked: boolean): void => {
const scrollValue = useRef<string>();

const restoreScroll = useCallback(() => {
// restore scroll to page
const { body } = document;
const scrollY = body.style.top;
body.style.position = '';
body.style.top = '';
body.style.width = '';
window.scrollTo(0, Number.parseInt(scrollY || '0', 10) * -1);
}, []);
useEffect(() => {
if (isLocked) {
scrollValue.current = `${window.scrollY}px`;
Expand All @@ -31,13 +40,10 @@ export const useScrollLock = (isLocked: boolean): void => {
body.style.width = `${bodyWidth}px`;
body.style.top = `-${scrollY}`;
} else {
// restore scroll to page
const { body } = document;
const scrollY = body.style.top;
body.style.position = '';
body.style.top = '';
body.style.width = '';
window.scrollTo(0, Number.parseInt(scrollY || '0', 10) * -1);
restoreScroll();
}
}, [isLocked]);
return () => {
restoreScroll();
};
}, [isLocked, restoreScroll]);
};

0 comments on commit 4440560

Please sign in to comment.