Merge pull request #15 from ragusa-it/perf-gradient-blinds-reflow-11693170314543928560

 Optimize GradientBlinds pointer move handler
This commit was merged in pull request #15.
This commit is contained in:
Melvin Ragusa
2026-01-24 11:18:57 +01:00
committed by GitHub
2 changed files with 53 additions and 3 deletions

View File

@@ -22,6 +22,9 @@ vi.mock('ogl', () => {
Mesh: class {
remove() {}
},
Geometry: class {
remove() {}
},
Triangle: class {
remove() {}
},
@@ -129,4 +132,33 @@ describe('GradientBlinds', () => {
unmount();
expect(disconnectSpy).toHaveBeenCalled();
});
it('minimizes getBoundingClientRect calls during pointer move', () => {
const { unmount } = render(<GradientBlinds />);
// Spy on getBoundingClientRect
// Note: In jsdom, canvas is an HTMLCanvasElement which inherits from HTMLElement
const spy = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect');
// Trigger pointer move to clear any initial calls or verify baseline
// The initial render calls resize(), which calls getBoundingClientRect on container
// Clear spy history from initial render
spy.mockClear();
act(() => {
const event = new PointerEvent('pointermove', {
clientX: 200,
clientY: 200,
bubbles: true,
});
window.dispatchEvent(event);
});
// EXPECTATION: It should NOT be called.
// This will fail currently.
expect(spy).not.toHaveBeenCalled();
unmount();
});
});

View File

@@ -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];