Skip to content

Commit 07e814a

Browse files
authored
brush: fix brush jumping around after mouseup (#1836)
1 parent 3044bc5 commit 07e814a

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

packages/visx-brush/src/BaseBrush.tsx

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import {
1515
BrushingType,
1616
BrushPageOffset,
1717
} from './types';
18-
import { getPageCoordinates } from './utils';
18+
import { debounce, getPageCoordinates } from './utils';
1919

2020
type PointerHandlerEvent = React.PointerEvent<SVGRectElement>;
2121

@@ -177,14 +177,14 @@ export default class BaseBrush extends React.Component<BaseBrushProps, BaseBrush
177177
componentDidMount() {
178178
if (this.props.useWindowMoveEvents) {
179179
window.addEventListener('mouseup', this.handleWindowPointerUp);
180-
window.addEventListener('mousemove', this.handleWindowPointerMove);
180+
window.addEventListener('mousemove', this.debouncedHandleWindowPointerMove);
181181
}
182182
}
183183

184184
componentWillUnmount() {
185185
if (this.props.useWindowMoveEvents) {
186186
window.removeEventListener('mouseup', this.handleWindowPointerUp);
187-
window.removeEventListener('mousemove', this.handleWindowPointerMove);
187+
window.removeEventListener('mousemove', this.debouncedHandleWindowPointerMove);
188188
}
189189
}
190190

@@ -320,6 +320,8 @@ export default class BaseBrush extends React.Component<BaseBrushProps, BaseBrush
320320
}
321321
};
322322

323+
debouncedHandleWindowPointerMove = debounce(this.handleWindowPointerMove, 1);
324+
323325
getExtent = (start: Partial<Point>, end: Partial<Point>) => {
324326
const { brushDirection, width, height } = this.props;
325327
const x0 = brushDirection === 'vertical' ? 0 : Math.min(start.x || 0, end.x || 0);

packages/visx-brush/src/utils.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,14 @@ export function getPageCoordinates(event: MouseTouchOrPointerEvent) {
6969
pageY: pointerEvent.pageY,
7070
};
7171
}
72+
73+
// Tweaked from https://dev.to/cantem/how-to-write-a-debounce-function-1bdf
74+
export function debounce<T extends Function>(func: T, delay: number): (...args: any[]) => void {
75+
let timeoutId: ReturnType<typeof setTimeout>;
76+
return function debouncedFn(this: unknown, ...args: unknown[]) {
77+
clearTimeout(timeoutId);
78+
timeoutId = setTimeout(() => {
79+
func.apply(this, args);
80+
}, delay);
81+
};
82+
}

0 commit comments

Comments
 (0)