Skip to content

Commit

Permalink
feat(HorizontalScroll): add scrollOnAnyWheel (#4390)
Browse files Browse the repository at this point in the history
- closed #4367
  • Loading branch information
SevereCloud authored Mar 9, 2023
1 parent 34c0481 commit a53d570
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
import * as React from 'react';
import { fireEvent, render } from '@testing-library/react';
import { baselineComponent } from '../../testing/utils';
import { HorizontalScroll } from './HorizontalScroll';

describe('HorizontalScroll', () => {
baselineComponent(HorizontalScroll);

it('scrollOnAnyWheel', () => {
const ref = React.createRef<HTMLDivElement>();
render(
<HorizontalScroll getRef={ref} scrollOnAnyWheel>
<div />
<div />
</HorizontalScroll>,
);

const scrollBy: Element['scrollBy'] = jest.fn();
ref.current!.scrollBy = scrollBy;

fireEvent.wheel(ref.current!, {
deltaX: 10,
deltaY: 10,
});

expect(scrollBy).toBeCalledTimes(1);
});
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { classNames } from '@vkontakte/vkjs';
import { classNames, noop } from '@vkontakte/vkjs';
import { useAdaptivityHasPointer } from '../../hooks/useAdaptivityHasPointer';
import { useEventListener } from '../../hooks/useEventListener';
import { useExternRef } from '../../hooks/useExternRef';
Expand Down Expand Up @@ -39,6 +39,11 @@ export interface HorizontalScrollProps
arrowSize?: 'm' | 'l';
showArrows?: boolean | 'always';
scrollAnimationDuration?: number;
/**
* Добавляет возможность прокручивать контент на любое колесо мыши.
* По умолчанию прокручивается как любой горизонтальный контент через shift.
*/
scrollOnAnyWheel?: boolean;
}

/**
Expand Down Expand Up @@ -131,6 +136,7 @@ export const HorizontalScroll = ({
scrollAnimationDuration = SCROLL_ONE_FRAME_TIME,
getRef,
className,
scrollOnAnyWheel = false,
...restProps
}: HorizontalScrollProps) => {
const [canScrollLeft, setCanScrollLeft] = React.useState(false);
Expand Down Expand Up @@ -199,6 +205,28 @@ export const HorizontalScroll = ({
}, [scrollEvent, scrollerRef]);
React.useEffect(onscroll, [scrollerRef, children, onscroll]);

/**
* Прокрутка с помощью любого колеса мыши
*/
const onwheel = React.useCallback(
(e: WheelEvent) => {
scrollerRef.current!.scrollBy({ left: e.deltaX + e.deltaY, behavior: 'auto' });
e.preventDefault();
},
[scrollerRef],
);

const wheelEvent = useEventListener('wheel', onwheel);
React.useEffect(() => {
if (!scrollerRef.current || !scrollOnAnyWheel) {
return noop;
}

wheelEvent.add(scrollerRef.current);

return wheelEvent.remove;
}, [wheelEvent, scrollerRef, scrollOnAnyWheel]);

return (
<div
{...restProps}
Expand Down

0 comments on commit a53d570

Please sign in to comment.