Skip to content

Commit

Permalink
brush: fix brush jumping around after mouseup (#1836)
Browse files Browse the repository at this point in the history
  • Loading branch information
tfineberg4 committed May 24, 2024
1 parent 3044bc5 commit 07e814a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
8 changes: 5 additions & 3 deletions packages/visx-brush/src/BaseBrush.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
BrushingType,
BrushPageOffset,
} from './types';
import { getPageCoordinates } from './utils';
import { debounce, getPageCoordinates } from './utils';

type PointerHandlerEvent = React.PointerEvent<SVGRectElement>;

Expand Down Expand Up @@ -177,14 +177,14 @@ export default class BaseBrush extends React.Component<BaseBrushProps, BaseBrush
componentDidMount() {
if (this.props.useWindowMoveEvents) {
window.addEventListener('mouseup', this.handleWindowPointerUp);
window.addEventListener('mousemove', this.handleWindowPointerMove);
window.addEventListener('mousemove', this.debouncedHandleWindowPointerMove);
}
}

componentWillUnmount() {
if (this.props.useWindowMoveEvents) {
window.removeEventListener('mouseup', this.handleWindowPointerUp);
window.removeEventListener('mousemove', this.handleWindowPointerMove);
window.removeEventListener('mousemove', this.debouncedHandleWindowPointerMove);
}
}

Expand Down Expand Up @@ -320,6 +320,8 @@ export default class BaseBrush extends React.Component<BaseBrushProps, BaseBrush
}
};

debouncedHandleWindowPointerMove = debounce(this.handleWindowPointerMove, 1);

getExtent = (start: Partial<Point>, end: Partial<Point>) => {
const { brushDirection, width, height } = this.props;
const x0 = brushDirection === 'vertical' ? 0 : Math.min(start.x || 0, end.x || 0);
Expand Down
11 changes: 11 additions & 0 deletions packages/visx-brush/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,14 @@ export function getPageCoordinates(event: MouseTouchOrPointerEvent) {
pageY: pointerEvent.pageY,
};
}

// Tweaked from https://dev.to/cantem/how-to-write-a-debounce-function-1bdf
export function debounce<T extends Function>(func: T, delay: number): (...args: any[]) => void {
let timeoutId: ReturnType<typeof setTimeout>;
return function debouncedFn(this: unknown, ...args: unknown[]) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}

0 comments on commit 07e814a

Please sign in to comment.