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(zoom): Allow custom gesture handlers #1846

Open
wants to merge 1 commit 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
75 changes: 44 additions & 31 deletions packages/visx-zoom/src/Zoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
ScaleSignature,
ProvidedZoom,
PinchDelta,
CreateGestureHandlers,
} from './types';

// default prop values
Expand All @@ -38,6 +39,40 @@ const defaultPinchDelta: PinchDelta = ({ offset: [s], lastOffset: [lastS] }) =>
scaleY: s - lastS < 0 ? 0.9 : 1.1,
});

const defaultCreateGestureHandlers: CreateGestureHandlers = <ElementType,>({
dragStart,
dragEnd,
dragMove,
handlePinch,
handleWheel,
}: ProvidedZoom<ElementType>) => ({
onDragStart: ({ event }) => {
if (!(event instanceof KeyboardEvent)) dragStart(event);
},
onDrag: ({ event, pinching, cancel }) => {
if (pinching) {
cancel();
dragEnd();
} else if (!(event instanceof KeyboardEvent)) {
dragMove(event);
}
},
onDragEnd: dragEnd,
onPinch: handlePinch,
onWheel: ({ event, active, pinching }) => {
if (
// Outside of Safari, the wheel event is fired together with the pinch event
pinching ||
// currently onWheelEnd emits one final wheel event which causes 2x scale
// updates for the last tick. ensuring that the gesture is active avoids this
!active
) {
return;
}
handleWheel(event);
},
});

export type ZoomProps<ElementType> = {
/** Width of the zoom container. */
width: number;
Expand Down Expand Up @@ -94,6 +129,8 @@ export type ZoomProps<ElementType> = {
/** Initial transform matrix to apply. */
initialTransformMatrix?: TransformMatrix;
children: (zoom: ProvidedZoom<ElementType> & ZoomState) => React.ReactElement;
/** A function that returns gesture handlers for managing UI interactions */
createGestureHandlers?: CreateGestureHandlers;
};

type ZoomState = {
Expand All @@ -114,6 +151,7 @@ function Zoom<ElementType extends Element>({
height,
constrain,
children,
createGestureHandlers = defaultCreateGestureHandlers,
}: ZoomProps<ElementType>): React.ReactElement {
const containerRef = useRef<ElementType>(null);
const matrixStateRef = useRef<TransformMatrix>(initialTransformMatrix);
Expand Down Expand Up @@ -312,37 +350,6 @@ function Zoom<ElementType extends Element>({
setTransformMatrix(identityMatrix());
}, [setTransformMatrix]);

useGesture(
{
onDragStart: ({ event }) => {
if (!(event instanceof KeyboardEvent)) dragStart(event);
},
onDrag: ({ event, pinching, cancel }) => {
if (pinching) {
cancel();
dragEnd();
} else if (!(event instanceof KeyboardEvent)) {
dragMove(event);
}
},
onDragEnd: dragEnd,
onPinch: handlePinch,
onWheel: ({ event, active, pinching }) => {
if (
// Outside of Safari, the wheel event is fired together with the pinch event
pinching ||
// currently onWheelEnd emits one final wheel event which causes 2x scale
// updates for the last tick. ensuring that the gesture is active avoids this
!active
) {
return;
}
handleWheel(event);
},
},
{ target: containerRef, eventOptions: { passive: false }, drag: { filterTaps: true } },
);

const zoom: ProvidedZoom<ElementType> & ZoomState = {
initialTransformMatrix,
transformMatrix,
Expand All @@ -368,6 +375,12 @@ function Zoom<ElementType extends Element>({
containerRef,
};

useGesture(createGestureHandlers(zoom), {
target: containerRef,
eventOptions: { passive: false },
drag: { filterTaps: true },
});

return <>{children(zoom)}</>;
}

Expand Down
12 changes: 11 additions & 1 deletion packages/visx-zoom/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { UserHandlers, WebKitGestureEvent, Handler } from '@use-gesture/react';
import {
UserHandlers,
WebKitGestureEvent,
Handler,
GestureHandlers,
EventTypes,
} from '@use-gesture/react';
import {
RefObject,
MouseEvent as ReactMouseEvent,
Expand Down Expand Up @@ -46,6 +52,10 @@ export interface ScaleSignature {
point?: Point;
}

export type CreateGestureHandlers = <ElementType>(
zoom: ProvidedZoom<ElementType>,
) => GestureHandlers<EventTypes>;

export interface ProvidedZoom<ElementType> {
/** Sets translateX/Y to the center defined by width and height. */
center: () => void;
Expand Down
31 changes: 27 additions & 4 deletions packages/visx-zoom/test/Zoom.test.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import React from 'react';
import { render } from 'enzyme';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Zoom, inverseMatrix } from '../src';
import { CreateGestureHandlers } from '../lib/types';

describe('<Zoom />', () => {
it('should be defined', () => {
expect(Zoom).toBeDefined();
});

it('should render the children and pass zoom params', () => {
const initialTransform = {
scaleX: 1.27,
Expand All @@ -16,7 +19,7 @@ describe('<Zoom />', () => {
skewY: 0,
};

const wrapper = render(
render(
<Zoom
width={400}
height={400}
Expand All @@ -28,12 +31,32 @@ describe('<Zoom />', () => {
>
{({ transformMatrix }) => {
const { scaleX, scaleY, translateX, translateY } = transformMatrix;
return <div>{[scaleX, scaleY, translateX, translateY].join(',')}</div>;
return (
<div data-testid="zoom-child">{[scaleX, scaleY, translateX, translateY].join(',')}</div>
);
}}
</Zoom>,
);
expect(screen.getByTestId('zoom-child').innerHTML).toBe('1.27,1.27,-211.62,162.59');
});
it('should accept custom gesture handlers', () => {
const onClick = jest.fn();

const createGestureHandlers: CreateGestureHandlers = () => ({ onClick });

render(
<Zoom<HTMLButtonElement>
width={400}
height={400}
createGestureHandlers={createGestureHandlers}
>
{({ containerRef }) => <button type="button" ref={containerRef} />}
</Zoom>,
);

expect(wrapper.html()).toBe('1.27,1.27,-211.62,162.59');
const button = screen.getByRole('button');
userEvent.click(button);
expect(onClick.mock.calls).toHaveLength(1);
});
});

Expand Down
Loading