diff --git a/packages/graphics/src/components/stage/index.jsx b/packages/graphics/src/components/stage/index.jsx index 3225bf2..545bc59 100644 --- a/packages/graphics/src/components/stage/index.jsx +++ b/packages/graphics/src/components/stage/index.jsx @@ -21,54 +21,52 @@ const Stage = forwardRef(({ ticker, }, fref) => { const hostRef = useRef(); + const normalizeDeltaAndPosition = (event) => { + let { + clientX, + clientY, + deltaX, + deltaY, + } = event; + /* eslint-disable no-param-reassign */ + if (-1 !== ['touchstart', 'touchmove'].indexOf(event.type)) { + clientX = event.touches[0].clientX; + deltaX = event.touches[0].deltaX; + clientY = event.touches[0].clientY; + deltaY = event.touches[0].deltaY; + } + /* eslint-enable no-param-reassign */ + const {left, top} = event.target.getBoundingClientRect(); + Object.defineProperty( + event, + 'delta', + {get: () => [deltaX, deltaY]}, + ); + Object.defineProperty( + event, + 'position', + {get: () => [(clientX - left) / scale, (clientY - top) / scale]}, + ); + return event; + }; useImperativeHandle(fref, () => ({ events: () => K.merge( - [ - 'click', - 'mousemove', - 'mouseout', - 'mousedown', - 'mouseup', - 'touchend', - 'touchmove', - 'touchstart', - 'wheel', - ] - .map((event) => ( - K.fromEvents( - renderer.element, - event, - // Normalize touch events. - (event) => { - let { - clientX, - clientY, - deltaX, - deltaY, - } = event; - /* eslint-disable no-param-reassign */ - if (-1 !== ['touchstart', 'touchmove'].indexOf(event.type)) { - clientX = event.touches[0].clientX; - deltaX = event.touches[0].deltaX; - clientY = event.touches[0].clientY; - deltaY = event.touches[0].deltaY; + [].concat( + ['touchmove', 'touchstart', 'wheel'] + .map((event) => ( + K.stream((emitter) => { + const handler = (event) => { + emitter.emit(normalizeDeltaAndPosition(event)); + }; + renderer.element.addEventListener(event, handler, {passive: true}); + return () => { + renderer.element.removeEventListener(event, handler); } - /* eslint-enable no-param-reassign */ - const {left, top} = event.target.getBoundingClientRect(); - Object.defineProperty( - event, - 'delta', - {get: () => [deltaX, deltaY]}, - ); - Object.defineProperty( - event, - 'position', - {get: () => [(clientX - left) / scale, (clientY - top) / scale]}, - ); - return event; - }, - ) - )), + }) + )), + ['click', 'mousemove', 'mouseout', 'mousedown', 'mouseup', 'touchend'] + .map((event) => K.fromEvents(renderer.element, event, normalizeDeltaAndPosition)), + ), ), })); useEffect(() => {