Simple implementation of event handler throttling.
This commit is contained in:
1 parent
963f6037ca
commit
ab5c8ff6bb
3 files changed
+33
-24
No files matched your search
@@ -1,8 +1,7 @@
|
||||
import react, { useState } from 'react';
|
||||
import { throttle } from 'lodash';
|
||||
import { Point } from './types';
|
||||
import { handlersConfig } from './config';
|
||||
import './Handler.css';
|
||||
import { handlersConfig } from './config';
|
||||
|
||||
export interface HandlersProperties {
|
||||
/**Transform the map:
|
||||
@@ -44,7 +43,11 @@ export const Handlers: react.FC<HandlersProperties> = (
|
||||
const initialMouseState = {
|
||||
down: false,
|
||||
starting: { x: -1, y: -1 },
|
||||
timestamp: 0,
|
||||
};
|
||||
|
||||
const [mouseState, setMouseState] = useState(initialMouseState);
|
||||
|
||||
const mouseLeaveHandler = (event: any) => {
|
||||
genericHandler(event);
|
||||
setMouseState(initialMouseState);
|
||||
@@ -55,6 +58,7 @@ export const Handlers: react.FC<HandlersProperties> = (
|
||||
setMouseState({
|
||||
down: true,
|
||||
starting: { x: event.clientX, y: event.clientY },
|
||||
timestamp: 0,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -63,28 +67,33 @@ export const Handlers: react.FC<HandlersProperties> = (
|
||||
setMouseState(initialMouseState);
|
||||
};
|
||||
|
||||
const mouseMoveHandler = throttle((event: any) => {
|
||||
genericHandler(event);
|
||||
if (mouseState.down) {
|
||||
props.transformMap(
|
||||
{
|
||||
x: event.clientX - mouseState.starting.x,
|
||||
y: event.clientY - mouseState.starting.y,
|
||||
},
|
||||
null,
|
||||
null
|
||||
);
|
||||
setMouseState({
|
||||
down: true,
|
||||
starting: {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
},
|
||||
});
|
||||
const mouseMoveHandler = (event: any) => {
|
||||
if (
|
||||
mouseState.down &&
|
||||
Date.now() - mouseState.timestamp > handlersConfig.mouseMoveThrottleDelay
|
||||
) {
|
||||
genericHandler(event);
|
||||
if (mouseState.down) {
|
||||
props.transformMap(
|
||||
{
|
||||
x: event.clientX - mouseState.starting.x,
|
||||
y: event.clientY - mouseState.starting.y,
|
||||
},
|
||||
null,
|
||||
null
|
||||
);
|
||||
setMouseState({
|
||||
down: true,
|
||||
starting: {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
},
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}, handlersConfig.mouseMoveThrottleDelay);
|
||||
};
|
||||
|
||||
const [mouseState, setMouseState] = useState(initialMouseState);
|
||||
return (
|
||||
<div
|
||||
className='handler'
|
||||
|
||||
Reference in new issue
Block a user