Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
20 changes: 19 additions & 1 deletion semcore/core/__tests__/usePreventScroll.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { cleanup, renderHook } from '@semcore/testing-utils/testing-library';
import { expect, test, describe, beforeEach, afterEach } from '@semcore/testing-utils/vitest';
import { expect, test, describe, beforeEach, afterEach, vi } from '@semcore/testing-utils/vitest';

import usePreventScroll from '../src/utils/use/usePreventScroll';

Expand Down Expand Up @@ -63,6 +63,24 @@ describe('usePreventScroll', () => {
expect(document.body.style.overflow).toBe('');
});

test.sequential.each(['hidden', 'clip'])(
'Verify skips locking when body overflow is already %s',
(overflow) => {
const spy = vi
.spyOn(window, 'getComputedStyle')
.mockReturnValue({ paddingRight: '0px', overflow } as CSSStyleDeclaration);

const { unmount } = renderHook(() => usePreventScroll(true));

expect(document.body.style.overflow).toBe('');
expect(document.body.style.paddingRight).toBe('');
expect(document.body.style.boxSizing).toBe('');

unmount();
spy.mockRestore();
},
);

test.sequential('Verify reacts to visible changing from true to false', () => {
const { rerender, unmount } = renderHook(({ visible }) => usePreventScroll(visible), {
initialProps: { visible: true },
Expand Down
6 changes: 5 additions & 1 deletion semcore/core/src/utils/use/usePreventScroll.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ const lockedBodyStyles = {
overflow: '',
boxSizing: '',
};

const overflowValuesToSkip = new Set<string>(['clip', 'hidden']);
export default function usePreventScroll(visible = true, disabled = false) {
const scrollbarWidth = React.useMemo(getScrollbarWidth, [getScrollbarWidth]);
const id = useUID('scroll-preventer-');
Expand All @@ -46,12 +48,14 @@ export default function usePreventScroll(visible = true, disabled = false) {
scrollPreventers.add(id);
if (scrollPreventers.size > 1) return;

const { paddingRight } = window.getComputedStyle(document.body);
const { paddingRight, overflow } = window.getComputedStyle(document.body);

lockedBodyStyles.paddingRight = document.body.style.paddingRight;
lockedBodyStyles.overflow = document.body.style.overflow;
lockedBodyStyles.boxSizing = document.body.style.boxSizing;

if (overflowValuesToSkip.has(overflow)) return;

const intPaddingRight = getIntValueFromCss(paddingRight);
let intPaddingRightFromStyle = getIntValueFromCss(document.body.style.paddingRight);
// Detected own style for window inside window
Expand Down
Loading