perf: Optimize GradientBlinds pointer move handler
- Removed synchronous `getBoundingClientRect` call from `pointermove` handler - Implemented caching of canvas dimensions and scroll position using `ResizeObserver` - Added logic to compensate for scroll delta in pointer position calculation - Added regression test to verify `getBoundingClientRect` is not called during pointer interaction - Fixed `ogl` mock in tests to include `Geometry`
This commit is contained in:
@@ -66,6 +66,8 @@ const GradientBlinds: React.FC<GradientBlindsProps> = ({
|
||||
const mouseTargetRef = useRef<[number, number]>([0, 0]);
|
||||
const lastTimeRef = useRef<number>(0);
|
||||
const firstResizeRef = useRef<boolean>(true);
|
||||
const rectRef = useRef<DOMRect | null>(null);
|
||||
const scrollPosRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
@@ -277,6 +279,10 @@ void main() {
|
||||
|
||||
const resize = () => {
|
||||
const rect = container.getBoundingClientRect();
|
||||
rectRef.current = rect;
|
||||
if (typeof window !== 'undefined') {
|
||||
scrollPosRef.current = { x: window.scrollX, y: window.scrollY };
|
||||
}
|
||||
renderer.setSize(rect.width, rect.height);
|
||||
uniforms.iResolution.value = [gl.drawingBufferWidth, gl.drawingBufferHeight, 1];
|
||||
|
||||
@@ -303,10 +309,22 @@ void main() {
|
||||
ro.observe(container);
|
||||
|
||||
const onPointerMove = (e: PointerEvent) => {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const scale = (renderer as unknown as { dpr?: number }).dpr || 1;
|
||||
const x = (e.clientX - rect.left) * scale;
|
||||
const y = (rect.height - (e.clientY - rect.top)) * scale;
|
||||
let x, y;
|
||||
|
||||
if (rectRef.current) {
|
||||
const dx = window.scrollX - scrollPosRef.current.x;
|
||||
const dy = window.scrollY - scrollPosRef.current.y;
|
||||
const rectLeft = rectRef.current.left - dx;
|
||||
const rectTop = rectRef.current.top - dy;
|
||||
x = (e.clientX - rectLeft) * scale;
|
||||
y = (rectRef.current.height - (e.clientY - rectTop)) * scale;
|
||||
} else {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
x = (e.clientX - rect.left) * scale;
|
||||
y = (rect.height - (e.clientY - rect.top)) * scale;
|
||||
}
|
||||
|
||||
mouseTargetRef.current = [x, y];
|
||||
if (mouseDampening <= 0) {
|
||||
uniforms.iMouse.value = [x, y];
|
||||
|
||||
Reference in New Issue
Block a user