Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ScrollLock): add useScrollingLockedScroll to scroll locked layout #8137

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
79 changes: 72 additions & 7 deletions packages/vkui/src/components/AppRoot/ScrollContext.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,33 +70,93 @@ describe(useScrollLock, () => {

clearWindowMeasuresMock();
});

test('context api', () => {
test.each([true, false])('context api with locked=%s', (locked) => {
const contextRef = createRef<ScrollContextInterface>();
render(
const Fixture = () => (
<GlobalScrollController elRef={createRef<HTMLElement>()}>
<ChildWithContext contextRef={contextRef} />
</GlobalScrollController>,
</GlobalScrollController>
);

const { rerender } = render(<Fixture />);

const clearWindowMeasuresMock = mockWindowMeasures(50, 50);
const clearElementScrollMock = mockElementScroll(document.body, 100, 100);
const clearMockWindowScrollToMock = mockWindowScrollTo();

if (locked) {
contextRef.current?.incrementScrollLockCounter();
rerender(<Fixture />);
}

expect(contextRef.current?.getScroll()).toEqual({ x: 0, y: 50 });
expect(contextRef.current?.getScroll({ compensateKeyboardHeight: false })).toEqual({
x: 0,
y: 0,
});
contextRef.current?.scrollTo(10, 10);
expect(contextRef.current?.getScroll()).toEqual({ x: 10, y: 60 });

if (locked) {
expect(getPositionOfBody()).toEqual([`-${10}px`, `-${10}px`]);
expect(window.pageYOffset).toBe(0);
} else {
expect(window.pageYOffset).toBe(10);
}
andrey-medvedev-vk marked this conversation as resolved.
Show resolved Hide resolved

contextRef.current?.scrollTo();
expect(contextRef.current?.getScroll()).toEqual({ x: 0, y: 50 });

clearWindowMeasuresMock();
clearElementScrollMock();
clearMockWindowScrollToMock();
});

test('scroll when not locked and then when locked', () => {
const contextRef = createRef<ScrollContextInterface>();
const Fixture = () => (
<GlobalScrollController elRef={createRef<HTMLElement>()}>
<ChildWithContext contextRef={contextRef} />
</GlobalScrollController>
);

const { rerender } = render(<Fixture />);

const clearWindowMeasuresMock = mockWindowMeasures(50, 50);
const clearElementScrollMock = mockElementScroll(document.body, 100, 100);
const clearMockWindowScrollToMock = mockWindowScrollTo();

// Скролим не залоченный скролл
contextRef.current?.scrollTo(10, 10);
expect(window.pageYOffset).toBe(10);
expect(window.pageXOffset).toBe(10);

// Блокируем скролл
contextRef.current?.incrementScrollLockCounter();
rerender(<Fixture />);

// Блокируем скролл - отступы остаются те же
expect(window.pageYOffset).toBe(10);
expect(window.pageXOffset).toBe(10);
expect(getPositionOfBody()).toEqual([`-${10}px`, `-${10}px`]);

// Скролим залоченный скролл
contextRef.current?.scrollTo(25, 25);

expect(getPositionOfBody()).toEqual([`-${25}px`, `-${25}px`]);

// Выключаем блокировку скролла
contextRef.current?.decrementScrollLockCounter();
rerender(<Fixture />);

// Отступы window должны пересчитаться
expect(window.pageYOffset).toBe(25);
expect(window.pageXOffset).toBe(25);

clearWindowMeasuresMock();
clearElementScrollMock();
clearMockWindowScrollToMock();
});
});

describe(ElementScrollController, () => {
Expand Down Expand Up @@ -222,6 +282,11 @@ function getStyleAttributeObject(el: HTMLElement | null) {
);
}

function getPositionOfBody() {
const styles = getStyleAttributeObject(document.body);
return styles && [styles.left, styles.top];
}

function mockWindowMeasures(width: number, height: number) {
const originalW = window.innerWidth;
const originalH = window.innerHeight;
Expand All @@ -237,9 +302,9 @@ function mockWindowScrollTo() {
const original = window.scrollTo;
Object.defineProperty(window, 'scrollTo', {
configurable: true,
value: (x: number, y: number) => {
Object.defineProperty(window, 'pageXOffset', { configurable: true, value: x });
Object.defineProperty(window, 'pageYOffset', { configurable: true, value: y });
value: ({ left, top }: { left: number; top: number }) => {
Object.defineProperty(window, 'pageXOffset', { configurable: true, value: left });
Object.defineProperty(window, 'pageYOffset', { configurable: true, value: top });
},
});
return function clearMock() {
Expand Down
87 changes: 63 additions & 24 deletions packages/vkui/src/components/AppRoot/ScrollContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@
});
};

const getPageYOffsetWithoutKeyboardHeight = (window: Window) => {
const getPageYOffsetWithoutKeyboardHeight = (window: Window, scrollTop: number) => {
// Note: здесь расчёт на то, что `clientHeight` равен `window.innerHeight`.
// Это достигается тем, что тегу `html` задали`height: 100%` и у него нет отступов сверху и снизу. Если есть отступы,
// то надо задать `box-sizing: border-box`, чтобы они не учитывались.
const diffOfClientHeightAndViewportHeight =
window.document.documentElement.clientHeight - window.innerHeight;
return window.pageYOffset - diffOfClientHeightAndViewportHeight;
return scrollTop - diffOfClientHeightAndViewportHeight;
};

export type GetScrollOptions = {
Expand Down Expand Up @@ -86,30 +86,69 @@
};
}

export function useScrollingLockedScroll(): Pick<ScrollContextInterface, 'scrollTo' | 'getScroll'> {
const { scrollTo, getScroll } = React.useContext(ScrollContext);
return React.useMemo(
() => ({

Check warning on line 92 in packages/vkui/src/components/AppRoot/ScrollContext.tsx

View check run for this annotation

Codecov / codecov/patch

packages/vkui/src/components/AppRoot/ScrollContext.tsx#L89-L92

Added lines #L89 - L92 were not covered by tests
scrollTo,
getScroll,
}),
[getScroll, scrollTo],
);
}

export interface ScrollControllerProps extends HasChildren {
elRef: React.RefObject<HTMLElement | null>;
}

export const GlobalScrollController = ({ children }: ScrollControllerProps): React.ReactNode => {
const { window, document } = useDOM();
const beforeScrollLockFnSetRef = React.useRef<Set<() => void>>(new Set());
const scrollLockEnabledRef = React.useRef(false);

const getScroll = React.useCallback<ScrollContextInterface['getScroll']>(
(options = { compensateKeyboardHeight: true }) => ({
x: window!.pageXOffset,
y: options.compensateKeyboardHeight
? getPageYOffsetWithoutKeyboardHeight(window!)
: window!.pageYOffset,
}),
[window],
(options = { compensateKeyboardHeight: true }) => {
if (!window) {
throw new Error('window is not defined');

Check warning on line 112 in packages/vkui/src/components/AppRoot/ScrollContext.tsx

View check run for this annotation

Codecov / codecov/patch

packages/vkui/src/components/AppRoot/ScrollContext.tsx#L112

Added line #L112 was not covered by tests
}
const bodyStyles = document!.body.style;
const [scrollLeft, scrollTop] = scrollLockEnabledRef.current
? [-parseFloat(bodyStyles.left || '0'), -parseFloat(bodyStyles.top || '0')]
: [window.pageXOffset, window.pageYOffset];
return {
x: scrollLeft,
y: options.compensateKeyboardHeight
? getPageYOffsetWithoutKeyboardHeight(window, scrollTop)
: scrollTop,
};
},
[document, window],
);
const scrollTo = React.useCallback<ScrollContextInterface['scrollTo']>(
(x = 0, y = 0) => {
if (!window || !document) {
return;

Check warning on line 130 in packages/vkui/src/components/AppRoot/ScrollContext.tsx

View check run for this annotation

Codecov / codecov/patch

packages/vkui/src/components/AppRoot/ScrollContext.tsx#L130

Added line #L130 was not covered by tests
}

// Some iOS versions do not normalize scroll — do it manually.
window!.scrollTo(
x ? clamp(x, 0, document!.body.scrollWidth - window!.innerWidth) : 0,
y ? clamp(y, 0, document!.body.scrollHeight - window!.innerHeight) : 0,
);
const clampX = (value: number) =>
value ? clamp(value, 0, document.body.scrollWidth - window.innerWidth) : 0;
const clampY = (value: number) =>
value ? clamp(value, 0, document.body.scrollHeight - window.innerHeight) : 0;

const [left, top] = [clampX(x), clampY(y)];

if (scrollLockEnabledRef.current) {
Object.assign(document.body.style, {
left: `-${left}px`,
top: `-${top}px`,
});
} else {
window.scrollTo({
left,
top,
});
}
},
[document, window],
);
Expand All @@ -118,32 +157,32 @@
beforeScrollLockFnSetRef.current.forEach((fn) => {
fn();
});

const scrollY = window!.pageYOffset;
const scrollX = window!.pageXOffset;
const { x: scrollX, y: scrollY } = getScroll({ compensateKeyboardHeight: false });
const overflowY = window!.innerWidth > document!.documentElement.clientWidth ? 'scroll' : '';
const overflowX = window!.innerHeight > document!.documentElement.clientHeight ? 'scroll' : '';

Object.assign(document!.documentElement.style, { overscrollBehavior: 'none' });
Object.assign(document!.body.style, {
position: 'fixed',
top: `-${scrollY}px`,
left: `-${scrollX}px`,
right: '0',
overscrollBehavior: 'none',
overflowY,
overflowX,
});
}, [document, window]);

const disableScrollLock = React.useCallback(() => {
const scrollY = document!.body.style.top;
const scrollX = document!.body.style.left;
scrollLockEnabledRef.current = true;

scrollTo(scrollX, scrollY);
}, [document, getScroll, scrollTo, window]);

const disableScrollLock = React.useCallback(() => {
const scrollData = getScroll({ compensateKeyboardHeight: false });
Object.assign(document!.documentElement.style, { overscrollBehavior: '' });
clearDisableScrollStyle(document!.body);
window!.scrollTo(-parseInt(scrollX || '0'), -parseInt(scrollY || '0'));
}, [document, window]);
scrollLockEnabledRef.current = false;

scrollTo(scrollData.x, scrollData.y);
}, [document, getScroll, scrollTo]);

const { incrementScrollLockCounter, decrementScrollLockCounter } = useScrollLockController(
enableScrollLock,
Expand Down
2 changes: 1 addition & 1 deletion packages/vkui/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ export { usePagination } from './hooks/usePagination';
export { type Orientation, useOrientationChange } from './hooks/useOrientationChange';
export { usePatchChildren } from './hooks/usePatchChildren';
export { useTodayDate } from './hooks/useTodayDate';
export { useScrollLock } from './components/AppRoot/ScrollContext';
export { useScrollLock, useScrollingLockedScroll } from './components/AppRoot/ScrollContext';
export { useNavTransition } from './components/NavTransitionContext/NavTransitionContext';
export { useNavDirection } from './components/NavTransitionDirectionContext/NavTransitionDirectionContext';
export { useNavId } from './components/NavIdContext/useNavId';
Expand Down
Loading