diff --git a/src/Preview.tsx b/src/Preview.tsx index cc975c93..92ef3cd7 100644 --- a/src/Preview.tsx +++ b/src/Preview.tsx @@ -15,7 +15,7 @@ import useFrameSetState from './hooks/useFrameSetState'; import getFixScaleEleTransPosition from './getFixScaleEleTransPosition'; import { context } from './PreviewGroup'; -const { useState } = React; +const { useState, useEffect } = React; interface PreviewProps extends Omit { onClose?: (e: React.SyntheticEvent) => void; @@ -55,6 +55,7 @@ const Preview: React.FC = props => { const currentPreviewIndex = previewUrlsKeys.indexOf(current); const combinationSrc = isPreviewGroup ? previewUrls.get(current) : src; const showLeftOrRightSwitches = isPreviewGroup && previewGroupCount > 1; + const [lastWheelZoomDirection, setLastWheelZoomDirection] = React.useState({ wheelDirection: 0 }); const onAfterClose = () => { setScale(1); @@ -176,12 +177,31 @@ const Preview: React.FC = props => { } }; - React.useEffect(() => { + const onWheelMove: React.WheelEventHandler = event => { + if (!visible) return; + event.preventDefault(); + const wheelDirection = event.deltaY; + setLastWheelZoomDirection({ wheelDirection }); + }; + + useEffect(() => { + const { wheelDirection } = lastWheelZoomDirection; + if (wheelDirection > 0) { + onZoomOut(); + } else if (wheelDirection < 0) { + onZoomIn(); + } + }, [lastWheelZoomDirection]); + + useEffect(() => { let onTopMouseUpListener; let onTopMouseMoveListener; const onMouseUpListener = addEventListener(window, 'mouseup', onMouseUp, false); const onMouseMoveListener = addEventListener(window, 'mousemove', onMouseMove, false); + const onScrollWheelListener = addEventListener(window, 'wheel', onWheelMove, { + passive: false, + }); try { // Resolve if in iframe lost event @@ -198,6 +218,7 @@ const Preview: React.FC = props => { return () => { onMouseUpListener.remove(); onMouseMoveListener.remove(); + onScrollWheelListener.remove(); /* istanbul ignore next */ if (onTopMouseUpListener) onTopMouseUpListener.remove(); diff --git a/tests/preview.test.tsx b/tests/preview.test.tsx index 30ac9ed0..05e1ac69 100644 --- a/tests/preview.test.tsx +++ b/tests/preview.test.tsx @@ -153,6 +153,28 @@ describe('Preview', () => { expect(wrapper.find('.rc-image-preview-img').prop('style')).toMatchObject({ transform: 'scale3d(1, 1, 1) rotate(0deg)', }); + + act(() => { + const wheelEvent = new Event('wheel'); + wheelEvent.deltaY = -50; + global.dispatchEvent(wheelEvent); + jest.runAllTimers(); + wrapper.update(); + }); + expect(wrapper.find('.rc-image-preview-img').prop('style')).toMatchObject({ + transform: 'scale3d(2, 2, 1) rotate(0deg)', + }); + + act(() => { + const wheelEvent = new Event('wheel'); + wheelEvent.deltaY = 50; + global.dispatchEvent(wheelEvent); + jest.runAllTimers(); + wrapper.update(); + }); + expect(wrapper.find('.rc-image-preview-img').prop('style')).toMatchObject({ + transform: 'scale3d(1, 1, 1) rotate(0deg)', + }); }); it('Mouse Event', () => {